context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System.Diagnostics;
using System.Reflection;
namespace System.Management.Automation.Interpreter
{
internal abstract class MulInstruction : Instruction
{
private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double;
public override int ConsumedStack { get { return 2; } }
public override int ProducedStack { get { return 1; } }
private MulInstruction()
{
}
internal sealed class MulInt32 : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l * (Int32)r));
frame.StackIndex--;
return +1;
}
}
internal sealed class MulInt16 : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Int16)unchecked((Int16)l * (Int16)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulInt64 : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Int64)unchecked((Int64)l * (Int64)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulUInt16 : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (UInt16)unchecked((UInt16)l * (UInt16)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulUInt32 : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (UInt32)unchecked((UInt32)l * (UInt32)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulUInt64 : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (UInt64)unchecked((Int16)l * (Int16)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulSingle : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulDouble : MulInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r;
frame.StackIndex--;
return +1;
}
}
public static Instruction Create(Type type)
{
Debug.Assert(!type.GetTypeInfo().IsEnum);
switch (type.GetTypeCode())
{
case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulInt16());
case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulInt32());
case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulInt64());
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16());
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32());
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64());
case TypeCode.Single: return s_single ?? (s_single = new MulSingle());
case TypeCode.Double: return s_double ?? (s_double = new MulDouble());
default:
throw Assert.Unreachable;
}
}
public override string ToString()
{
return "Mul()";
}
}
internal abstract class MulOvfInstruction : Instruction
{
private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double;
public override int ConsumedStack { get { return 2; } }
public override int ProducedStack { get { return 1; } }
private MulOvfInstruction()
{
}
internal sealed class MulOvfInt32 : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l * (Int32)r));
frame.StackIndex--;
return +1;
}
}
internal sealed class MulOvfInt16 : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Int16)checked((Int16)l * (Int16)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulOvfInt64 : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Int64)checked((Int64)l * (Int64)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulOvfUInt16 : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (UInt16)checked((UInt16)l * (UInt16)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulOvfUInt32 : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (UInt32)checked((UInt32)l * (UInt32)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulOvfUInt64 : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (UInt64)checked((Int16)l * (Int16)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulOvfSingle : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Single)((Single)l * (Single)r);
frame.StackIndex--;
return +1;
}
}
internal sealed class MulOvfDouble : MulOvfInstruction
{
public override int Run(InterpretedFrame frame)
{
object l = frame.Data[frame.StackIndex - 2];
object r = frame.Data[frame.StackIndex - 1];
frame.Data[frame.StackIndex - 2] = (Double)l * (Double)r;
frame.StackIndex--;
return +1;
}
}
public static Instruction Create(Type type)
{
Debug.Assert(!type.GetTypeInfo().IsEnum);
switch (type.GetTypeCode())
{
case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulOvfInt16());
case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulOvfInt32());
case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulOvfInt64());
case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16());
case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32());
case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64());
case TypeCode.Single: return s_single ?? (s_single = new MulOvfSingle());
case TypeCode.Double: return s_double ?? (s_double = new MulOvfDouble());
default:
throw Assert.Unreachable;
}
}
public override string ToString()
{
return "MulOvf()";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.FSharp.Core.CompilerServices;
namespace TypeProviderInCSharp
{
public class ArtificialType : Type
{
string _Namespace;
string _Name;
bool _IsGenericType;
bool _IsValueType; // value type = not class / not interface
bool _IsByRef; // is the value passed by reference?
bool _IsEnum;
bool _IsPointer;
Type _BaseType;
MethodInfo _Method1;
PropertyInfo _Property1;
EventInfo _Event1;
FieldInfo _Field1;
ConstructorInfo _Ctor1;
public ArtificialType(string @namespace, string name, bool isGenericType, Type basetype, bool isValueType, bool isByRef, bool isEnum, bool IsPointer)
{
_Name = name;
_Namespace = @namespace;
_IsGenericType = isGenericType;
_BaseType = basetype;
_IsValueType = isValueType;
_IsByRef = isByRef;
_IsEnum = isEnum;
_IsPointer = IsPointer;
_Method1 = new ArtificialMethodInfo("M", this, typeof(int[]), MethodAttributes.Public | MethodAttributes.Static);
_Property1 = new ArtificialPropertyInfo("StaticProp", this, typeof(decimal), true, false);
_Event1 = new ArtificalEventInfo("Event1", this, typeof(EventHandler));
_Ctor1 = new ArtificialConstructorInfo(this, new ParameterInfo[] {} ); // parameter-less ctor
}
public override System.Reflection.Assembly Assembly
{
get
{
return Assembly.GetExecutingAssembly();
}
}
public override string Name
{
get
{
return _Name;
}
}
public override Type BaseType
{
get
{
return _BaseType;
}
}
public override string Namespace
{
get
{
return _Namespace;
}
}
public override string FullName
{
get
{
return string.Format("{0}.{1}", _Namespace, _Name);
}
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
Debug.Assert(false, "Why are we calling into GetCustomAttributes()?");
return null;
}
public override object[] GetCustomAttributes(bool inherit)
{
Debug.Assert(false, "Why are we calling into GetCustomAttributes()?");
return null;
}
// TODO: what is this?
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl()
{
return TypeAttributes.Class | TypeAttributes.Public | (TypeAttributes)0x40000000; // add the special flag to indicate an erased type, see TypeProviderTypeAttributes
}
// This one seems to be invoked when in IDE, I type something like:
// let _ = typeof<N.
// In this case => no constructors
public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
if (_Ctor1!=null)
return new System.Reflection.ConstructorInfo[] { _Ctor1 };
else
return new System.Reflection.ConstructorInfo[] { };
}
// When you start typing more interesting things like...
// let a = N.T.M()
// this one gets invoked...
public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new[] { _Method1 };
}
// This method is called when in the source file we have something like:
// - N.T.StaticProp
// (most likely also when we have an instance prop...)
// name -> "StaticProp"
protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
Debug.Assert(binder == null && returnType == null && types == null && modifiers == null, "One of binder, returnType, types, or modifiers was not null");
if (name == _Property1.Name)
return _Property1;
else
return null;
}
// Advertise our property...
// I think that is this one returns an empty array => you don't get intellisense/autocomplete in IDE/FSI
public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new PropertyInfo[] { _Property1 };
}
// No fields...
public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return null;
}
public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new System.Reflection.FieldInfo[] { };
}
// Events
public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
if (_Event1 != null && _Event1.Name == name)
return _Event1;
else
return null;
}
// Events...
public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr)
{
return _Event1 != null ? new [] { _Event1 } : new System.Reflection.EventInfo[] { };
}
// TODO: according to the spec, this should not be invoked... instead it seems like it may be invoked...
// ?? I have no idea what this is used for... ??
public override Type UnderlyingSystemType
{
get
{
return null;
}
}
// According to the spec, this should always be 'false'
protected override bool IsArrayImpl()
{
return false;
}
// No interfaces...
public override Type[] GetInterfaces()
{
return new Type[] { };
}
// No nested type
// This method is invoked on the type 'T', e.g.:
// let _ = N.T.M
// to figure out if M is a nested type.
public override Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr)
{
return null;
}
public override Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new Type[] { };
}
// This one is invoked when the type has a .ctor
// and the code looks like
// let _ = new N.T()
// for example.
// It was observed that the
// TODO: cover both cases!
public override bool IsGenericType
{
get
{
return _IsGenericType;
}
}
// This is invoked if the IsGenericType is true
public override Type[] GetGenericArguments()
{
if (_IsGenericType)
return new Type[] { typeof(int), typeof(decimal), typeof(System.Guid) }; // This is currently triggering an ICE...
else
{
Debug.Assert(false, "Why are we here?");
throw new NotImplementedException();
}
}
// This one seems to be invoked when compiling something like
// let a = new N.T()
// Let's just stay away from generics...
public override bool IsGenericTypeDefinition
{
get
{
return _IsGenericType;
}
}
// This one seems to be invoked when compiling something like
// let a = new N.T()
// Let's just stay away from generics...
public override bool ContainsGenericParameters
{
get
{
return _IsGenericType;
}
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsValueTypeImpl()
{
return _IsValueType;
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsByRefImpl()
{
return _IsByRef;
}
// This one seems to be checked when in IDE.
// let b = N.T(
public override bool IsEnum
{
get
{
return _IsEnum;
}
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsPointerImpl()
{
return _IsPointer;
}
public override string AssemblyQualifiedName
{
get
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override Guid GUID
{
get
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type GetElementType()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type GetInterface(string name, bool ignoreCase)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool HasElementTypeImpl()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool IsCOMObjectImpl()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool IsPrimitiveImpl()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override System.Reflection.Module Module
{
get {
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override bool IsDefined(Type attributeType, bool inherit)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override MethodBase DeclaringMethod
{
get
{
Debug.Assert(false, "NYI");
return base.DeclaringMethod;
}
}
// This one is invoked by the F# compiler!
public override Type DeclaringType
{
get
{
return null; // base.DeclaringType;
}
}
public override Type[] FindInterfaces(TypeFilter filter, object filterCriteria)
{
Debug.Assert(false, "NYI");
return base.FindInterfaces(filter, filterCriteria);
}
public override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria)
{
Debug.Assert(false, "NYI");
return base.FindMembers(memberType, bindingAttr, filter, filterCriteria);
}
public override GenericParameterAttributes GenericParameterAttributes
{
get
{
Debug.Assert(false, "NYI");
return base.GenericParameterAttributes;
}
}
public override int GenericParameterPosition
{
get
{
Debug.Assert(false, "NYI");
return base.GenericParameterPosition;
}
}
public override int GetArrayRank()
{
Debug.Assert(false, "NYI");
return base.GetArrayRank();
}
public override MemberInfo[] GetDefaultMembers()
{
Debug.Assert(false, "NYI");
return base.GetDefaultMembers();
}
public override string GetEnumName(object value)
{
Debug.Assert(false, "NYI");
return base.GetEnumName(value);
}
public override string[] GetEnumNames()
{
Debug.Assert(false, "NYI");
return base.GetEnumNames();
}
public override Type GetEnumUnderlyingType()
{
Debug.Assert(false, "NYI");
return base.GetEnumUnderlyingType();
}
public override Array GetEnumValues()
{
Debug.Assert(false, "NYI");
return base.GetEnumValues();
}
public override EventInfo[] GetEvents()
{
Debug.Assert(false, "NYI");
return base.GetEvents();
}
public override Type[] GetGenericParameterConstraints()
{
Debug.Assert(false, "NYI");
return base.GetGenericParameterConstraints();
}
public override Type GetGenericTypeDefinition()
{
Debug.Assert(false, "NYI");
return base.GetGenericTypeDefinition();
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
Debug.Assert(false, "NYI");
return base.GetInterfaceMap(interfaceType);
}
public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
{
Debug.Assert(false, "NYI");
return base.GetMember(name, bindingAttr);
}
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
Debug.Assert(false, "NYI");
return base.GetMember(name, type, bindingAttr);
}
protected override TypeCode GetTypeCodeImpl()
{
Debug.Assert(false, "NYI");
return base.GetTypeCodeImpl();
}
public override bool IsAssignableFrom(Type c)
{
Debug.Assert(false, "NYI");
return base.IsAssignableFrom(c);
}
protected override bool IsContextfulImpl()
{
Debug.Assert(false, "NYI");
return base.IsContextfulImpl();
}
public override bool IsEnumDefined(object value)
{
Debug.Assert(false, "NYI");
return base.IsEnumDefined(value);
}
public override bool IsEquivalentTo(Type other)
{
Debug.Assert(false, "NYI");
return base.IsEquivalentTo(other);
}
public override bool IsGenericParameter
{
get
{
return _IsGenericType;
}
}
public override bool IsInstanceOfType(object o)
{
Debug.Assert(false, "NYI");
return base.IsInstanceOfType(o);
}
protected override bool IsMarshalByRefImpl()
{
Debug.Assert(false, "NYI");
return base.IsMarshalByRefImpl();
}
public override bool IsSecurityCritical
{
get
{
Debug.Assert(false, "NYI");
return base.IsSecurityCritical;
}
}
public override bool IsSecuritySafeCritical
{
get
{
Debug.Assert(false, "NYI");
return base.IsSecuritySafeCritical;
}
}
public override bool IsSecurityTransparent
{
get
{
Debug.Assert(false, "NYI");
return base.IsSecurityTransparent;
}
}
public override bool IsSerializable
{
get
{
Debug.Assert(false, "NYI");
return base.IsSerializable;
}
}
public override bool IsSubclassOf(Type c)
{
Debug.Assert(false, "NYI");
return base.IsSubclassOf(c);
}
public override Type MakeArrayType()
{
Debug.Assert(false, "NYI");
return base.MakeArrayType();
}
public override Type MakeArrayType(int rank)
{
Debug.Assert(false, "NYI");
return base.MakeArrayType(rank);
}
public override Type MakeByRefType()
{
return base.MakeByRefType();
}
public override Type MakeGenericType(params Type[] typeArguments)
{
Debug.Assert(false, "NYI");
return base.MakeGenericType(typeArguments);
}
public override Type MakePointerType()
{
Debug.Assert(false, "NYI");
return base.MakePointerType();
}
public override MemberTypes MemberType
{
get
{
Debug.Assert(false, "NYI");
return base.MemberType;
}
}
public override int MetadataToken
{
get
{
Debug.Assert(false, "NYI");
return base.MetadataToken;
}
}
public override Type ReflectedType
{
get
{
Debug.Assert(false, "NYI");
return base.ReflectedType;
}
}
public override System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute
{
get
{
Debug.Assert(false, "NYI");
return base.StructLayoutAttribute;
}
}
public override RuntimeTypeHandle TypeHandle
{
get
{
Debug.Assert(false, "NYI");
return base.TypeHandle;
}
}
public override string ToString()
{
Debug.Assert(false, "NYI");
return base.ToString();
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
var attrs = new List<CustomAttributeData>();
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderXmlDocAttribute("This is a synthetic type created by me!")));
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderDefinitionLocationAttribute() { Column = 21, FilePath = "File.fs", Line = 3 }));
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderEditorHideMethodsAttribute()));
return attrs;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Carousel;
using osu.Game.Screens.Select.Filter;
using osu.Game.Tests.Resources;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
[TestFixture]
public class TestSceneBeatmapCarousel : OsuManualInputManagerTestScene
{
private TestBeatmapCarousel carousel;
private RulesetStore rulesets;
private readonly Stack<BeatmapSetInfo> selectedSets = new Stack<BeatmapSetInfo>();
private readonly HashSet<int> eagerSelectedIDs = new HashSet<int>();
private BeatmapInfo currentSelection => carousel.SelectedBeatmapInfo;
private const int set_count = 5;
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
this.rulesets = rulesets;
}
[Test]
public void TestManyPanels()
{
loadBeatmaps(count: 5000, randomDifficulties: true);
}
[Test]
public void TestKeyRepeat()
{
loadBeatmaps();
advanceSelection(false);
AddStep("press down arrow", () => InputManager.PressKey(Key.Down));
BeatmapInfo selection = null;
checkSelectionIterating(true);
AddStep("press up arrow", () => InputManager.PressKey(Key.Up));
checkSelectionIterating(true);
AddStep("release down arrow", () => InputManager.ReleaseKey(Key.Down));
checkSelectionIterating(true);
AddStep("release up arrow", () => InputManager.ReleaseKey(Key.Up));
checkSelectionIterating(false);
void checkSelectionIterating(bool isIterating)
{
for (int i = 0; i < 3; i++)
{
AddStep("store selection", () => selection = carousel.SelectedBeatmapInfo);
if (isIterating)
AddUntilStep("selection changed", () => !carousel.SelectedBeatmapInfo.Equals(selection));
else
AddUntilStep("selection not changed", () => carousel.SelectedBeatmapInfo.Equals(selection));
}
}
}
[Test]
public void TestRecommendedSelection()
{
loadBeatmaps(carouselAdjust: carousel => carousel.GetRecommendedBeatmap = beatmaps => beatmaps.LastOrDefault());
AddStep("select last", () => carousel.SelectBeatmap(carousel.BeatmapSets.Last().Beatmaps.Last()));
// check recommended was selected
advanceSelection(direction: 1, diff: false);
waitForSelection(1, 3);
// change away from recommended
advanceSelection(direction: -1, diff: true);
waitForSelection(1, 2);
// next set, check recommended
advanceSelection(direction: 1, diff: false);
waitForSelection(2, 3);
// next set, check recommended
advanceSelection(direction: 1, diff: false);
waitForSelection(3, 3);
// go back to first set and ensure user selection was retained
advanceSelection(direction: -1, diff: false);
advanceSelection(direction: -1, diff: false);
waitForSelection(1, 2);
}
/// <summary>
/// Test keyboard traversal
/// </summary>
[Test]
public void TestTraversal()
{
loadBeatmaps();
AddStep("select first", () => carousel.SelectBeatmap(carousel.BeatmapSets.First().Beatmaps.First()));
waitForSelection(1, 1);
advanceSelection(direction: 1, diff: true);
waitForSelection(1, 2);
advanceSelection(direction: -1, diff: false);
waitForSelection(set_count, 1);
advanceSelection(direction: -1, diff: true);
waitForSelection(set_count - 1, 3);
advanceSelection(diff: false);
advanceSelection(diff: false);
waitForSelection(1, 2);
advanceSelection(direction: -1, diff: true);
advanceSelection(direction: -1, diff: true);
waitForSelection(set_count, 3);
}
[TestCase(true)]
[TestCase(false)]
public void TestTraversalBeyondVisible(bool forwards)
{
var sets = new List<BeatmapSetInfo>();
const int total_set_count = 200;
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo());
loadBeatmaps(sets);
for (int i = 1; i < total_set_count; i += i)
selectNextAndAssert(i);
void selectNextAndAssert(int amount)
{
setSelected(forwards ? 1 : total_set_count, 1);
AddStep($"{(forwards ? "Next" : "Previous")} beatmap {amount} times", () =>
{
for (int i = 0; i < amount; i++)
{
carousel.SelectNext(forwards ? 1 : -1);
}
});
waitForSelection(forwards ? amount + 1 : total_set_count - amount);
}
}
[Test]
public void TestTraversalBeyondVisibleDifficulties()
{
var sets = new List<BeatmapSetInfo>();
const int total_set_count = 20;
for (int i = 0; i < total_set_count; i++)
sets.Add(TestResources.CreateTestBeatmapSetInfo(3));
loadBeatmaps(sets);
// Selects next set once, difficulty index doesn't change
selectNextAndAssert(3, true, 2, 1);
// Selects next set 16 times (50 \ 3 == 16), difficulty index changes twice (50 % 3 == 2)
selectNextAndAssert(50, true, 17, 3);
// Travels around the carousel thrice (200 \ 60 == 3)
// continues to select 20 times (200 \ 60 == 20)
// selects next set 6 times (20 \ 3 == 6)
// difficulty index changes twice (20 % 3 == 2)
selectNextAndAssert(200, true, 7, 3);
// All same but in reverse
selectNextAndAssert(3, false, 19, 3);
selectNextAndAssert(50, false, 4, 1);
selectNextAndAssert(200, false, 14, 1);
void selectNextAndAssert(int amount, bool forwards, int expectedSet, int expectedDiff)
{
// Select very first or very last difficulty
setSelected(forwards ? 1 : 20, forwards ? 1 : 3);
AddStep($"{(forwards ? "Next" : "Previous")} difficulty {amount} times", () =>
{
for (int i = 0; i < amount; i++)
carousel.SelectNext(forwards ? 1 : -1, false);
});
waitForSelection(expectedSet, expectedDiff);
}
}
/// <summary>
/// Test filtering
/// </summary>
[Test]
public void TestFiltering()
{
loadBeatmaps();
// basic filtering
setSelected(1, 1);
AddStep("Filter", () => carousel.Filter(new FilterCriteria { SearchText = carousel.BeatmapSets.ElementAt(2).Metadata.Title }, false));
checkVisibleItemCount(diff: false, count: 1);
checkVisibleItemCount(diff: true, count: 3);
waitForSelection(3, 1);
advanceSelection(diff: true, count: 4);
waitForSelection(3, 2);
AddStep("Un-filter (debounce)", () => carousel.Filter(new FilterCriteria()));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(diff: false, count: set_count);
checkVisibleItemCount(diff: true, count: 3);
// test filtering some difficulties (and keeping current beatmap set selected).
setSelected(1, 2);
AddStep("Filter some difficulties", () => carousel.Filter(new FilterCriteria { SearchText = "Normal" }, false));
waitForSelection(1, 1);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
waitForSelection(1, 1);
AddStep("Filter all", () => carousel.Filter(new FilterCriteria { SearchText = "Dingo" }, false));
checkVisibleItemCount(false, 0);
checkVisibleItemCount(true, 0);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(true);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(false);
AddAssert("Selection is null", () => currentSelection == null);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
AddAssert("Selection is non-null", () => currentSelection != null);
setSelected(1, 3);
}
[Test]
public void TestFilterRange()
{
string searchText = null;
loadBeatmaps();
// buffer the selection
setSelected(3, 2);
AddStep("get search text", () => searchText = carousel.SelectedBeatmapSet.Metadata.Title);
setSelected(1, 3);
AddStep("Apply a range filter", () => carousel.Filter(new FilterCriteria
{
SearchText = searchText,
StarDifficulty = new FilterCriteria.OptionalRange<double>
{
Min = 2,
Max = 5.5,
IsLowerInclusive = true
}
}, false));
// should reselect the buffered selection.
waitForSelection(3, 2);
}
/// <summary>
/// Test random non-repeating algorithm
/// </summary>
[Test]
public void TestRandom()
{
loadBeatmaps();
setSelected(1, 1);
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
prevRandom();
ensureRandomFetchSuccess();
prevRandom();
ensureRandomFetchSuccess();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
AddAssert("ensure repeat", () => selectedSets.Contains(carousel.SelectedBeatmapSet));
AddStep("Add set with 100 difficulties", () => carousel.UpdateBeatmapSet(TestResources.CreateTestBeatmapSetInfo(100, rulesets.AvailableRulesets.ToArray())));
AddStep("Filter Extra", () => carousel.Filter(new FilterCriteria { SearchText = "Extra 10" }, false));
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
}
/// <summary>
/// Test adding and removing beatmap sets
/// </summary>
[Test]
public void TestAddRemove()
{
loadBeatmaps();
var firstAdded = TestResources.CreateTestBeatmapSetInfo();
var secondAdded = TestResources.CreateTestBeatmapSetInfo();
AddStep("Add new set", () => carousel.UpdateBeatmapSet(firstAdded));
AddStep("Add new set", () => carousel.UpdateBeatmapSet(secondAdded));
checkVisibleItemCount(false, set_count + 2);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(firstAdded));
checkVisibleItemCount(false, set_count + 1);
setSelected(set_count + 1, 1);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(secondAdded));
checkVisibleItemCount(false, set_count);
waitForSelection(set_count);
}
[Test]
public void TestSelectionEnteringFromEmptyRuleset()
{
var sets = new List<BeatmapSetInfo>();
AddStep("Create beatmaps for taiko only", () =>
{
sets.Clear();
var rulesetBeatmapSet = TestResources.CreateTestBeatmapSetInfo(1);
var taikoRuleset = rulesets.AvailableRulesets.ElementAt(1);
rulesetBeatmapSet.Beatmaps.ForEach(b =>
{
b.Ruleset = taikoRuleset;
b.RulesetID = 1;
});
sets.Add(rulesetBeatmapSet);
});
loadBeatmaps(sets, () => new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) });
AddStep("Set non-empty mode filter", () =>
carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(1) }, false));
AddAssert("Something is selected", () => carousel.SelectedBeatmapInfo != null);
}
/// <summary>
/// Test sorting
/// </summary>
[Test]
public void TestSorting()
{
var sets = new List<BeatmapSetInfo>();
const string zzz_string = "zzzzz";
for (int i = 0; i < 20; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo();
if (i == 4)
set.Metadata.Artist = zzz_string;
if (i == 16)
set.Metadata.AuthorString = zzz_string;
sets.Add(set);
}
loadBeatmaps(sets);
AddStep("Sort by author", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Author }, false));
AddAssert($"Check {zzz_string} is at bottom", () => carousel.BeatmapSets.Last().Metadata.Author.Username == zzz_string);
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert($"Check {zzz_string} is at bottom", () => carousel.BeatmapSets.Last().Metadata.Artist == zzz_string);
}
[Test]
public void TestSortingStability()
{
var sets = new List<BeatmapSetInfo>();
for (int i = 0; i < 20; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo();
set.Metadata.Artist = "same artist";
set.Metadata.Title = "same title";
sets.Add(set);
}
int idOffset = sets.First().OnlineID ?? 0;
loadBeatmaps(sets);
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.OnlineID == index + idOffset).All(b => b));
AddStep("Sort by title", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Title }, false));
AddAssert("Items remain in original order", () => carousel.BeatmapSets.Select((set, index) => set.OnlineID == index + idOffset).All(b => b));
}
[Test]
public void TestSortingWithFiltered()
{
List<BeatmapSetInfo> sets = new List<BeatmapSetInfo>();
for (int i = 0; i < 3; i++)
{
var set = TestResources.CreateTestBeatmapSetInfo(3);
set.Beatmaps[0].StarRating = 3 - i;
set.Beatmaps[2].StarRating = 6 + i;
sets.Add(set);
}
loadBeatmaps(sets);
AddStep("Filter to normal", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Normal" }, false));
AddAssert("Check first set at end", () => carousel.BeatmapSets.First().Equals(sets.Last()));
AddAssert("Check last set at start", () => carousel.BeatmapSets.Last().Equals(sets.First()));
AddStep("Filter to insane", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Difficulty, SearchText = "Insane" }, false));
AddAssert("Check first set at start", () => carousel.BeatmapSets.First().Equals(sets.First()));
AddAssert("Check last set at end", () => carousel.BeatmapSets.Last().Equals(sets.Last()));
}
[Test]
public void TestRemoveAll()
{
loadBeatmaps();
setSelected(2, 1);
AddAssert("Selection is non-null", () => currentSelection != null);
AddStep("Remove selected", () => carousel.RemoveBeatmapSet(carousel.SelectedBeatmapSet));
waitForSelection(2);
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
waitForSelection(1);
AddUntilStep("Remove all", () =>
{
if (!carousel.BeatmapSets.Any()) return true;
carousel.RemoveBeatmapSet(carousel.BeatmapSets.Last());
return false;
});
checkNoSelection();
}
[Test]
public void TestEmptyTraversal()
{
loadBeatmaps(new List<BeatmapSetInfo>());
advanceSelection(direction: 1, diff: false);
checkNoSelection();
advanceSelection(direction: 1, diff: true);
checkNoSelection();
advanceSelection(direction: -1, diff: false);
checkNoSelection();
advanceSelection(direction: -1, diff: true);
checkNoSelection();
}
[Test]
public void TestHiding()
{
BeatmapSetInfo hidingSet = null;
List<BeatmapSetInfo> hiddenList = new List<BeatmapSetInfo>();
AddStep("create hidden set", () =>
{
hidingSet = TestResources.CreateTestBeatmapSetInfo(3);
hidingSet.Beatmaps[1].Hidden = true;
hiddenList.Clear();
hiddenList.Add(hidingSet);
});
loadBeatmaps(hiddenList);
setSelected(1, 1);
checkVisibleItemCount(true, 2);
advanceSelection(true);
waitForSelection(1, 3);
setHidden(3);
waitForSelection(1, 1);
setHidden(2, false);
advanceSelection(true);
waitForSelection(1, 2);
setHidden(1);
waitForSelection(1, 2);
setHidden(2);
checkNoSelection();
void setHidden(int diff, bool hidden = true)
{
AddStep((hidden ? "" : "un") + $"hide diff {diff}", () =>
{
hidingSet.Beatmaps[diff - 1].Hidden = hidden;
carousel.UpdateBeatmapSet(hidingSet);
});
}
}
[Test]
public void TestSelectingFilteredRuleset()
{
BeatmapSetInfo testMixed = null;
createCarousel();
AddStep("add mixed ruleset beatmapset", () =>
{
testMixed = TestResources.CreateTestBeatmapSetInfo(3);
for (int i = 0; i <= 2; i++)
{
testMixed.Beatmaps[i].Ruleset = rulesets.AvailableRulesets.ElementAt(i);
testMixed.Beatmaps[i].RulesetID = i;
}
carousel.UpdateBeatmapSet(testMixed);
});
AddStep("filter to ruleset 0", () =>
carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) }, false));
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testMixed.Beatmaps[1], false));
AddAssert("unfiltered beatmap not selected", () => carousel.SelectedBeatmapInfo.RulesetID == 0);
AddStep("remove mixed set", () =>
{
carousel.RemoveBeatmapSet(testMixed);
testMixed = null;
});
BeatmapSetInfo testSingle = null;
AddStep("add single ruleset beatmapset", () =>
{
testSingle = TestResources.CreateTestBeatmapSetInfo(3);
testSingle.Beatmaps.ForEach(b =>
{
b.Ruleset = rulesets.AvailableRulesets.ElementAt(1);
b.RulesetID = b.Ruleset.ID ?? 1;
});
carousel.UpdateBeatmapSet(testSingle);
});
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testSingle.Beatmaps[0], false));
checkNoSelection();
AddStep("remove single ruleset set", () => carousel.RemoveBeatmapSet(testSingle));
}
[Test]
public void TestCarouselRemembersSelection()
{
List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>();
for (int i = 1; i <= 50; i++)
manySets.Add(TestResources.CreateTestBeatmapSetInfo(3));
loadBeatmaps(manySets);
advanceSelection(direction: 1, diff: false);
for (int i = 0; i < 5; i++)
{
AddStep("Toggle non-matching filter", () =>
{
carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false);
});
AddStep("Restore no filter", () =>
{
carousel.Filter(new FilterCriteria(), false);
eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID);
});
}
// always returns to same selection as long as it's available.
AddAssert("Selection was remembered", () => eagerSelectedIDs.Count == 1);
}
[Test]
public void TestRandomFallbackOnNonMatchingPrevious()
{
List<BeatmapSetInfo> manySets = new List<BeatmapSetInfo>();
AddStep("populate maps", () =>
{
for (int i = 0; i < 10; i++)
{
manySets.Add(TestResources.CreateTestBeatmapSetInfo(3, new[]
{
// all taiko except for first
rulesets.GetRuleset(i > 0 ? 1 : 0)
}));
}
});
loadBeatmaps(manySets);
for (int i = 0; i < 10; i++)
{
AddStep("Reset filter", () => carousel.Filter(new FilterCriteria(), false));
AddStep("select first beatmap", () => carousel.SelectBeatmap(manySets.First().Beatmaps.First()));
AddStep("Toggle non-matching filter", () =>
{
carousel.Filter(new FilterCriteria { SearchText = Guid.NewGuid().ToString() }, false);
});
AddAssert("selection lost", () => carousel.SelectedBeatmapInfo == null);
AddStep("Restore different ruleset filter", () =>
{
carousel.Filter(new FilterCriteria { Ruleset = rulesets.GetRuleset(1) }, false);
eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.OnlineID ?? -1);
});
AddAssert("selection changed", () => !carousel.SelectedBeatmapInfo.Equals(manySets.First().Beatmaps.First()));
}
AddAssert("Selection was random", () => eagerSelectedIDs.Count > 2);
}
[Test]
public void TestFilteringByUserStarDifficulty()
{
BeatmapSetInfo set = null;
loadBeatmaps(new List<BeatmapSetInfo>());
AddStep("add mixed difficulty set", () =>
{
set = TestResources.CreateTestBeatmapSetInfo(1);
set.Beatmaps.Clear();
for (int i = 1; i <= 15; i++)
{
set.Beatmaps.Add(new BeatmapInfo
{
DifficultyName = $"Stars: {i}",
Ruleset = new OsuRuleset().RulesetInfo,
StarRating = i,
});
}
carousel.UpdateBeatmapSet(set);
});
AddStep("select added set", () => carousel.SelectBeatmap(set.Beatmaps[0], false));
AddStep("filter [5..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 11);
AddStep("filter to [0..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Max = 7 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 7);
AddStep("filter to [5..7]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 5, Max = 7 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 3);
AddStep("filter [2..2]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 2, Max = 2 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 1);
AddStep("filter to [0..]", () => carousel.Filter(new FilterCriteria { UserStarDifficulty = { Min = 0 } }));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(true, 15);
}
private void loadBeatmaps(List<BeatmapSetInfo> beatmapSets = null, Func<FilterCriteria> initialCriteria = null, Action<BeatmapCarousel> carouselAdjust = null, int? count = null, bool randomDifficulties = false)
{
bool changed = false;
createCarousel(c =>
{
carouselAdjust?.Invoke(c);
if (beatmapSets == null)
{
beatmapSets = new List<BeatmapSetInfo>();
for (int i = 1; i <= (count ?? set_count); i++)
{
beatmapSets.Add(randomDifficulties
? TestResources.CreateTestBeatmapSetInfo()
: TestResources.CreateTestBeatmapSetInfo(3));
}
}
carousel.Filter(initialCriteria?.Invoke() ?? new FilterCriteria());
carousel.BeatmapSetsChanged = () => changed = true;
carousel.BeatmapSets = beatmapSets;
});
AddUntilStep("Wait for load", () => changed);
}
private void createCarousel(Action<BeatmapCarousel> carouselAdjust = null, Container target = null)
{
AddStep("Create carousel", () =>
{
selectedSets.Clear();
eagerSelectedIDs.Clear();
carousel = new TestBeatmapCarousel
{
RelativeSizeAxes = Axes.Both,
};
carouselAdjust?.Invoke(carousel);
(target ?? this).Child = carousel;
});
}
private void ensureRandomFetchSuccess() =>
AddAssert("ensure prev random fetch worked", () => selectedSets.Peek().Equals(carousel.SelectedBeatmapSet));
private void waitForSelection(int set, int? diff = null) =>
AddUntilStep($"selected is set{set}{(diff.HasValue ? $" diff{diff.Value}" : "")}", () =>
{
if (diff != null)
return carousel.SelectedBeatmapInfo?.Equals(carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff.Value - 1).First()) == true;
return carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Contains(carousel.SelectedBeatmapInfo);
});
private void setSelected(int set, int diff) =>
AddStep($"select set{set} diff{diff}", () =>
carousel.SelectBeatmap(carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff - 1).First()));
private void advanceSelection(bool diff, int direction = 1, int count = 1)
{
if (count == 1)
{
AddStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff));
}
else
{
AddRepeatStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff), count);
}
}
private void checkVisibleItemCount(bool diff, int count)
{
// until step required as we are querying against alive items, which are loaded asynchronously inside DrawableCarouselBeatmapSet.
AddUntilStep($"{count} {(diff ? "diffs" : "sets")} visible", () =>
carousel.Items.Count(s => (diff ? s.Item is CarouselBeatmap : s.Item is CarouselBeatmapSet) && s.Item.Visible) == count);
}
private void checkNoSelection() => AddAssert("Selection is null", () => currentSelection == null);
private void nextRandom() =>
AddStep("select random next", () =>
{
carousel.RandomAlgorithm.Value = RandomSelectAlgorithm.RandomPermutation;
if (!selectedSets.Any() && carousel.SelectedBeatmapInfo != null)
selectedSets.Push(carousel.SelectedBeatmapSet);
carousel.SelectNextRandom();
selectedSets.Push(carousel.SelectedBeatmapSet);
});
private void ensureRandomDidntRepeat() =>
AddAssert("ensure no repeats", () => selectedSets.Distinct().Count() == selectedSets.Count);
private void prevRandom() => AddStep("select random last", () =>
{
carousel.SelectPreviousRandom();
selectedSets.Pop();
});
private bool selectedBeatmapVisible()
{
var currentlySelected = carousel.Items.FirstOrDefault(s => s.Item is CarouselBeatmap && s.Item.State.Value == CarouselItemState.Selected);
if (currentlySelected == null)
return true;
return currentlySelected.Item.Visible;
}
private void checkInvisibleDifficultiesUnselectable()
{
nextRandom();
AddAssert("Selection is visible", selectedBeatmapVisible);
}
private class TestBeatmapCarousel : BeatmapCarousel
{
public bool PendingFilterTask => PendingFilter != null;
public IEnumerable<DrawableCarouselItem> Items
{
get
{
foreach (var item in Scroll.Children)
{
yield return item;
if (item is DrawableCarouselBeatmapSet set)
{
foreach (var difficulty in set.DrawableBeatmaps)
yield return difficulty;
}
}
}
}
protected override IEnumerable<BeatmapSetInfo> GetLoadableBeatmaps() => Enumerable.Empty<BeatmapSetInfo>();
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace Lucene.Net.Search
{
using NUnit.Framework;
using System.IO;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using English = Lucene.Net.Util.English;
using Fields = Lucene.Net.Index.Fields;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
[TestFixture]
public class TestMultiThreadTermVectors : LuceneTestCase
{
private Directory Directory;
public int NumDocs = 100;
public int NumThreads = 3;
[SetUp]
public override void SetUp()
{
base.SetUp();
Directory = NewDirectory();
IndexWriter writer = new IndexWriter(Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
//writer.setNoCFSRatio(0.0);
//writer.infoStream = System.out;
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.Tokenized = false;
customType.StoreTermVectors = true;
for (int i = 0; i < NumDocs; i++)
{
Documents.Document doc = new Documents.Document();
Field fld = NewField("field", English.IntToEnglish(i), customType);
doc.Add(fld);
writer.AddDocument(doc);
}
writer.Dispose();
}
[TearDown]
public override void TearDown()
{
Directory.Dispose();
base.TearDown();
}
[Test]
public virtual void Test()
{
IndexReader reader = null;
try
{
reader = DirectoryReader.Open(Directory);
for (int i = 1; i <= NumThreads; i++)
{
TestTermPositionVectors(reader, i);
}
}
catch (IOException ioe)
{
Assert.Fail(ioe.Message);
}
finally
{
if (reader != null)
{
try
{
/// <summary>
/// close the opened reader </summary>
reader.Dispose();
}
catch (IOException ioe)
{
Console.WriteLine(ioe.ToString());
Console.Write(ioe.StackTrace);
}
}
}
}
public virtual void TestTermPositionVectors(IndexReader reader, int threadCount)
{
MultiThreadTermVectorsReader[] mtr = new MultiThreadTermVectorsReader[threadCount];
for (int i = 0; i < threadCount; i++)
{
mtr[i] = new MultiThreadTermVectorsReader();
mtr[i].Init(reader);
}
// run until all threads finished
int threadsAlive = mtr.Length;
while (threadsAlive > 0)
{
//System.out.println("Threads alive");
Thread.Sleep(10);
threadsAlive = mtr.Length;
for (int i = 0; i < mtr.Length; i++)
{
if (mtr[i].Alive == true)
{
break;
}
threadsAlive--;
}
}
long totalTime = 0L;
for (int i = 0; i < mtr.Length; i++)
{
totalTime += mtr[i].TimeElapsed;
mtr[i] = null;
}
//System.out.println("threadcount: " + mtr.Length + " average term vector time: " + totalTime/mtr.Length);
}
}
internal class MultiThreadTermVectorsReader : IThreadRunnable
{
private IndexReader Reader = null;
private ThreadClass t = null;
private readonly int RunsToDo = 100;
internal long TimeElapsed = 0;
public virtual void Init(IndexReader reader)
{
this.Reader = reader;
TimeElapsed = 0;
t = new ThreadClass(new System.Threading.ThreadStart(this.Run));
t.Start();
}
public virtual bool Alive
{
get
{
if (t == null)
{
return false;
}
return t.IsAlive;
}
}
[Test]
public void Run()
{
try
{
// run the test 100 times
for (int i = 0; i < RunsToDo; i++)
{
TestTermVectors();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.Write(e.StackTrace);
}
return;
}
private void TestTermVectors()
{
// check:
int numDocs = Reader.NumDocs;
long start = 0L;
for (int docId = 0; docId < numDocs; docId++)
{
start = Environment.TickCount;
Fields vectors = Reader.GetTermVectors(docId);
TimeElapsed += Environment.TickCount - start;
// verify vectors result
VerifyVectors(vectors, docId);
start = Environment.TickCount;
Terms vector = Reader.GetTermVectors(docId).Terms("field");
TimeElapsed += Environment.TickCount - start;
VerifyVector(vector.Iterator(null), docId);
}
}
private void VerifyVectors(Fields vectors, int num)
{
foreach (string field in vectors)
{
Terms terms = vectors.Terms(field);
Debug.Assert(terms != null);
VerifyVector(terms.Iterator(null), num);
}
}
private void VerifyVector(TermsEnum vector, int num)
{
StringBuilder temp = new StringBuilder();
while (vector.Next() != null)
{
temp.Append(vector.Term().Utf8ToString());
}
if (!English.IntToEnglish(num).Trim().Equals(temp.ToString().Trim()))
{
Console.WriteLine("wrong term result");
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Internal;
using System.Runtime.Serialization;
namespace System.Management.Automation
{
/// <summary>
/// Defines the exception thrown for all Metadata errors.
/// </summary>
[Serializable]
public class MetadataException : RuntimeException
{
internal const string MetadataMemberInitialization = "MetadataMemberInitialization";
internal const string BaseName = "Metadata";
/// <summary>
/// Initializes a new instance of MetadataException with serialization parameters.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected MetadataException(SerializationInfo info, StreamingContext context) : base(info, context)
{
SetErrorCategory(ErrorCategory.MetadataError);
}
/// <summary>
/// Initializes a new instance of MetadataException with the message set
/// to typeof(MetadataException).FullName.
/// </summary>
public MetadataException() : base(typeof(MetadataException).FullName)
{
SetErrorCategory(ErrorCategory.MetadataError);
}
/// <summary>
/// Initializes a new instance of MetadataException setting the message.
/// </summary>
/// <param name="message">The exception's message.</param>
public MetadataException(string message) : base(message)
{
SetErrorCategory(ErrorCategory.MetadataError);
}
/// <summary>
/// Initializes a new instance of MetadataException setting the message and innerException.
/// </summary>
/// <param name="message">The exception's message.</param>
/// <param name="innerException">The exceptions's inner exception.</param>
public MetadataException(string message, Exception innerException) : base(message, innerException)
{
SetErrorCategory(ErrorCategory.MetadataError);
}
internal MetadataException(
string errorId,
Exception innerException,
string resourceStr,
params object[] arguments)
: base(
StringUtil.Format(resourceStr, arguments),
innerException)
{
SetErrorCategory(ErrorCategory.MetadataError);
SetErrorId(errorId);
}
}
/// <summary>
/// Defines the exception thrown for all Validate attributes.
/// </summary>
[Serializable]
[SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")]
public class ValidationMetadataException : MetadataException
{
internal const string ValidateRangeElementType = "ValidateRangeElementType";
internal const string ValidateRangePositiveFailure = "ValidateRangePositiveFailure";
internal const string ValidateRangeNonNegativeFailure = "ValidateRangeNonNegativeFailure";
internal const string ValidateRangeNegativeFailure = "ValidateRangeNegativeFailure";
internal const string ValidateRangeNonPositiveFailure = "ValidateRangeNonPositiveFailure";
internal const string ValidateRangeMinRangeMaxRangeType = "ValidateRangeMinRangeMaxRangeType";
internal const string ValidateRangeNotIComparable = "ValidateRangeNotIComparable";
internal const string ValidateRangeMaxRangeSmallerThanMinRange = "ValidateRangeMaxRangeSmallerThanMinRange";
internal const string ValidateRangeGreaterThanMaxRangeFailure = "ValidateRangeGreaterThanMaxRangeFailure";
internal const string ValidateRangeSmallerThanMinRangeFailure = "ValidateRangeSmallerThanMinRangeFailure";
internal const string ValidateFailureResult = "ValidateFailureResult";
internal const string ValidatePatternFailure = "ValidatePatternFailure";
internal const string ValidateScriptFailure = "ValidateScriptFailure";
internal const string ValidateCountNotInArray = "ValidateCountNotInArray";
internal const string ValidateCountMaxLengthSmallerThanMinLength = "ValidateCountMaxLengthSmallerThanMinLength";
internal const string ValidateCountMinLengthFailure = "ValidateCountMinLengthFailure";
internal const string ValidateCountMaxLengthFailure = "ValidateCountMaxLengthFailure";
internal const string ValidateLengthMaxLengthSmallerThanMinLength = "ValidateLengthMaxLengthSmallerThanMinLength";
internal const string ValidateLengthNotString = "ValidateLengthNotString";
internal const string ValidateLengthMinLengthFailure = "ValidateLengthMinLengthFailure";
internal const string ValidateLengthMaxLengthFailure = "ValidateLengthMaxLengthFailure";
internal const string ValidateSetFailure = "ValidateSetFailure";
internal const string ValidateVersionFailure = "ValidateVersionFailure";
internal const string InvalidValueFailure = "InvalidValueFailure";
/// <summary>
/// Initializes a new instance of ValidationMetadataException with serialization parameters.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected ValidationMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { }
/// <summary>
/// Initializes a new instance of ValidationMetadataException with the message set
/// to typeof(ValidationMetadataException).FullName.
/// </summary>
public ValidationMetadataException() : base(typeof(ValidationMetadataException).FullName) { }
/// <summary>
/// Initializes a new instance of ValidationMetadataException setting the message.
/// </summary>
/// <param name="message">The exception's message.</param>
public ValidationMetadataException(string message) : this(message, false) { }
/// <summary>
/// Initializes a new instance of ValidationMetadataException setting the message and innerException.
/// </summary>
/// <param name="message">The exception's message.</param>
/// <param name="innerException">The exceptions's inner exception.</param>
public ValidationMetadataException(string message, Exception innerException) : base(message, innerException) { }
internal ValidationMetadataException(
string errorId,
Exception innerException,
string resourceStr,
params object[] arguments)
: base(errorId, innerException, resourceStr, arguments)
{
}
/// <summary>
/// Initialize a new instance of ValidationMetadataException. This validation exception could be
/// ignored in positional binding phase if the <para>swallowException</para> is set to be true.
/// </summary>
/// <param name="message">
/// The error message</param>
/// <param name="swallowException">
/// Indicate whether to swallow this exception in positional binding phase
/// </param>
internal ValidationMetadataException(string message, bool swallowException) : base(message)
{
_swallowException = swallowException;
}
/// <summary>
/// Make the positional binding swallow this exception when it's set to true.
/// </summary>
/// <remarks>
/// This property is only used internally in the positional binding phase
/// </remarks>
internal bool SwallowException
{
get { return _swallowException; }
}
private readonly bool _swallowException = false;
}
/// <summary>
/// Defines the exception thrown for all ArgumentTransformation attributes.
/// </summary>
[Serializable]
public class ArgumentTransformationMetadataException : MetadataException
{
internal const string ArgumentTransformationArgumentsShouldBeStrings = "ArgumentTransformationArgumentsShouldBeStrings";
/// <summary>
/// Initializes a new instance of ArgumentTransformationMetadataException with serialization parameters.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected ArgumentTransformationMetadataException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
/// <summary>
/// Initializes a new instance of ArgumentTransformationMetadataException with the message set
/// to typeof(ArgumentTransformationMetadataException).FullName.
/// </summary>
public ArgumentTransformationMetadataException()
: base(typeof(ArgumentTransformationMetadataException).FullName) { }
/// <summary>
/// Initializes a new instance of ArgumentTransformationMetadataException setting the message.
/// </summary>
/// <param name="message">The exception's message.</param>
public ArgumentTransformationMetadataException(string message)
: base(message) { }
/// <summary>
/// Initializes a new instance of ArgumentTransformationMetadataException setting the message and innerException.
/// </summary>
/// <param name="message">The exception's message.</param>
/// <param name="innerException">The exceptions's inner exception.</param>
public ArgumentTransformationMetadataException(string message, Exception innerException)
: base(message, innerException) { }
internal ArgumentTransformationMetadataException(
string errorId,
Exception innerException,
string resourceStr,
params object[] arguments)
: base(errorId, innerException, resourceStr, arguments)
{
}
}
/// <summary>
/// Defines the exception thrown for all parameter binding exceptions related to metadata attributes.
/// </summary>
[Serializable]
public class ParsingMetadataException : MetadataException
{
internal const string ParsingTooManyParameterSets = "ParsingTooManyParameterSets";
/// <summary>
/// Initializes a new instance of ParsingMetadataException with serialization parameters.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
protected ParsingMetadataException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
/// <summary>
/// Initializes a new instance of ParsingMetadataException with the message set
/// to typeof(ParsingMetadataException).FullName.
/// </summary>
public ParsingMetadataException()
: base(typeof(ParsingMetadataException).FullName) { }
/// <summary>
/// Initializes a new instance of ParsingMetadataException setting the message.
/// </summary>
/// <param name="message">The exception's message.</param>
public ParsingMetadataException(string message)
: base(message) { }
/// <summary>
/// Initializes a new instance of ParsingMetadataException setting the message and innerException.
/// </summary>
/// <param name="message">The exception's message.</param>
/// <param name="innerException">The exceptions's inner exception.</param>
public ParsingMetadataException(string message, Exception innerException)
: base(message, innerException) { }
internal ParsingMetadataException(
string errorId,
Exception innerException,
string resourceStr,
params object[] arguments)
: base(errorId, innerException, resourceStr, arguments)
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace Hydra.Framework.Conversions
{
//
// **********************************************************************
/// <summary>
/// Utility methods to work with lists, arrays, hashtables, etc.
/// </summary>
// **********************************************************************
//
public class ConvertList
{
#region Static Methods
//
// **********************************************************************
/// <summary>
/// Finds list for objects with the string representation equal to the given name.
/// </summary>
/// <param name="list">list to search in</param>
/// <param name="text">string representation to look for</param>
/// <param name="comparisonType">string comparison method</param>
/// <returns>the string representation equal to the given name or null if not found</returns>
// **********************************************************************
//
static public T FindByText<T>(IEnumerable<T> list, string text, StringComparison comparisonType)
{
if (list != null &&
text != null)
{
foreach (object obj in list)
if (obj != null &&
obj.ToString().Equals(text, comparisonType))
return (T)obj;
}
return default(T);
}
//
// **********************************************************************
/// <summary>
/// Finds list for objects with the string representation equal to the given name.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">list to search in</param>
/// <param name="text">string representation to look for</param>
/// <returns>
/// the string representation equal to the given name or null if not found
/// </returns>
// **********************************************************************
//
static public T FindByText<T>(IEnumerable<T> list, string text)
{
return FindByText(list, text, StringComparison.Ordinal);
}
//
// **********************************************************************
/// <summary>
/// Finds list for objects with the string representation equal to the given name.
/// Case-insensitive.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">list to search in</param>
/// <param name="text">string representation to look for</param>
/// <returns>
/// the string representation equal to the given name or null if not found
/// </returns>
// **********************************************************************
//
static public T FindByTextCI<T>(IEnumerable<T> list, string text)
{
return FindByText(list, text, StringComparison.OrdinalIgnoreCase);
}
//
// **********************************************************************
/// <summary>
/// Finds list for objects with the string representation equal to the given name.
/// </summary>
/// <param name="list">list to search in</param>
/// <param name="text">string representation to look for</param>
/// <param name="comparisonType">string comparison method</param>
/// <returns>the string representation equal to the given name or null if not found</returns>
// **********************************************************************
//
static public object FindByText(IEnumerable list, string text, StringComparison comparisonType)
{
if (list != null &&
text != null)
{
foreach (object obj in list)
if (obj != null &&
obj.ToString().Equals(text, comparisonType))
return obj;
}
return null;
}
//
// **********************************************************************
/// <summary>
/// Finds list for objects with the string representation equal to the given name.
/// </summary>
/// <param name="list">list to search in</param>
/// <param name="text">string representation to look for</param>
/// <returns>
/// the string representation equal to the given name or null if not found
/// </returns>
// **********************************************************************
//
static public object FindByText(IEnumerable list, string text)
{
return FindByText(list, text, StringComparison.Ordinal);
}
//
// **********************************************************************
/// <summary>
/// Finds list for objects with the string representation equal to the given name.
/// Case-insensitive.
/// </summary>
/// <param name="list">list to search in</param>
/// <param name="text">string representation to look for</param>
/// <returns>
/// the string representation equal to the given name or null if not found
/// </returns>
// **********************************************************************
//
static public object FindByTextCI(IEnumerable list, string text)
{
return FindByText(list, text, StringComparison.OrdinalIgnoreCase);
}
//
// **********************************************************************
/// <summary>
/// Reverts list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">list to revert</param>
/// <returns>reverted list</returns>
// **********************************************************************
//
static public IList<T> Reverse<T>(IList<T> list)
{
if (list != null)
{
List<T> result = new List<T>();
for (int i = list.Count - 1; i >= 0; i--)
result.Add(list[i]);
return result;
}
return null;
}
//
// **********************************************************************
/// <summary>
/// Reverts list.
/// </summary>
/// <param name="list">list to revert</param>
/// <returns>reverted list</returns>
// **********************************************************************
//
static public IList Reverse(IList list)
{
if (list != null)
{
ArrayList result = new ArrayList(list.Count);
for (int i = list.Count - 1; i >= 0; i--)
result.Add(list[i]);
return result;
}
return null;
}
//
// **********************************************************************
/// <summary>
/// Returns list that contains all not null objects from the array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arr">source array</param>
/// <returns>
/// list that contains all not null objects from the array
/// </returns>
// **********************************************************************
//
static public IList<T> ArrayToList<T>(T[] arr) where T : class
{
List<T> list = new List<T>();
foreach (T obj in arr)
if (obj != null) list.Add(obj);
return list;
}
//
// **********************************************************************
/// <summary>
/// Parses strings in the following format: StateName=Value.
/// </summary>
/// <param name="args">array of strings in format StateName=Value</param>
/// <param name="isQuoted">true if value can be enclosed in double quotas</param>
/// <returns>
/// NameValueCollection of parsed name-value pairs
/// </returns>
// **********************************************************************
//
static public NameValueCollection ParseNamesAndValues(string[] args, bool isQuoted)
{
NameValueCollection result = new NameValueCollection();
if (args != null)
{
for (int i = 0; i < args.Length; i++)
{
string name = "";
string value = "";
if (ConvertUtils.NotEmpty(args[i]))
{
int index = args[i].IndexOf("=");
if (index > 0)
{
name = args[i].Substring(0, index);
value = args[i].Substring(index + 1);
if (isQuoted)
value = ConvertText.ExtractQuotedString(value);
}
else if (index < 0)
{
name = args[i];
}
}
if (ConvertUtils.NotEmpty(name))
result[name] = value;
}
}
return result;
}
//
// **********************************************************************
/// <summary>
/// Parses strings in the following format: StateName=Value.
/// </summary>
/// <param name="args">array of strings in format StateName=Value</param>
/// <returns>
/// NameValueCollection of parsed name-value pairs
/// </returns>
// **********************************************************************
//
static public NameValueCollection ParseNamesAndValues(string[] args)
{
return ParseNamesAndValues(args, false);
}
//
// **********************************************************************
/// <summary>
/// Parses strings in the following format: StateName="Value".
/// </summary>
/// <param name="args">array of strings in format StateName=Value</param>
/// <returns>
/// NameValueCollection of parsed name-value pairs
/// </returns>
// **********************************************************************
//
static public NameValueCollection ParseNamesAndQuotedValues(string[] args)
{
return ParseNamesAndValues(args, true);
}
//
// **********************************************************************
/// <summary>
/// Finds given string in the array or list.
/// </summary>
/// <param name="list">string array to find strings</param>
/// <param name="s">string to find</param>
/// <returns>
/// index of the string in array of -1 if not found
/// </returns>
// **********************************************************************
//
static public int IndexOf(IList list, string s)
{
for (int i = 0; i < list.Count; i++)
if ((string)list[i] == s)
return i;
return -1;
}
//
// **********************************************************************
/// <summary>
/// Finds given string in the array or list.
/// Case-insensitive.
/// </summary>
/// <param name="list">string array to find strings</param>
/// <param name="s">string to find</param>
/// <returns>
/// index of the string in array of -1 if not found
/// </returns>
// **********************************************************************
//
static public int IndexOfCI(IList list, string s)
{
for (int i = 0; i < list.Count; i++)
if (ConvertText.Equals((string)list[i], s))
return i;
return -1;
}
//
// **********************************************************************
/// <summary>
/// Returns dictionary (hashtable) containing all list elements.
/// </summary>
/// <param name="list">The list.</param>
/// <returns></returns>
// **********************************************************************
//
static public IDictionary GetDictionaryFromList(IList list)
{
Hashtable result = new Hashtable();
AppendDictionaryFromList(result, list);
return result;
}
//
// **********************************************************************
/// <summary>
/// Appends dictionary (hashtable) with the list elements.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="list">The list.</param>
// **********************************************************************
//
static public void AppendDictionaryFromList(IDictionary dictionary, IList list)
{
if (dictionary != null &&
list != null)
{
foreach (object element in list)
if (element != null)
dictionary[element] = element;
}
}
//
// **********************************************************************
/// <summary>
/// Returns true if the given collection is null or does not have elements.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>
/// <c>true</c> if the specified list is empty; otherwise, <c>false</c>.
/// </returns>
// **********************************************************************
//
static public bool IsEmpty(ICollection list)
{
return list == null || list.Count == 0;
}
//
// **********************************************************************
/// <summary>
/// Returns true if the given collection is null or does not have elements.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">The list.</param>
/// <returns>
/// <c>true</c> if the specified list is empty2; otherwise, <c>false</c>.
/// </returns>
// **********************************************************************
//
static public bool IsEmpty2<T>(ICollection<T> list)
{
return list == null || list.Count == 0;
}
//
// **********************************************************************
/// <summary>
/// Adds item to the list if item is not null.
/// </summary>
/// <param name="list">list to add item to</param>
/// <param name="item">item to add to list</param>
/// <returns>
/// index of the added item or -1 if item was not added
/// </returns>
// **********************************************************************
//
static public int AddIfNotNull(IList list, object item)
{
return list != null && item != null ? list.Add(item) : -1;
}
//
// **********************************************************************
/// <summary>
/// Adds item to the dictionary if item is not null.
/// </summary>
/// <param name="dictionary">dictionary to add item to</param>
/// <param name="key">key to add to dictionary</param>
/// <param name="value">value to add to dictionary</param>
// **********************************************************************
//
static public void AddIfNotNull(IDictionary dictionary, object key, object value)
{
if (dictionary != null &&
key != null &&
value != null)
dictionary[key] = value;
}
//
// **********************************************************************
/// <summary>
/// Adds item to the list if item is not null and not exists in the list.
/// </summary>
/// <param name="list">list to add item to</param>
/// <param name="item">item to add to list</param>
/// <returns>
/// index of the added item or -1 if item was not added
/// </returns>
// **********************************************************************
//
static public int AddIfNotInList(IList list, object item)
{
return (list != null && item != null && list.IndexOf(item) < 0) ? list.Add(item) : -1;
}
//
// **********************************************************************
/// <summary>
/// Adds source list items to the list if item is not null and not exists in the list.
/// </summary>
/// <param name="list">list to add item to</param>
/// <param name="sourceList">source list to add items from</param>
// **********************************************************************
//
static public void AddIfNotInList(IList list, IEnumerable sourceList)
{
if (list != null &&
sourceList != null)
{
Hashtable itemMap = new Hashtable();
foreach (object item in list)
if (item != null)
itemMap[item] = true;
foreach (object item in sourceList)
if (item != null &&
!itemMap.ContainsKey(item))
list.Add(item);
}
}
//
// **********************************************************************
/// <summary>
/// Adds a range of items into the given list.
/// </summary>
/// <typeparam name="T">type of elements</typeparam>
/// <param name="list">destination list</param>
/// <param name="sourceList">source list</param>
// **********************************************************************
//
static public void AddRange<T>(IList<T> list, IEnumerable<T> sourceList)
{
foreach (T element in sourceList)
list.Add(element);
}
//
// **********************************************************************
/// <summary>
/// Adds a range of items into the given list.
/// </summary>
/// <param name="list">destination list</param>
/// <param name="sourceList">source list</param>
// **********************************************************************
//
static public void AddRange(IList list, IEnumerable sourceList)
{
foreach (object element in sourceList)
list.Add(element);
}
//
// **********************************************************************
/// <summary>
/// Converts source list to string list.
/// </summary>
/// <param name="source">source list</param>
/// <returns>source list converted to string list</returns>
// **********************************************************************
//
static public List<string> ToStringList(IList source)
{
List<string> target = new List<string>();
if (source != null)
foreach (object o in source)
target.Add(ConvertUtils.ToString(o));
return target;
}
//
// **********************************************************************
/// <summary>
/// Moves the given objects inside the given collection by the offset.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objectsToMove">the objects being moved</param>
/// <param name="objects">the object-holder collection</param>
/// <param name="offset">the offset of the move</param>
/// <returns>true if succeeded</returns>
// **********************************************************************
//
static public bool Move<T>(IList<T> objectsToMove, IList<T> objects, int offset)
{
int[] oldIndexes = new int[objectsToMove.Count];
for (int i = 0; i < objectsToMove.Count; i++)
oldIndexes[i] = objects.IndexOf(objectsToMove[i]);
//
// Here we get the index of the leading item,
// i.e. the future index of the first item in the direction of the move.
//
int leadingIndex = (offset > 0) ? oldIndexes[oldIndexes.Length - 1] + offset : (offset < 0) ? oldIndexes[0] + offset : -1;
//
// If the leading row is not in the range of the grid visible items - then do nothing.
//
if (leadingIndex >= objects.Count ||
leadingIndex < 0)
return false;
if (offset > 0)
{
for (int i = objectsToMove.Count - 1; i >= 0; i--)
Move(objectsToMove[i], objects, offset);
}
else
{
for (int i = 0; i < objectsToMove.Count; i++)
Move(objectsToMove[i], objects, offset);
}
return true;
}
//
// **********************************************************************
/// <summary>
/// Moves the given object inside the given collection by the offset.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objectToMove">the object being moved</param>
/// <param name="objects">the object-holder collection</param>
/// <param name="offset">the offset to move by</param>
/// <returns>true if succeeded</returns>
// **********************************************************************
//
static public bool Move<T>(T objectToMove, IList<T> objects, int offset)
{
int oldIndex = objects.IndexOf(objectToMove);
if (oldIndex < 0)
return false;
int newIndex = oldIndex + offset;
if (newIndex < 0 || newIndex >= objects.Count)
return false;
objects.RemoveAt(oldIndex);
objects.Insert(newIndex, objectToMove);
return true;
}
//
// **********************************************************************
/// <summary>
/// Converts given enumrable to the typed list.
/// </summary>
/// <typeparam name="T">type of list elements</typeparam>
/// <param name="source">source enumerable</param>
/// <returns>converted list</returns>
// **********************************************************************
//
static public List<T> ToList<T>(IEnumerable source)
{
List<T> list = new List<T>();
foreach (T item in source)
list.Add(item);
return list;
}
//
// **********************************************************************
/// <summary>
/// Compares two lists.
/// Considers list equal if two lists contains the same elements,
/// element order is ignored.
/// </summary>
/// <typeparam name="T">type of list elements</typeparam>
/// <param name="l1">first list</param>
/// <param name="l2">second list</param>
/// <returns>true if lists are equal, false otherwise</returns>
// **********************************************************************
//
static public bool CompareUnOrdered<T>(IList<T> l1, IList<T> l2)
{
if (l1 == null &&
l2 == null)
return true;
if (l1 == null ||
l2 == null)
return false;
if (l1.Count != l2.Count)
return false;
foreach (T item in l1)
if (!l2.Contains(item))
return false;
foreach (T item in l2)
if (!l1.Contains(item))
return false;
return true;
}
//
// **********************************************************************
/// <summary>
/// Compares two lists. Element order is important.
/// </summary>
/// <typeparam name="T">type of list elements</typeparam>
/// <param name="l1">first list</param>
/// <param name="l2">second list</param>
/// <returns>true if lists are equal, false otherwise</returns>
// **********************************************************************
//
static public bool CompareOrdered<T>(IList<T> l1, IList<T> l2)
{
if (l1 == null &&
l2 == null)
return true;
if (l1 == null ||
l2 == null)
return false;
if (l1.Count != l2.Count)
return false;
for (int i = 0; i < l1.Count; i++)
if (!Equals(l1[i], l2[i]))
return false;
return true;
}
//
// **********************************************************************
/// <summary>
/// Compares two lists. Element order is important.
/// </summary>
/// <typeparam name="T">type of list elements</typeparam>
/// <param name="l1">first list</param>
/// <param name="l2">second list</param>
/// <returns>true if lists are equal, otherwise false</returns>
// **********************************************************************
//
static public bool CompareOrdered<T>(IList l1, IList l2) where T : class
{
if (l1 == null &&
l2 == null)
return true;
if (l1 == null ||
l2 == null)
return false;
if (l1.Count != l2.Count)
return false;
for (int i = 0; i < l1.Count; i++)
if (!Equals(l1[i] as T, l2[i] as T))
return false;
return true;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using Prism.Properties;
namespace Prism.Modularity
{
/// <summary>
/// The <see cref="ModuleCatalogBase"/> holds information about the modules that can be used by the
/// application. Each module is described in a <see cref="IModuleInfo"/> class, that records the
/// name, type and location of the module.
///
/// It also verifies that the <see cref="ModuleCatalogBase"/> is internally valid. That means that
/// it does not have:
/// <list>
/// <item>Circular dependencies</item>
/// <item>Missing dependencies</item>
/// <item>
/// Invalid dependencies, such as a Module that's loaded at startup that depends on a module
/// that might need to be retrieved.
/// </item>
/// </list>
/// The <see cref="ModuleCatalogBase"/> also serves as a baseclass for more specialized Catalogs .
/// </summary>
public class ModuleCatalogBase : IModuleCatalog
{
private ModuleCatalogItemCollection _items { get; }
private bool _isLoaded;
/// <summary>
/// Initializes a new instance of the <see cref="IModuleCatalog"/> class.
/// </summary>
public ModuleCatalogBase()
{
_items = new ModuleCatalogItemCollection();
_items.CollectionChanged += ItemsCollectionChanged;
}
/// <summary>
/// Initializes a new instance of the <see cref="IModuleCatalog"/> class while providing an
/// initial list of <see cref="IModuleInfo"/>s.
/// </summary>
/// <param name="modules">The initial list of modules.</param>
public ModuleCatalogBase(IEnumerable<IModuleInfo> modules)
: this()
{
if (modules == null) throw new ArgumentNullException(nameof(modules));
foreach (IModuleInfo moduleInfo in modules)
{
Items.Add(moduleInfo);
}
}
/// <summary>
/// Gets the items in the <see cref="IModuleCatalog"/>. This property is mainly used to add <see cref="IModuleInfoGroup"/>s or
/// <see cref="IModuleInfo"/>s through XAML.
/// </summary>
/// <value>The items in the catalog.</value>
public Collection<IModuleCatalogItem> Items => _items;
/// <summary>
/// Gets all the <see cref="IModuleInfo"/> classes that are in the <see cref="IModuleCatalog"/>, regardless
/// if they are within a <see cref="IModuleInfoGroup"/> or not.
/// </summary>
/// <value>The modules.</value>
public virtual IEnumerable<IModuleInfo> Modules => GrouplessModules.Union(Groups.SelectMany(g => g));
/// <summary>
/// Gets the <see cref="IModuleInfoGroup"/>s that have been added to the <see cref="IModuleCatalog"/>.
/// </summary>
/// <value>The groups.</value>
public IEnumerable<IModuleInfoGroup> Groups => Items.OfType<IModuleInfoGroup>();
/// <summary>
/// Gets or sets a value that remembers whether the <see cref="ModuleCatalogBase"/> has been validated already.
/// </summary>
protected bool Validated { get; set; }
/// <summary>
/// Returns the list of <see cref="IModuleInfo"/>s that are not contained within any <see cref="IModuleInfoGroup"/>.
/// </summary>
/// <value>The groupless modules.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Groupless")]
protected IEnumerable<IModuleInfo> GrouplessModules => Items.OfType<IModuleInfo>();
/// <summary>
/// Loads the catalog if necessary.
/// </summary>
public virtual void Load()
{
_isLoaded = true;
InnerLoad();
}
/// <summary>
/// Return the list of <see cref="IModuleInfo"/>s that <paramref name="moduleInfo"/> depends on.
/// </summary>
/// <remarks>
/// If the <see cref="IModuleCatalog"/> was not yet validated, this method will call <see cref="Validate"/>.
/// </remarks>
/// <param name="moduleInfo">The <see cref="IModuleInfo"/> to get the </param>
/// <returns>An enumeration of <see cref="IModuleInfo"/> that <paramref name="moduleInfo"/> depends on.</returns>
public virtual IEnumerable<IModuleInfo> GetDependentModules(IModuleInfo moduleInfo)
{
this.EnsureCatalogValidated();
return this.GetDependentModulesInner(moduleInfo);
}
/// <summary>
/// Returns a list of <see cref="IModuleInfo"/>s that contain both the <see cref="IModuleInfo"/>s in
/// <paramref name="modules"/>, but also all the modules they depend on.
/// </summary>
/// <param name="modules">The modules to get the dependencies for.</param>
/// <returns>
/// A list of <see cref="IModuleInfo"/> that contains both all <see cref="IModuleInfo"/>s in <paramref name="modules"/>
/// but also all the <see cref="IModuleInfo"/> they depend on.
/// </returns>
public virtual IEnumerable<IModuleInfo> CompleteListWithDependencies(IEnumerable<IModuleInfo> modules)
{
if (modules == null)
throw new ArgumentNullException(nameof(modules));
EnsureCatalogValidated();
List<IModuleInfo> completeList = new List<IModuleInfo>();
List<IModuleInfo> pendingList = modules.ToList();
while (pendingList.Count > 0)
{
var moduleInfo = pendingList[0];
foreach (var dependency in GetDependentModules(moduleInfo))
{
if (!completeList.Contains(dependency) && !pendingList.Contains(dependency))
{
pendingList.Add(dependency);
}
}
pendingList.RemoveAt(0);
completeList.Add(moduleInfo);
}
IEnumerable<IModuleInfo> sortedList = Sort(completeList);
return sortedList;
}
/// <summary>
/// Validates the <see cref="IModuleCatalog"/>.
/// </summary>
/// <exception cref="ModularityException">When validation of the <see cref="IModuleCatalog"/> fails.</exception>
public virtual void Validate()
{
ValidateUniqueModules();
ValidateDependencyGraph();
ValidateCrossGroupDependencies();
ValidateDependenciesInitializationMode();
Validated = true;
}
/// <summary>
/// Adds a <see cref="IModuleInfo"/> to the <see cref="IModuleCatalog"/>.
/// </summary>
/// <param name="moduleInfo">The <see cref="IModuleInfo"/> to add.</param>
/// <returns>The <see cref="IModuleCatalog"/> for easily adding multiple modules.</returns>
public virtual IModuleCatalog AddModule(IModuleInfo moduleInfo)
{
Items.Add(moduleInfo);
return this;
}
/// <summary>
/// Initializes the catalog, which may load and validate the modules.
/// </summary>
/// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalogBase"/> fails, because this method calls <see cref="Validate"/>.</exception>
public virtual void Initialize()
{
if (!_isLoaded)
{
Load();
}
Validate();
}
/// <summary>
/// Checks for cyclic dependencies, by calling the dependency solver.
/// </summary>
/// <param name="modules">the.</param>
/// <returns></returns>
protected static string[] SolveDependencies(IEnumerable<IModuleInfo> modules)
{
if (modules == null)
throw new ArgumentNullException(nameof(modules));
ModuleDependencySolver solver = new ModuleDependencySolver();
foreach (var data in modules)
{
solver.AddModule(data.ModuleName);
if (data.DependsOn != null)
{
foreach (string dependency in data.DependsOn)
{
solver.AddDependency(data.ModuleName, dependency);
}
}
}
if (solver.ModuleCount > 0)
{
return solver.Solve();
}
return new string[0];
}
/// <summary>
/// Ensures that all the dependencies within <paramref name="modules"/> refer to <see cref="IModuleInfo"/>s
/// within that list.
/// </summary>
/// <param name="modules">The modules to validate modules for.</param>
/// <exception cref="ModularityException">
/// Throws if a <see cref="IModuleInfo"/> in <paramref name="modules"/> depends on a module that's
/// not in <paramref name="modules"/>.
/// </exception>
/// <exception cref="ArgumentNullException">Throws if <paramref name="modules"/> is <see langword="null"/>.</exception>
protected static void ValidateDependencies(IEnumerable<IModuleInfo> modules)
{
if (modules == null)
throw new ArgumentNullException(nameof(modules));
var moduleNames = modules.Select(m => m.ModuleName).ToList();
foreach (var moduleInfo in modules)
{
if (moduleInfo.DependsOn != null && moduleInfo.DependsOn.Except(moduleNames).Any())
{
throw new ModularityException(
moduleInfo.ModuleName,
string.Format(CultureInfo.CurrentCulture, Resources.ModuleDependenciesNotMetInGroup, moduleInfo.ModuleName));
}
}
}
/// <summary>
/// Does the actual work of loading the catalog. The base implementation does nothing.
/// </summary>
protected virtual void InnerLoad()
{
}
/// <summary>
/// Sorts a list of <see cref="IModuleInfo"/>s. This method is called by <see cref="CompleteListWithDependencies"/>
/// to return a sorted list.
/// </summary>
/// <param name="modules">The <see cref="IModuleInfo"/>s to sort.</param>
/// <returns>Sorted list of <see cref="IModuleInfo"/>s</returns>
protected virtual IEnumerable<IModuleInfo> Sort(IEnumerable<IModuleInfo> modules)
{
foreach (string moduleName in SolveDependencies(modules))
{
yield return modules.First(m => m.ModuleName == moduleName);
}
}
/// <summary>
/// Makes sure all modules have an Unique name.
/// </summary>
/// <exception cref="DuplicateModuleException">
/// Thrown if the names of one or more modules are not unique.
/// </exception>
protected virtual void ValidateUniqueModules()
{
List<string> moduleNames = Modules.Select(m => m.ModuleName).ToList();
string duplicateModule = moduleNames.FirstOrDefault(
m => moduleNames.Count(m2 => m2 == m) > 1);
if (duplicateModule != null)
{
throw new DuplicateModuleException(duplicateModule, string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedModule, duplicateModule));
}
}
/// <summary>
/// Ensures that there are no cyclic dependencies.
/// </summary>
protected virtual void ValidateDependencyGraph()
{
SolveDependencies(Modules);
}
/// <summary>
/// Ensures that there are no dependencies between modules on different groups.
/// </summary>
/// <remarks>
/// A groupless module can only depend on other groupless modules.
/// A module within a group can depend on other modules within the same group and/or on groupless modules.
/// </remarks>
protected virtual void ValidateCrossGroupDependencies()
{
ValidateDependencies(GrouplessModules);
foreach (var group in Groups)
{
ValidateDependencies(GrouplessModules.Union(group));
}
}
/// <summary>
/// Ensures that there are no modules marked to be loaded <see cref="InitializationMode.WhenAvailable"/>
/// depending on modules loaded <see cref="InitializationMode.OnDemand"/>
/// </summary>
protected virtual void ValidateDependenciesInitializationMode()
{
var moduleInfo = Modules.FirstOrDefault(
m =>
m.InitializationMode == InitializationMode.WhenAvailable &&
GetDependentModulesInner(m)
.Any(dependency => dependency.InitializationMode == InitializationMode.OnDemand));
if (moduleInfo != null)
{
throw new ModularityException(
moduleInfo.ModuleName,
string.Format(CultureInfo.CurrentCulture, Resources.StartupModuleDependsOnAnOnDemandModule, moduleInfo.ModuleName));
}
}
/// <summary>
/// Returns the <see cref="IModuleInfo"/> on which the received module depends on.
/// </summary>
/// <param name="moduleInfo">Module whose dependant modules are requested.</param>
/// <returns>Collection of <see cref="IModuleInfo"/> dependants of <paramref name="moduleInfo"/>.</returns>
protected virtual IEnumerable<IModuleInfo> GetDependentModulesInner(IModuleInfo moduleInfo)
{
return Modules.Where(dependantModule => moduleInfo.DependsOn.Contains(dependantModule.ModuleName));
}
/// <summary>
/// Ensures that the catalog is validated.
/// </summary>
protected virtual void EnsureCatalogValidated()
{
if (!Validated)
{
Validate();
}
}
private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (Validated)
{
EnsureCatalogValidated();
}
}
private class ModuleCatalogItemCollection : Collection<IModuleCatalogItem>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected override void InsertItem(int index, IModuleCatalogItem item)
{
base.InsertItem(index, item);
RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
protected void RaiseCollectionChanged(NotifyCollectionChangedEventArgs eventArgs)
{
CollectionChanged?.Invoke(this, eventArgs);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using Xunit;
namespace System.Collections.HashtableTests
{
public class CtorTests
{
[Fact]
public void TestCtorDefault()
{
Hashtable hash = null;
int nAttempts = 100;
int[] iIntArray = new int[nAttempts];
//
// [] Constructor: Create Hashtable using default settings.
//
hash = new Hashtable();
Assert.NotNull(hash);
// Verify that the hash tabe is empty.
Assert.Equal(hash.Count, 0);
}
[Fact]
public void TestCtorDictionarySingle()
{
// No exception
var hash = new Hashtable(new Hashtable(), 1f);
// No exception
hash = new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()), 1f), 1f), 1f), 1f);
// []test to see if elements really get copied from old dictionary to new hashtable
Hashtable tempHash = new Hashtable();
// this for assumes that MinValue is a negative!
for (long i = long.MinValue; i < long.MinValue + 100; i++)
{
tempHash.Add(i, i);
}
hash = new Hashtable(tempHash, 1f);
// make sure that new hashtable has the elements in it that old hashtable had
for (long i = long.MinValue; i < long.MinValue + 100; i++)
{
Assert.True(hash.ContainsKey(i));
Assert.True(hash.ContainsValue(i));
}
//[]make sure that there are no connections with the old and the new hashtable
tempHash.Clear();
for (long i = long.MinValue; i < long.MinValue + 100; i++)
{
Assert.True(hash.ContainsKey(i));
Assert.True(hash.ContainsValue(i));
}
}
[Fact]
public void TestCtorDictionarySingleNegative()
{
// variables used for tests
Hashtable hash = null;
Assert.Throws<ArgumentNullException>(() =>
{
hash = new Hashtable(null, 1);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(new Hashtable(), Int32.MinValue);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(new Hashtable(), Single.NaN);
}
);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(new Hashtable(), 100.1f);
}
);
}
[Fact]
public void TestCtorDictionary()
{
Hashtable hash = null;
Hashtable hash2 = null;
Int32 i4a;
//
// [] Constructor: null
//
Assert.Throws<ArgumentNullException>(() =>
{
hash = new Hashtable((IDictionary)null);
}
);
//
// []Constructor: empty
//
hash2 = new Hashtable(); //empty dictionary
// No exception
hash = new Hashtable(hash2);
//
// []Constructor: dictionary with 100 entries...
//
hash2 = new Hashtable();
for (int i = 0; i < 100; i++)
{
hash2.Add("key_" + i, "val_" + i);
}
// No exception
hash = new Hashtable(hash2);
//Confirming the values
Hashtable hash3 = new Hashtable(200);
for (int ii = 0; ii < 100; ii++)
{
i4a = ii;
hash3.Add("key_" + ii, i4a);
}
hash = new Hashtable(hash3);
Assert.Equal(100, hash.Count);
for (int ii = 0; ii < 100; ii++)
{
Assert.Equal(ii, (int)hash3["key_" + ii]);
Assert.True(hash3.ContainsKey("key_" + ii));
}
Assert.False(hash3.ContainsKey("key_100"));
}
[Fact]
public void TestCtorIntSingle()
{
// variables used for tests
Hashtable hash = null;
// [] should get ArgumentException if trying to have large num of entries
Assert.Throws<ArgumentException>(() =>
{
hash = new Hashtable(int.MaxValue, .1f);
}
);
// []should not get any exceptions for valid values - we also check that the HT works here
hash = new Hashtable(100, .1f);
int iNumberOfElements = 100;
for (int i = 0; i < iNumberOfElements; i++)
{
hash.Add("Key_" + i, "Value_" + i);
}
//Count
Assert.Equal(hash.Count, iNumberOfElements);
DictionaryEntry[] strValueArr = new DictionaryEntry[hash.Count];
hash.CopyTo(strValueArr, 0);
Hashtable hsh3 = new Hashtable();
for (int i = 0; i < iNumberOfElements; i++)
{
Assert.True(hash.Contains("Key_" + i), "Error, Expected value not returned, " + hash.Contains("Key_" + i));
Assert.True(hash.ContainsKey("Key_" + i), "Error, Expected value not returned, " + hash.ContainsKey("Key_" + i));
Assert.True(hash.ContainsValue("Value_" + i), "Error, Expected value not returned, " + hash.ContainsValue("Value_" + i));
//we still need a way to make sure that there are all these unique values here -see below code for that
Assert.True(hash.ContainsValue(((DictionaryEntry)strValueArr[i]).Value), "Error, Expected value not returned, " + ((DictionaryEntry)strValueArr[i]).Value);
hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null);
}
}
[Fact]
public void TestCtorIntSingleNegative()
{
Hashtable hash = null;
// []should get ArgumentOutOfRangeException if capacity range is not correct
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(5, .01f);
}
);
// should get ArgumentOutOfRangeException if range is not correct
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(5, 100.1f);
}
);
// should get OutOfMemoryException if Dictionary is null
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(int.MaxValue, 100.1f);
}
);
// []ArgumentOutOfRangeException if capacity is less than zero.
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(int.MinValue, 10.1f);
}
);
}
[Fact]
public void TestCtorIntCapacity()
{
//--------------------------------------------------------------------------
// Variable definitions.
//--------------------------------------------------------------------------
Hashtable hash = null;
int nCapacity = 100;
//
// [] Constructor: Create Hashtable using a capacity value.
//
hash = new Hashtable(nCapacity);
Assert.NotNull(hash);
// Verify that the hash tabe is empty.
Assert.Equal(0, hash.Count);
//
// [] Constructor: Create Hashtablewith zero capacity value - valid.
//
hash = new Hashtable(0);
//
// []Constructor: Create Hashtable using a invalid capacity value.
//
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(-1);
}
);
Assert.Throws<ArgumentException>(() => { hash = new Hashtable(Int32.MaxValue); });
}
[Fact]
public void TestCtorIntFloat()
{
//--------------------------------------------------------------------------
// Variable definitions.
//--------------------------------------------------------------------------
Hashtable hash = null;
int nCapacity = 100;
float fltLoadFactor = (float).5; // Note: default load factor is .73
//
// []Constructor: Create Hashtable using a capacity and load factor.
//
hash = new Hashtable(nCapacity, fltLoadFactor);
Assert.NotNull(hash);
// Verify that the hash tabe is empty.
Assert.Equal(0, hash.Count);
//
// [] Constructor: Create Hashtable using a zero capacity and some load factor.
//
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(-1, fltLoadFactor);
});
//
// [] Constructor: Create Hashtable using a invalid capacity and valid load factor.
//
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(nCapacity, .09f); // min lf allowed is .01
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(nCapacity, 1.1f);
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
hash = new Hashtable(-1, -1f);
});
Assert.Throws<OutOfMemoryException>(() =>
{
hash = new Hashtable((int)100000000, .5f);
});
}
[Fact]
public void DebuggerAttributeTests()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new Hashtable());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection.Internal;
using TestUtilities;
using Xunit;
namespace System.Reflection.Metadata.Tests
{
//
// Test reading/decoding of compressed integers as described in the ECMA 335 CLI specification.
// See Section II.3.2 - Blobs and Signatures.
//
public class CompressedIntegerTests
{
[Fact]
public void DecompressUnsignedIntegersFromSpecExamples()
{
// These examples are straight from the CLI spec.
// Test that we read them correctly straight from their explicit encoded values.
Assert.Equal(0x03, ReadCompressedUnsignedInteger(0x03));
Assert.Equal(0x7f, ReadCompressedUnsignedInteger(0x7f));
Assert.Equal(0x80, ReadCompressedUnsignedInteger(0x80, 0x80));
Assert.Equal(0x2E57, ReadCompressedUnsignedInteger(0xAE, 0x57));
Assert.Equal(0x3FFF, ReadCompressedUnsignedInteger(0xBF, 0xFF));
Assert.Equal(0x4000, ReadCompressedUnsignedInteger(0xC0, 0x00, 0x40, 0x00));
Assert.Equal(0x1FFFFFFF, ReadCompressedUnsignedInteger(0xDF, 0xFF, 0xFF, 0xFF));
}
[Fact]
public void CompressUnsignedIntegersFromSpecExamples()
{
// These examples are straight from the CLI spec.
// Test that our compression routine (written below for test purposes) encodes them the same way.
AssertEx.Equal(CompressUnsignedInteger(0x03), new byte[] { 0x03 });
AssertEx.Equal(CompressUnsignedInteger(0x7F), new byte[] { 0x7f });
AssertEx.Equal(CompressUnsignedInteger(0x80), new byte[] { 0x80, 0x80 });
AssertEx.Equal(CompressUnsignedInteger(0x2E57), new byte[] { 0xAE, 0x57 });
AssertEx.Equal(CompressUnsignedInteger(0x3FFF), new byte[] { 0xBF, 0xFF });
AssertEx.Equal(CompressUnsignedInteger(0x4000), new byte[] { 0xC0, 0x00, 0x40, 0x00 });
AssertEx.Equal(CompressUnsignedInteger(0x1FFFFFFF), new byte[] { 0xDF, 0xFF, 0xFF, 0xFF });
}
[Fact]
public void DecompressInvalidUnsignedIntegers()
{
// Too few bytes
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(new byte[0]));
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0x80));
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0xC0, 0xFF));
// No compressed integer can lead with 3 bits set.
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0xFF, 0xFF, 0xFF, 0xFF));
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedUnsignedInteger(0xE0, 0x00, 0x00, 0x00));
}
[Fact]
public void DecompressSignedIntegersFromSpecExamples()
{
// These examples are straight from the CLI spec.
// Test that we read them correctly straight from their explicit encoded values.
Assert.Equal(3, ReadCompressedSignedInteger(0x06));
Assert.Equal(-3, ReadCompressedSignedInteger(0x7B));
Assert.Equal(64, ReadCompressedSignedInteger(0x80, 0x80));
Assert.Equal(-64, ReadCompressedSignedInteger(0x01));
Assert.Equal(8192, ReadCompressedSignedInteger(0xC0, 0x00, 0x40, 0x00));
Assert.Equal(-8192, ReadCompressedSignedInteger(0x80, 0x01));
Assert.Equal(268435455, ReadCompressedSignedInteger(0xDF, 0xFF, 0xFF, 0xFE));
Assert.Equal(-268435456, ReadCompressedSignedInteger(0xC0, 0x00, 0x00, 0x01));
}
[Fact]
public void CheckCompressedUnsignedIntegers()
{
// Test that we can round trip unsigned integers near the edge conditions
// Around 0
CheckCompressedUnsignedInteger(0, 1);
CheckCompressedUnsignedInteger(-1, -1);
CheckCompressedUnsignedInteger(1, 1);
// Near 1 byte limit
CheckCompressedUnsignedInteger((1 << 7), 2);
CheckCompressedUnsignedInteger((1 << 7) - 1, 1);
CheckCompressedUnsignedInteger((1 << 7) + 1, 2);
// Near 2 byte limit
CheckCompressedUnsignedInteger((1 << 14), 4);
CheckCompressedUnsignedInteger((1 << 14) - 1, 2);
CheckCompressedUnsignedInteger((1 << 14) + 1, 4);
// Near 4 byte limit
CheckCompressedUnsignedInteger((1 << 29), -1);
CheckCompressedUnsignedInteger((1 << 29) - 1, 4);
CheckCompressedUnsignedInteger((1 << 29) + 1, -1);
}
[Fact]
public void CompressSignedIntegersFromSpecExamples()
{
// These examples are straight from the CLI spec.
// Test that our compression routine (written below for test purposes) encodes them the same way.
AssertEx.Equal(CompressSignedInteger(3), new byte[] { 0x06 });
AssertEx.Equal(CompressSignedInteger(-3), new byte[] { 0x7b });
AssertEx.Equal(CompressSignedInteger(64), new byte[] { 0x80, 0x80 });
AssertEx.Equal(CompressSignedInteger(-64), new byte[] { 0x01 });
AssertEx.Equal(CompressSignedInteger(8192), new byte[] { 0xC0, 0x00, 0x40, 0x00 });
AssertEx.Equal(CompressSignedInteger(-8192), new byte[] { 0x80, 0x01 });
AssertEx.Equal(CompressSignedInteger(268435455), new byte[] { 0xDF, 0xFF, 0xFF, 0xFE });
AssertEx.Equal(CompressSignedInteger(-268435456), new byte[] { 0xC0, 0x00, 0x00, 0x01 });
}
[Fact]
public unsafe void DecompressInvalidSignedIntegers()
{
// Too few bytes
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(new byte[0]));
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0x80));
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0xC0, 0xFF));
// No compressed integer can lead with 3 bits set.
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0xFF, 0xFF, 0xFF, 0xFF));
Assert.Equal(BlobReader.InvalidCompressedInteger, ReadCompressedSignedInteger(0xE0, 0x00, 0x00, 0x00));
}
[Fact]
public void CheckCompressedSignedIntegers()
{
// Test that we can round trip signed integers near the edge conditions.
// around 0
CheckCompressedSignedInteger(-1, 1);
CheckCompressedSignedInteger(1, 1);
// around 1 byte limit
CheckCompressedSignedInteger(-(1 << 6), 1);
CheckCompressedSignedInteger(-(1 << 6) - 1, 2);
CheckCompressedSignedInteger(-(1 << 6) + 1, 1);
CheckCompressedSignedInteger((1 << 6), 2);
CheckCompressedSignedInteger((1 << 6) - 1, 1);
CheckCompressedSignedInteger((1 << 6) + 1, 2);
// around 2 byte limit
CheckCompressedSignedInteger(-(1 << 13), 2);
CheckCompressedSignedInteger(-(1 << 13) - 1, 4);
CheckCompressedSignedInteger(-(1 << 13) + 1, 2);
CheckCompressedSignedInteger((1 << 13), 4);
CheckCompressedSignedInteger((1 << 13) - 1, 2);
CheckCompressedSignedInteger((1 << 13) + 1, 4);
// around 4 byte limit
CheckCompressedSignedInteger(-(1 << 28), 4);
CheckCompressedSignedInteger(-(1 << 28) - 1, -1);
CheckCompressedSignedInteger(-(1 << 28) + 1, 4);
CheckCompressedSignedInteger((1 << 28), -1);
CheckCompressedSignedInteger((1 << 28) - 1, 4);
CheckCompressedSignedInteger((1 << 28) + 1, -1);
}
private void CheckCompressedSignedInteger(int valueToRoundTrip, int numberOfBytesExpected)
{
CheckCompressedInteger(valueToRoundTrip, numberOfBytesExpected, CompressSignedInteger, ReadCompressedSignedInteger);
}
private void CheckCompressedUnsignedInteger(int valueToRoundTrip, int numberOfBytesExpected)
{
CheckCompressedInteger(valueToRoundTrip, numberOfBytesExpected, CompressUnsignedInteger, ReadCompressedUnsignedInteger);
}
private void CheckCompressedInteger(int valueToRoundTrip, int numberOfBytesExpected, Func<int, byte[]> compress, Func<byte[], int> read)
{
byte[] bytes = compress(valueToRoundTrip);
if (bytes == null)
{
Assert.Equal(-1, numberOfBytesExpected);
}
else
{
Assert.Equal(numberOfBytesExpected, bytes.Length);
Assert.Equal(valueToRoundTrip, read(bytes));
}
}
// NOTE: The compression routines below can be optimized, but please don't do that.
// The whole idea is to follow the verbal descriptions of the algorithms in
// the spec as closely as possible.
private byte[] CompressUnsignedInteger(int value)
{
if (value < 0)
{
return null; // too small
}
if (value < (1 << 7))
{
return EncodeInteger(value, 1);
}
if (value < (1 << 14))
{
return EncodeInteger(value, 2);
}
if (value < (1 << 29))
{
return EncodeInteger(value, 4);
}
return null; // too big
}
private byte[] CompressSignedInteger(int value)
{
if (value >= -(1 << 6) && value < (1 << 6))
{
return EncodeInteger(Rotate(value, 0x7f), 1);
}
if (value >= -(1 << 13) && value < (1 << 13))
{
return EncodeInteger(Rotate(value, 0x3fff), 2);
}
if (value >= -(1 << 28) && value < (1 << 28))
{
return EncodeInteger(Rotate(value, 0x1fffffff), 4);
}
return null; // out of compressible range.
}
private int Rotate(int value, int mask)
{
int signBit = value >= 0 ? 0 : 1;
value <<= 1;
value |= signBit;
value &= mask;
return value;
}
private byte[] EncodeInteger(int value, int byteCount)
{
Assert.True(value >= 0);
switch (byteCount)
{
case 1:
Assert.True(value < (1 << 7));
return new byte[]
{
// 1 byte encoding: bit 7 clear,
// 7-bit value in bits 0-6
(byte)value
};
case 2:
Assert.True(value < (1 << 14));
return new byte[]
{
// 2 byte encoding: bit 15 set, bit 14 clear,
// 14-bit value stored big-endian in bits 0-13
(byte)(0x80 | ((value >> 8) & 0x3f)),
(byte)( ((value >> 0) & 0xff)),
};
case 4:
Assert.True(value < (1 << 29));
return new byte[]
{
// 4 byte encoding: bit 31 set, bit 30 set, bit 29 clear,
// 29-bit value stored big-endian in bits 0-28
(byte)(0xC0 | ((value >> 24) & 0x1f)),
(byte)( ((value >> 16) & 0xff)),
(byte)( ((value >> 8) & 0xff)),
(byte)( ((value >> 0) & 0xff)),
};
default:
throw new ArgumentOutOfRangeException();
}
}
private int ReadCompressedUnsignedInteger(params byte[] bytes)
{
return ReadCompressedInteger(
bytes,
delegate (ref BlobReader reader, out int value) { return reader.TryReadCompressedInteger(out value); },
delegate (ref BlobReader reader) { return reader.ReadCompressedInteger(); });
}
private int ReadCompressedSignedInteger(params byte[] bytes)
{
return ReadCompressedInteger(
bytes,
delegate (ref BlobReader reader, out int value) { return reader.TryReadCompressedSignedInteger(out value); },
delegate (ref BlobReader reader) { return reader.ReadCompressedSignedInteger(); });
}
private delegate bool TryReadFunc(ref BlobReader reader, out int value);
private delegate int ReadFunc(ref BlobReader reader);
private unsafe int ReadCompressedInteger(byte[] bytes, TryReadFunc tryRead, ReadFunc read)
{
fixed (byte* ptr = bytes)
{
var reader = new BlobReader(new MemoryBlock(ptr, bytes.Length));
int value;
bool valid = tryRead(ref reader, out value);
if (valid)
{
Assert.Equal(bytes.Length, reader.Offset);
reader.Reset();
Assert.Equal(value, read(ref reader));
Assert.Equal(bytes.Length, reader.Offset);
}
else
{
Assert.Equal(0, reader.Offset);
Assert.Throws<BadImageFormatException>(() => reader.ReadCompressedInteger());
Assert.Equal(value, BlobReader.InvalidCompressedInteger);
Assert.Equal(0, reader.Offset);
}
return value;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedSslCertificatesClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
AggregatedListSslCertificatesRequest request = new AggregatedListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, SslCertificatesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
AggregatedListSslCertificatesRequest request = new AggregatedListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, SslCertificatesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, SslCertificatesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, SslCertificatesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteSslCertificateRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
DeleteSslCertificateRequest request = new DeleteSslCertificateRequest
{
RequestId = "",
SslCertificate = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteSslCertificateRequest, CallSettings)
// Additional: DeleteAsync(DeleteSslCertificateRequest, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
DeleteSslCertificateRequest request = new DeleteSslCertificateRequest
{
RequestId = "",
SslCertificate = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Delete(project, sslCertificate);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.DeleteAsync(project, sslCertificate);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetSslCertificateRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
GetSslCertificateRequest request = new GetSslCertificateRequest
{
SslCertificate = "",
Project = "",
};
// Make the request
SslCertificate response = sslCertificatesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetSslCertificateRequest, CallSettings)
// Additional: GetAsync(GetSslCertificateRequest, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
GetSslCertificateRequest request = new GetSslCertificateRequest
{
SslCertificate = "",
Project = "",
};
// Make the request
SslCertificate response = await sslCertificatesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
SslCertificate response = sslCertificatesClient.Get(project, sslCertificate);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
SslCertificate response = await sslCertificatesClient.GetAsync(project, sslCertificate);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertSslCertificateRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
InsertSslCertificateRequest request = new InsertSslCertificateRequest
{
RequestId = "",
SslCertificateResource = new SslCertificate(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertSslCertificateRequest, CallSettings)
// Additional: InsertAsync(InsertSslCertificateRequest, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
InsertSslCertificateRequest request = new InsertSslCertificateRequest
{
RequestId = "",
SslCertificateResource = new SslCertificate(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, SslCertificate, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
SslCertificate sslCertificateResource = new SslCertificate();
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Insert(project, sslCertificateResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, SslCertificate, CallSettings)
// Additional: InsertAsync(string, SslCertificate, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
SslCertificate sslCertificateResource = new SslCertificate();
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.InsertAsync(project, sslCertificateResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
ListSslCertificatesRequest request = new ListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (SslCertificate item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
ListSslCertificatesRequest request = new ListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SslCertificate item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (SslCertificate item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SslCertificate item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
// uncomment to track garbage collection of widgets
//#define TRACK_GC
using System;
using System.Globalization;
using System.Linq.Expressions;
namespace Eto
{
/// <summary>
/// Interface for widgets that have a control object
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public interface IControlObjectSource
{
/// <summary>
/// Gets the control object for this widget
/// </summary>
/// <value>The control object for the widget</value>
object ControlObject { get; }
}
/// <summary>
/// Interface for widgets that have a handler
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public interface IHandlerSource
{
/// <summary>
/// Gets the platform handler object for the widget
/// </summary>
/// <value>The handler for the widget</value>
object Handler { get; }
}
/// <summary>
/// Interface to get the callback object for a widget
/// </summary>
public interface ICallbackSource
{
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <remarks>
/// The callback should implement the parent class' callback interface so that there only needs
/// to be a single callback for the entire hierarchy.
///
/// This should return a static instance to avoid having overhead for each instance of your widget.
/// </remarks>
/// <returns>The callback instance to use for this widget</returns>
object Callback { get; }
}
/// <summary>
/// Base widget class for all objects requiring a platform-specific implementation
/// </summary>
/// <remarks>
/// The Widget is the base of all abstracted objects that have platform-specific implementations.
///
/// To implement the handler for a widget, use the <see cref="Eto.WidgetHandler{TWidget}"/> as the base class.
/// </remarks>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[RuntimeNameProperty("ID")]
public abstract class Widget : IHandlerSource, IDisposable, ICallbackSource
{
IHandler WidgetHandler { get { return Handler as IHandler; } }
/// <summary>
/// Gets the platform that was used to create the <see cref="Handler"/> for this widget
/// </summary>
/// <remarks>
/// This gets set to the current <see cref="Eto.Platform.Instance"/> during the construction of the object
/// </remarks>
public Platform Platform { get; private set; }
/// <summary>
/// Gets the platform-specific handler for this widget
/// </summary>
public object Handler { get; internal set; }
/// <summary>
/// Gets the native platform-specific handle for integration purposes
/// </summary>
/// <value>The native handle.</value>
public IntPtr NativeHandle
{
get { return WidgetHandler.NativeHandle; }
}
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <remarks>
/// The callback should implement the parent class' <see cref="ICallback"/> interface so that there only needs
/// to be a single callback for the entire hierarchy.
///
/// This should return a static instance to avoid having overhead for each instance of your control.
/// </remarks>
/// <returns>The callback instance to use for this widget</returns>
protected virtual object GetCallback() { return null; }
object ICallbackSource.Callback { get { return GetCallback(); } }
/// <summary>>
/// Base callback interface for all widgets
/// </summary>
public interface ICallback
{
}
/// <summary>
/// Handler interface for the <see cref="Widget"/> class
/// </summary>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public interface IHandler
{
/// <summary>
/// Gets or sets an ID for the widget
/// </summary>
/// <remarks>
/// Some platforms may use this to identify controls (e.g. web)
/// </remarks>
string ID { get; set; }
/// <summary>
/// Gets the widget this handler is implemented for
/// </summary>
Widget Widget { get; set; }
/// <summary>
/// Gets the native platform-specific handle for integration purposes
/// </summary>
/// <value>The native handle.</value>
IntPtr NativeHandle { get; }
/// <summary>
/// Called after the widget is constructed
/// </summary>
/// <remarks>
/// This gets called automatically after the control is constructed and the <see cref="Widget"/> and <see cref="Platform"/> properties are set.
/// When the handler has specialized construction methods, then the <see cref="AutoInitializeAttribute"/> can be used to disable automatic
/// initialization. In this case, it is the responsibility of the subclass to call <see cref="Eto.Widget.Initialize()"/>
/// </remarks>
void Initialize();
/// <summary>
/// Called to handle a specific event
/// </summary>
/// <remarks>
/// Most events are late bound by this method. Instead of wiring all events, this
/// will be called with an event string that is defined by the control.
///
/// This is called automatically when attaching to events, but must be called manually
/// when users of the control only override the event's On... method.
/// </remarks>
/// <param name="id">ID of the event to handle</param>
/// <param name = "defaultEvent">True if the event is default (e.g. overridden or via an event handler subscription)</param>
void HandleEvent(string id, bool defaultEvent = false);
}
/// <summary>
/// Registers the event for overridding
/// </summary>
/// <remarks>
/// This is used to register an event that will be automatically hooked up when a derived class overrides the
/// event method.
/// This should be called in the static constructor of your class.
/// </remarks>
/// <example>
/// Shows a custom control with an event:
/// <code>
/// public class MyEtoControl : Eto.Forms.Control
/// {
/// public const string MySomethingEvent = "MyEtoControl.MySomethingEvent";
///
/// public event EventHandler<EventArgs> MySomething
/// {
/// add { Properties.AddHandlerEvent(MySomethingEvent, value); }
/// remove { Properties.RemoveEvent(MySomethingEvent, value); }
/// }
///
/// protected virtual void OnMySomething(EventArgs e)
/// {
/// Properties.TriggerEvent(MySomethingEvent, this, e);
/// }
///
/// static MyEtoControl()
/// {
/// RegisterEvent<MyEtoControl>(c => c.OnMySomething(null), MySomethingEvent);
/// }
/// }
/// </code>
/// </example>
/// <param name="method">Expression to call the method that raises your event</param>
/// <param name="identifier">Identifier of the event</param>
/// <typeparam name="T">Your object type</typeparam>
protected static void RegisterEvent<T>(Expression<Action<T>> method, string identifier)
{
EventLookup.Register(method, identifier);
}
#if TRACK_GC
~Widget()
{
Dispose(false);
}
#endif
/// <summary>
/// Initializes a new instance of the Widget class
/// </summary>
protected Widget()
{
var platform = Platform.Instance;
if (platform == null)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Platform instance is null. Have you created your application?"));
var info = platform.FindHandler(GetType());
if (info == null)
throw new ArgumentOutOfRangeException(string.Format(CultureInfo.CurrentCulture, "Type for '{0}' could not be found in this platform", GetType().FullName));
Handler = info.Instantiator();
Platform = platform;
var widgetHandler = this.Handler as IHandler;
if (widgetHandler != null)
{
widgetHandler.Widget = this;
}
if (info.Initialize)
Initialize();
}
/// <summary>
/// Initializes a new instance of the Widget class
/// </summary>
/// <param name="handler">Handler to assign to this widget for its implementation</param>
protected Widget(IHandler handler)
{
Handler = handler;
Platform = Platform.Instance;
if (handler != null)
{
handler.Widget = this; // tell the handler who we are
}
Initialize();
}
/// <summary>
/// Initializes the widget handler
/// </summary>
/// <remarks>
/// This is typically called from the constructor after all of the logic is completed to construct
/// the object.
///
/// If your handler interface has the <see cref="AutoInitializeAttribute"/> set to false, then you are responsible
/// for calling this method in your constructor after calling the creation method on your custom handler.
/// </remarks>
protected void Initialize()
{
var handler = WidgetHandler;
if (handler != null)
handler.Initialize();
EventLookup.HookupEvents(this);
Platform.Instance.TriggerWidgetCreated(new WidgetCreatedEventArgs(this));
}
PropertyStore properties;
/// <summary>
/// Gets the dictionary of properties for this widget
/// </summary>
public PropertyStore Properties
{
get { return properties ?? (properties = new PropertyStore(this)); }
}
/// <summary>
/// Gets or sets the ID of this widget
/// </summary>
public string ID
{
get { return WidgetHandler.ID; }
set { WidgetHandler.ID = value; }
}
/// <summary>
/// Gets or sets the style of this widget
/// </summary>
/// <remarks>
/// Styles allow you to attach custom platform-specific logic to a widget.
/// In your platform-specific assembly, use <see cref="M:Style.Add{H}(string, StyleHandler{H})"/>
/// to add the style logic with the same id.
/// </remarks>
/// <example>
/// <code><![CDATA[
/// // in your UI
/// var control = new Button { Style = "mystyle" };
///
/// // in your platform assembly
/// using Eto.Mac.Forms.Controls;
///
/// Styles.AddHandler<ButtonHandler>("mystyle", handler => {
/// // this is where you can use handler.Control to set properties, handle events, etc.
/// handler.Control.BezelStyle = NSBezelStyle.SmallSquare;
/// });
/// ]]></code>
/// </example>
public string Style
{
get { return Properties.Get<string>(StyleKey); }
set
{
var style = Style;
if (style != value)
{
Properties[StyleKey] = value;
OnStyleChanged(EventArgs.Empty);
}
}
}
static readonly object StyleKey = new object();
#region Events
static readonly object StyleChangedKey = new object();
/// <summary>
/// Occurs when the <see cref="Widget.Style"/> property has changed
/// </summary>
public event EventHandler<EventArgs> StyleChanged
{
add { Properties.AddEvent(StyleChangedKey, value); }
remove { Properties.RemoveEvent(StyleChangedKey, value); }
}
/// <summary>
/// Handles when the <see cref="Style"/> is changed.
/// </summary>
protected virtual void OnStyleChanged(EventArgs e)
{
Eto.Style.OnStyleWidget(this);
Properties.TriggerEvent(StyleChangedKey, this, e);
}
#endregion
/// <summary>
/// Gets the instance of the platform-specific object
/// </summary>
/// <remarks>
/// This can sometimes be useful to get the platform-specific object.
/// Some handlers may not have any backing object for its functionality, so this may be null.
///
/// It is more preferred to use the <see cref="Widget.Handler"/> and cast that to the platform-specific
/// handler class which can give you additional methods and helpers to do common tasks.
///
/// For example, the <see cref="Forms.Application"/> object's handler for OS X has a AddFullScreenMenuItem
/// property to specify if you want full screen support in your app.
/// </remarks>
public object ControlObject
{
get
{
var controlObjectSource = Handler as IControlObjectSource;
return controlObjectSource != null ? controlObjectSource.ControlObject : null;
}
}
/// <summary>
/// Attaches the specified late-bound event to the control to be handled
/// </summary>
/// <remarks>
/// This needs to be called when you want to override the On... methods instead of attaching
/// to the associated event.
/// </remarks>
/// <example>
/// <code><![CDATA[
/// // this will call HandleEvent automatically
/// var textBox = new TextBox ();
/// textBox.TextChanged += MyTextChangedHandler;
///
/// // must call HandleEvent when overriding OnTextChanged
/// public class MyTextBox : TextBox
/// {
/// public MyTextBox()
/// {
/// HandleEvent (TextChangedEvent);
/// }
///
/// protected override void OnTextChanged (EventArgs e)
/// {
/// // your logic
/// }
/// }
///
/// ]]></code>
/// </example>
/// <param name="id">ID of the event to handle. Usually a constant in the form of [Control].[EventName]Event (e.g. TextBox.TextChangedEvent)</param>
internal void HandleEvent(string id)
{
WidgetHandler.HandleEvent(id);
}
/// <summary>
/// Disposes of this widget, supressing the finalizer
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Handles the disposal of this widget
/// </summary>
/// <param name="disposing">True if the caller called <see cref="Dispose()"/> manually, false if being called from a finalizer</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
var handler = Handler as IDisposable;
if (handler != null)
handler.Dispose();
Handler = null;
}
#if TRACK_GC
System.Diagnostics.Debug.WriteLine ("{0}: {1}", disposing ? "Dispose" : "GC", GetType().Name);
#endif
}
}
}
| |
namespace Nancy.ViewEngines.DotLiquid.Tests
{
using System.Collections.Generic;
using System.IO;
using FakeItEasy;
using global::DotLiquid;
using global::DotLiquid.Exceptions;
using Nancy.Tests;
using Xunit;
using Xunit.Extensions;
public class LiquidNancyFileSystemFixture
{
[Fact]
public void Should_locate_template_with_single_quoted_name()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "'views/partial'");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_locate_template_with_double_quoted_name()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, @"""views/partial""");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_locate_template_with_unquoted_name()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "views/partial");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_not_locate_templates_that_does_not_have_liquid_extension()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "cshtml", () => null));
// When
var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, "views/partial"));
// Then
exception.ShouldBeOfType<FileSystemException>();
}
[Theory]
[InlineData("partial")]
[InlineData("paRTial")]
[InlineData("PARTIAL")]
public void Should_ignore_casing_of_template_name(string templateName)
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat("views/", templateName));
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_locating_template_when_template_name_contains_liquid_extension()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "views/partial.liquid");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_locating_template_when_template_name_does_not_contains_liquid_extension()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "views/partial");
// Then
result.ShouldEqual("The correct view");
}
[Theory]
[InlineData("liquid")]
[InlineData("liqUID")]
[InlineData("LIQUID")]
public void Should_ignore_extension_casing_when_template_name_contains_liquid_extension(string extension)
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat("views/partial.", extension));
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_not_locate_view_when_template_location_not_specified()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => null));
// When
var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, "partial"));
// Then
exception.ShouldBeOfType<FileSystemException>();
}
[Theory]
[InlineData("views", "Located in views/")]
[InlineData("views/shared", "Located in views/shared")]
public void Should_locate_templates_with_correct_location_specified(string location, string expectedResult)
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult(location, "partial", "liquid", () => new StringReader(expectedResult)));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat(location, "/partial"));
// Then
result.ShouldEqual(expectedResult);
}
[Theory]
[InlineData("views")]
[InlineData("viEws")]
[InlineData("VIEWS")]
public void Should_ignore_case_of_location_when_locating_template(string location)
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult(location, "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat(location, "/partial"));
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_backslashes_as_location_seperator()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult(@"views/shared", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, @"views\shared\partial");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_forward_slashes_as_location_seperator()
{
// Given
Context context;
var fileSystem = CreateFileSystem(out context,
new ViewLocationResult(@"views/shared", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, @"views/shared/partial");
// Then
result.ShouldEqual("The correct view");
}
private LiquidNancyFileSystem CreateFileSystem(out Context context, params ViewLocationResult[] viewLocationResults)
{
var viewLocationProvider = A.Fake<IViewLocationProvider>();
A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))
.Returns(viewLocationResults);
var viewEngine = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine.Extensions).Returns(new[] { "liquid" });
var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine });
var startupContext = new ViewEngineStartupContext(
null,
viewLocator);
var renderContext = A.Fake<IRenderContext>();
A.CallTo(() => renderContext.LocateView(A<string>.Ignored, A<object>.Ignored))
.ReturnsLazily(x => viewLocator.LocateView(x.Arguments.Get<string>(0), null));
context = new Context(new List<Hash>(), new Hash(),
Hash.FromAnonymousObject(new { nancy = renderContext }), false);
return new LiquidNancyFileSystem(startupContext, new[] { "liquid" });
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Linq;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish;
using Microsoft.WindowsAzure.Commands.Common.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
using System.Management.Automation;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions.DSC
{
/// <summary>
/// Uploads a Desired State Configuration script to Azure blob storage, which
/// later can be applied to Azure Virtual Machines using the
/// Set-AzureVMDscExtension cmdlet.
/// </summary>
[Cmdlet(
VerbsData.Publish,
"AzureVMDscConfiguration",
SupportsShouldProcess = true,
DefaultParameterSetName = UploadArchiveParameterSetName),
OutputType(
typeof(String))]
public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase
{
private const string CreateArchiveParameterSetName = "CreateArchive";
private const string UploadArchiveParameterSetName = "UploadArchive";
/// <summary>
/// Path to a file containing one or more configurations; the file can be a
/// PowerShell script (*.ps1) or MOF interface (*.mof).
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file containing one or more configurations")]
[ValidateNotNullOrEmpty]
public string ConfigurationPath { get; set; }
/// <summary>
/// Name of the Azure Storage Container the configuration is uploaded to.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")]
[ValidateNotNullOrEmpty]
public string ContainerName { get; set; }
/// <summary>
/// By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs.
/// Use -Force to overwrite them.
/// </summary>
[Parameter(HelpMessage = "By default Publish-AzureVMDscConfiguration will not overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
/// <summary>
/// The Azure Storage Context that provides the security settings used to upload
/// the configuration script to the container specified by ContainerName. This
/// context should provide write access to the container.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "The Azure Storage Context that provides the security settings used to upload " +
"the configuration script to the container specified by ContainerName")]
[ValidateNotNullOrEmpty]
public AzureStorageContext StorageContext { get; set; }
/// <summary>
/// Path to a local ZIP file to write the configuration archive to.
/// When using this parameter, Publish-AzureVMDscConfiguration creates a
/// local ZIP archive instead of uploading it to blob storage..
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = CreateArchiveParameterSetName,
HelpMessage = "Path to a local ZIP file to write the configuration archive to.")]
[ValidateNotNullOrEmpty]
public string ConfigurationArchivePath { get; set; }
/// <summary>
/// Suffix for the storage end point, e.g. core.windows.net
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")]
[ValidateNotNullOrEmpty]
public string StorageEndpointSuffix { get; set; }
/// <summary>
/// Excludes DSC resource dependencies from the configuration archive
/// </summary>
[Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")]
public SwitchParameter SkipDependencyDetection { get; set; }
/// <summary>
///Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")]
[ValidateNotNullOrEmpty]
public string ConfigurationDataPath { get; set; }
/// <summary>
/// Path to a file or a directory to include in the configuration archive
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file or a directory to include in the configuration archive")]
[ValidateNotNullOrEmpty]
public String[] AdditionalPath { get; set; }
/// <summary>
/// Outputs the blob url for configuration archive path
/// </summary>
[Parameter(HelpMessage = "Outputs the blob url for configuration archive path")]
public SwitchParameter PassThru { get; set; }
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
protected override void ProcessRecord()
{
try
{
// Create a cloud context, only in case of upload.
if (ParameterSetName == UploadArchiveParameterSetName)
{
base.ProcessRecord();
}
ExecuteCommand();
}
finally
{
DeleteTemporaryFiles();
}
}
private void ExecuteCommand()
{
//check the PS version
ValidatePsVersion();
//validate cmdlet params
ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath);
ValidateConfigurationPath(ConfigurationPath, ParameterSetName);
if (ConfigurationDataPath != null)
{
ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath);
ValidateConfigurationDataPath(ConfigurationDataPath);
}
if(AdditionalPath != null && AdditionalPath.Length > 0)
{
for(var count = 0; count < AdditionalPath.Length; count++)
{
AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]);
}
}
switch (ParameterSetName)
{
case CreateArchiveParameterSetName:
ConfigurationArchivePath = GetUnresolvedProviderPathFromPSPath(ConfigurationArchivePath);
break;
case UploadArchiveParameterSetName:
_storageCredentials = this.GetStorageCredentials(StorageContext);
if (ContainerName == null)
{
ContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (StorageEndpointSuffix == null)
{
StorageEndpointSuffix =
Profile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
break;
}
PublishConfiguration(
ConfigurationPath,
ConfigurationDataPath,
AdditionalPath,
ConfigurationArchivePath,
StorageEndpointSuffix,
ContainerName,
ParameterSetName,
Force.IsPresent,
SkipDependencyDetection.IsPresent,
_storageCredentials,
PassThru.IsPresent
);
}
}
}
| |
using System;
using System.IO;
namespace DjvuNet.Compression
{
public class ZPCodec
{
#region Private Variables
private int _buffer;
private long _code;
private short _delay;
private long _fence;
private Stream _ibs;
private short _scount;
private short _zByte;
private const int _arraySize = 256;
#endregion Private Variables
#region Protected Properties
#region FFZT
private static readonly sbyte[] _FFZT = new sbyte[_arraySize];
/// <summary>
/// Gets the FFZT data
/// </summary>
protected static sbyte[] FFZT
{
get { return _FFZT; }
}
#endregion FFZT
#region AValue
private int _AValue;
/// <summary>
/// Gets or sets the A Value for the item
/// </summary>
protected int AValue
{
get { return _AValue; }
set
{
_AValue = value;
}
}
#endregion AValue
#region Down
private MutableValue<sbyte>[] _down = new MutableValue<sbyte>[_arraySize];
/// <summary>
/// Gets or sets the down values for the item
/// </summary>
public MutableValue<sbyte>[] Down
{
get { return _down; }
set
{
if (Down != value)
{
_down = value;
}
}
}
#endregion Down
#region Up
private MutableValue<sbyte>[] _up = new MutableValue<sbyte>[_arraySize];
/// <summary>
/// Gets or sets the up values for the item
/// </summary>
public MutableValue<sbyte>[] Up
{
get { return _up; }
set
{
if (Up != value)
{
_up = value;
}
}
}
#endregion Up
#region Ffzt
private sbyte[] _ffzt = new sbyte[_arraySize];
/// <summary>
/// Gets the Ffzt data
/// </summary>
protected sbyte[] Ffzt
{
get { return _ffzt; }
private set
{
if (Ffzt != value)
{
_ffzt = value;
}
}
}
#endregion Ffzt
#region MArray
private int[] _mArray = new int[_arraySize];
/// <summary>
/// Gets or sets the M Array values for the item
/// </summary>
public int[] MArray
{
get { return _mArray; }
set
{
if (MArray != value)
{
_mArray = value;
}
}
}
#endregion MArray
#region PArray
private int[] _pArray = new int[_arraySize];
/// <summary>
/// Gets or sets the P Array values for the item
/// </summary>
public int[] PArray
{
get { return _pArray; }
set
{
_pArray = value;
}
}
#endregion PArray
#endregion Protected Properties
#region Public Properties
#region DefaultZPTable
private ZPTable[] _defaultZPTable;
/// <summary>
/// Gets the default ZP table
/// </summary>
public ZPTable[] DefaultZPTable
{
get
{
if (_defaultZPTable == null)
{
_defaultZPTable = BuildDefaultZPTable();
}
return _defaultZPTable;
}
}
#endregion DefaultZPTable
#endregion Public Properties
#region Constructors
static ZPCodec()
{
for (int i = 0; i < _arraySize; i++)
{
FFZT[i] = 0;
for (int j = i; (j & 0x80) > 0; j <<= 1)
{
FFZT[i]++;
}
}
}
public ZPCodec()
{
Ffzt = new sbyte[FFZT.Length];
Array.Copy(FFZT, 0, Ffzt, 0, Ffzt.Length);
for (int i = 0; i < _arraySize; i++)
{
Up[i] = new MutableValue<sbyte>();
Down[i] = new MutableValue<sbyte>();
}
}
public ZPCodec(Stream ibs)
: this()
{
Init(ibs);
}
#endregion Constructors
#region Public Methods
public int IWDecoder()
{
return DecodeSubSimple(0, 0x8000 + ((AValue + AValue + AValue) >> 3));
}
public int DecodeSub(MutableValue<sbyte> ctx, int z)
{
int bit = ctx.Value & 1;
int d = 24576 + ((z + AValue) >> 2);
if (z > d)
{
z = d;
}
if (z > _code)
{
z = 0x10000 - z;
AValue += z;
_code += z;
ctx.Value = Down[0xff & ctx.Value].Value;
int shift = FFZ(AValue);
_scount = (short)(_scount - shift);
AValue = 0xffff & (AValue << shift);
_code = 0xffff & ((_code << shift) | ((_buffer >> _scount) & ((1 << shift) - 1)));
if (_scount < 16)
{
Preload();
}
_fence = _code;
if (_code >= 32768L)
{
_fence = 32767L;
}
return bit ^ 1;
}
if ((unchecked((int)0xffffffffL) & AValue) >= (unchecked((int)0xffffffffL) & MArray[0xff & ctx.Value]))
{
ctx.Value = Up[0xff & ctx.Value].Value;
}
_scount--;
AValue = 0xffff & (z << 1);
_code = 0xffff & ((_code << 1) | ((_buffer >> _scount) & 1));
if (_scount < 16)
{
Preload();
}
_fence = _code;
if (_code >= 32768L)
{
_fence = 32767L;
}
return bit;
}
public int DecodeSubNolearn(int mps, int z)
{
int d = 24576 + ((z + AValue) >> 2);
if (z > d)
{
z = d;
}
if (z > _code)
{
z = 0x10000 - z;
AValue += z;
_code += z;
int shift = FFZ(AValue);
_scount = (short)(_scount - shift);
AValue = 0xffff & (AValue << shift);
_code = 0xffff & ((_code << shift) | ((_buffer >> _scount) & ((1 << shift) - 1)));
if (_scount < 16)
{
Preload();
}
_fence = _code;
if (_code >= 32768L)
{
_fence = 32767L;
}
return mps ^ 1;
}
_scount--;
AValue = 0xffff & (z << 1);
_code = 0xffff & ((_code << 1) | ((_buffer >> _scount) & 1));
if (_scount < 16)
{
Preload();
}
_fence = _code;
if (_code >= 32768L)
{
_fence = 32767L;
}
return mps;
}
public int DecodeSubSimple(int mps, int z)
{
if (z > _code)
{
z = 0x10000 - z;
AValue += z;
_code += z;
int shift = FFZ(AValue);
_scount = (short)(_scount - shift);
AValue = 0xffff & (AValue << shift);
_code = 0xffff & ((_code << shift) | ((_buffer >> _scount) & ((1 << shift) - 1)));
if (_scount < 16)
{
Preload();
}
_fence = _code;
if (_code >= 32768L)
{
_fence = 32767L;
}
return mps ^ 1;
}
_scount--;
AValue = 0xffff & (z << 1);
_code = 0xffff & ((_code << 1) | ((_buffer >> _scount) & 1));
if (_scount < 16)
{
Preload();
}
_fence = _code;
if (_code >= 32768L)
{
_fence = 32767L;
}
return mps;
}
public int Decoder()
{
return DecodeSubSimple(0, 0x8000 + (AValue >> 1));
}
public int Decoder(MutableValue<sbyte> ctx)
{
int ictx = 0xff & ctx.Value;
int z = AValue + PArray[ictx];
if (z <= _fence)
{
AValue = z;
return ictx & 1;
}
else
{
return DecodeSub(ctx, z);
}
}
public int FFZ(int x)
{
return ((unchecked((int)0xffffffffL) & x) < 65280L) ? Ffzt[0xff & (x >> 8)] : (Ffzt[0xff & x] + 8);
}
public ZPCodec Init(Stream ibs)
{
_ibs = ibs;
dinit();
return this;
}
public void NewZPTable(ZPTable[] table)
{
for (int i = 0; i < _arraySize; i++)
{
PArray[i] = table[i].PValue;
MArray[i] = table[i].MValue;
Up[i].Value = (sbyte)table[i].Up;
Down[i].Value = (sbyte)table[i].Down;
}
}
public void Preload()
{
for (; _scount <= 24; _scount = (short)(_scount + 8))
{
_zByte = -1;
_zByte = (short)_ibs.ReadByte();
if (_zByte == -1)
{
_zByte = 255;
if (--_delay < 1)
{
throw new IOException("EOF");
}
}
_buffer = (_buffer << 8) | _zByte;
}
}
#endregion Public Methods
#region Private Methods
private void dinit()
{
AValue = 0;
NewZPTable(DefaultZPTable);
_code = 0xff00;
try
{
_code &= (_ibs.ReadByte() << 8);
_zByte = (short)(0xff & _ibs.ReadByte());
}
catch (IOException exp)
{
_zByte = 255;
}
_code |= _zByte;
_delay = 25;
_scount = 0;
Preload();
_fence = _code;
if (_code >= 32768L)
{
_fence = 32767L;
}
}
/// <summary>
/// Builds the default version of the ZP Table
/// </summary>
/// <returns></returns>
private ZPTable[] BuildDefaultZPTable()
{
return new[]
{
new ZPTable(32768, 0, 84, 145),
new ZPTable(32768, 0, 3, 4),
new ZPTable(32768, 0, 4, 3),
new ZPTable(27581, 4261, 5, 1),
new ZPTable(27581, 4261, 6, 2),
new ZPTable(23877, 7976, 7, 3),
new ZPTable(23877, 7976, 8, 4),
new ZPTable(20921, 11219, 9, 5),
new ZPTable(20921, 11219, 10, 6),
new ZPTable(18451, 14051, 11, 7),
new ZPTable(18451, 14051, 12, 8),
new ZPTable(16341, 16524, 13, 9),
new ZPTable(16341, 16524, 14, 10),
new ZPTable(14513, 18685, 15, 11),
new ZPTable(14513, 18685, 16, 12),
new ZPTable(12917, 20573, 17, 13),
new ZPTable(12917, 20573, 18, 14),
new ZPTable(11517, 22224, 19, 15),
new ZPTable(11517, 22224, 20, 16),
new ZPTable(10277, 23665, 21, 17),
new ZPTable(10277, 23665, 22, 18),
new ZPTable(9131, 24923, 23, 19),
new ZPTable(9131, 24923, 24, 20),
new ZPTable(8071, 26021, 25, 21),
new ZPTable(8071, 26021, 26, 22),
new ZPTable(7099, 26978, 27, 23),
new ZPTable(7099, 26978, 28, 24),
new ZPTable(6213, 27810, 29, 25),
new ZPTable(6213, 27810, 30, 26),
new ZPTable(5411, 28532, 31, 27),
new ZPTable(5411, 28532, 32, 28),
new ZPTable(4691, 29158, 33, 29),
new ZPTable(4691, 29158, 34, 30),
new ZPTable(4047, 29700, 35, 31),
new ZPTable(4047, 29700, 36, 32),
new ZPTable(3477, 30166, 37, 33),
new ZPTable(3477, 30166, 38, 34),
new ZPTable(2973, 30568, 39, 35),
new ZPTable(2973, 30568, 40, 36),
new ZPTable(2531, 30914, 41, 37),
new ZPTable(2531, 30914, 42, 38),
new ZPTable(2145, 31210, 43, 39),
new ZPTable(2145, 31210, 44, 40),
new ZPTable(1809, 31463, 45, 41),
new ZPTable(1809, 31463, 46, 42),
new ZPTable(1521, 31678, 47, 43),
new ZPTable(1521, 31678, 48, 44),
new ZPTable(1273, 31861, 49, 45),
new ZPTable(1273, 31861, 50, 46),
new ZPTable(1061, 32015, 51, 47),
new ZPTable(1061, 32015, 52, 48),
new ZPTable(881, 32145, 53, 49),
new ZPTable(881, 32145, 54, 50),
new ZPTable(729, 32254, 55, 51),
new ZPTable(729, 32254, 56, 52),
new ZPTable(601, 32346, 57, 53),
new ZPTable(601, 32346, 58, 54),
new ZPTable(493, 32422, 59, 55),
new ZPTable(493, 32422, 60, 56),
new ZPTable(403, 32486, 61, 57),
new ZPTable(403, 32486, 62, 58),
new ZPTable(329, 32538, 63, 59),
new ZPTable(329, 32538, 64, 60),
new ZPTable(267, 32581, 65, 61),
new ZPTable(267, 32581, 66, 62),
new ZPTable(213, 32619, 67, 63),
new ZPTable(213, 32619, 68, 64),
new ZPTable(165, 32653, 69, 65),
new ZPTable(165, 32653, 70, 66),
new ZPTable(123, 32682, 71, 67),
new ZPTable(123, 32682, 72, 68),
new ZPTable(87, 32707, 73, 69),
new ZPTable(87, 32707, 74, 70),
new ZPTable(59, 32727, 75, 71),
new ZPTable(59, 32727, 76, 72),
new ZPTable(35, 32743, 77, 73),
new ZPTable(35, 32743, 78, 74),
new ZPTable(19, 32754, 79, 75),
new ZPTable(19, 32754, 80, 76),
new ZPTable(7, 32762, 81, 77),
new ZPTable(7, 32762, 82, 78),
new ZPTable(1, 32767, 81, 79),
new ZPTable(1, 32767, 82, 80),
new ZPTable(22165, 0, 9, 85),
new ZPTable(9454, 0, 86, 226),
new ZPTable(32768, 0, 5, 6),
new ZPTable(3376, 0, 88, 176),
new ZPTable(18458, 0, 89, 143),
new ZPTable(1153, 0, 90, 138),
new ZPTable(13689, 0, 91, 141),
new ZPTable(378, 0, 92, 112),
new ZPTable(9455, 0, 93, 135),
new ZPTable(123, 0, 94, 104),
new ZPTable(6520, 0, 95, 133),
new ZPTable(40, 0, 96, 100),
new ZPTable(4298, 0, 97, 129),
new ZPTable(13, 0, 82, 98),
new ZPTable(2909, 0, 99, 127),
new ZPTable(52, 0, 76, 72),
new ZPTable(1930, 0, 101, 125),
new ZPTable(160, 0, 70, 102),
new ZPTable(1295, 0, 103, 123),
new ZPTable(279, 0, 66, 60),
new ZPTable(856, 0, 105, 121),
new ZPTable(490, 0, 106, 110),
new ZPTable(564, 0, 107, 119),
new ZPTable(324, 0, 66, 108),
new ZPTable(371, 0, 109, 117),
new ZPTable(564, 0, 60, 54),
new ZPTable(245, 0, 111, 115),
new ZPTable(851, 0, 56, 48),
new ZPTable(161, 0, 69, 113),
new ZPTable(1477, 0, 114, 134),
new ZPTable(282, 0, 65, 59),
new ZPTable(975, 0, 116, 132),
new ZPTable(426, 0, 61, 55),
new ZPTable(645, 0, 118, 130),
new ZPTable(646, 0, 57, 51),
new ZPTable(427, 0, 120, 128),
new ZPTable(979, 0, 53, 47),
new ZPTable(282, 0, 122, 126),
new ZPTable(1477, 0, 49, 41),
new ZPTable(186, 0, 124, 62),
new ZPTable(2221, 0, 43, 37),
new ZPTable(122, 0, 72, 66),
new ZPTable(3276, 0, 39, 31),
new ZPTable(491, 0, 60, 54),
new ZPTable(4866, 0, 33, 25),
new ZPTable(742, 0, 56, 50),
new ZPTable(7041, 0, 29, 131),
new ZPTable(1118, 0, 52, 46),
new ZPTable(9455, 0, 23, 17),
new ZPTable(1680, 0, 48, 40),
new ZPTable(10341, 0, 23, 15),
new ZPTable(2526, 0, 42, 136),
new ZPTable(14727, 0, 137, 7),
new ZPTable(3528, 0, 38, 32),
new ZPTable(11417, 0, 21, 139),
new ZPTable(4298, 0, 140, 172),
new ZPTable(15199, 0, 15, 9),
new ZPTable(2909, 0, 142, 170),
new ZPTable(22165, 0, 9, 85),
new ZPTable(1930, 0, 144, 168),
new ZPTable(32768, 0, 141, 248),
new ZPTable(1295, 0, 146, 166),
new ZPTable(9454, 0, 147, 247),
new ZPTable(856, 0, 148, 164),
new ZPTable(3376, 0, 149, 197),
new ZPTable(564, 0, 150, 162),
new ZPTable(1153, 0, 151, 95),
new ZPTable(371, 0, 152, 160),
new ZPTable(378, 0, 153, 173),
new ZPTable(245, 0, 154, 158),
new ZPTable(123, 0, 155, 165),
new ZPTable(161, 0, 70, 156),
new ZPTable(40, 0, 157, 161),
new ZPTable(282, 0, 66, 60),
new ZPTable(13, 0, 81, 159),
new ZPTable(426, 0, 62, 56),
new ZPTable(52, 0, 75, 71),
new ZPTable(646, 0, 58, 52),
new ZPTable(160, 0, 69, 163),
new ZPTable(979, 0, 54, 48),
new ZPTable(279, 0, 65, 59),
new ZPTable(1477, 0, 50, 42),
new ZPTable(490, 0, 167, 171),
new ZPTable(2221, 0, 44, 38),
new ZPTable(324, 0, 65, 169),
new ZPTable(3276, 0, 40, 32),
new ZPTable(564, 0, 59, 53),
new ZPTable(4866, 0, 34, 26),
new ZPTable(851, 0, 55, 47),
new ZPTable(7041, 0, 30, 174),
new ZPTable(1477, 0, 175, 193),
new ZPTable(9455, 0, 24, 18),
new ZPTable(975, 0, 177, 191),
new ZPTable(11124, 0, 178, 222),
new ZPTable(645, 0, 179, 189),
new ZPTable(8221, 0, 180, 218),
new ZPTable(427, 0, 181, 187),
new ZPTable(5909, 0, 182, 216),
new ZPTable(282, 0, 183, 185),
new ZPTable(4023, 0, 184, 214),
new ZPTable(186, 0, 69, 61),
new ZPTable(2663, 0, 186, 212),
new ZPTable(491, 0, 59, 53),
new ZPTable(1767, 0, 188, 210),
new ZPTable(742, 0, 55, 49),
new ZPTable(1174, 0, 190, 208),
new ZPTable(1118, 0, 51, 45),
new ZPTable(781, 0, 192, 206),
new ZPTable(1680, 0, 47, 39),
new ZPTable(518, 0, 194, 204),
new ZPTable(2526, 0, 41, 195),
new ZPTable(341, 0, 196, 202),
new ZPTable(3528, 0, 37, 31),
new ZPTable(225, 0, 198, 200),
new ZPTable(11124, 0, 199, 243),
new ZPTable(148, 0, 72, 64),
new ZPTable(8221, 0, 201, 239),
new ZPTable(392, 0, 62, 56),
new ZPTable(5909, 0, 203, 237),
new ZPTable(594, 0, 58, 52),
new ZPTable(4023, 0, 205, 235),
new ZPTable(899, 0, 54, 48),
new ZPTable(2663, 0, 207, 233),
new ZPTable(1351, 0, 50, 44),
new ZPTable(1767, 0, 209, 231),
new ZPTable(2018, 0, 46, 38),
new ZPTable(1174, 0, 211, 229),
new ZPTable(3008, 0, 40, 34),
new ZPTable(781, 0, 213, 227),
new ZPTable(4472, 0, 36, 28),
new ZPTable(518, 0, 215, 225),
new ZPTable(6618, 0, 30, 22),
new ZPTable(341, 0, 217, 223),
new ZPTable(9455, 0, 26, 16),
new ZPTable(225, 0, 219, 221),
new ZPTable(12814, 0, 20, 220),
new ZPTable(148, 0, 71, 63),
new ZPTable(17194, 0, 14, 8),
new ZPTable(392, 0, 61, 55),
new ZPTable(17533, 0, 14, 224),
new ZPTable(594, 0, 57, 51),
new ZPTable(24270, 0, 8, 2),
new ZPTable(899, 0, 53, 47),
new ZPTable(32768, 0, 228, 87),
new ZPTable(1351, 0, 49, 43),
new ZPTable(18458, 0, 230, 246),
new ZPTable(2018, 0, 45, 37),
new ZPTable(13689, 0, 232, 244),
new ZPTable(3008, 0, 39, 33),
new ZPTable(9455, 0, 234, 238),
new ZPTable(4472, 0, 35, 27),
new ZPTable(6520, 0, 138, 236),
new ZPTable(6618, 0, 29, 21),
new ZPTable(10341, 0, 24, 16),
new ZPTable(9455, 0, 25, 15),
new ZPTable(14727, 0, 240, 8),
new ZPTable(12814, 0, 19, 241),
new ZPTable(11417, 0, 22, 242),
new ZPTable(17194, 0, 13, 7),
new ZPTable(15199, 0, 16, 10),
new ZPTable(17533, 0, 13, 245),
new ZPTable(22165, 0, 10, 2),
new ZPTable(24270, 0, 7, 1),
new ZPTable(32768, 0, 244, 83),
new ZPTable(32768, 0, 249, 250),
new ZPTable(22165, 0, 10, 2),
new ZPTable(18458, 0, 89, 143),
new ZPTable(18458, 0, 230, 246),
new ZPTable(0, 0, 0, 0),
new ZPTable(0, 0, 0, 0),
new ZPTable(0, 0, 0, 0),
new ZPTable(0, 0, 0, 0),
new ZPTable(0, 0, 0, 0)
};
}
#endregion Private Methods
}
}
| |
//
// SignatureReader.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 - 2007 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Signatures {
using System;
using System.Collections;
using System.IO;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Metadata;
internal sealed class SignatureReader : BaseSignatureVisitor {
MetadataRoot m_root;
ReflectionReader m_reflectReader;
byte [] m_blobData;
IDictionary m_signatures;
IAssemblyResolver AssemblyResolver {
get { return m_reflectReader.Module.Assembly.Resolver; }
}
public SignatureReader (MetadataRoot root, ReflectionReader reflectReader)
{
m_root = root;
m_reflectReader = reflectReader;
m_blobData = m_root.Streams.BlobHeap != null ? m_root.Streams.BlobHeap.Data : new byte [0];
m_signatures = new Hashtable ();
}
public FieldSig GetFieldSig (uint index)
{
FieldSig f = m_signatures [index] as FieldSig;
if (f == null) {
f = new FieldSig (index);
f.Accept (this);
m_signatures [index] = f;
}
return f;
}
public PropertySig GetPropSig (uint index)
{
PropertySig p = m_signatures [index] as PropertySig;
if (p == null) {
p = new PropertySig (index);
p.Accept (this);
m_signatures [index] = p;
}
return p;
}
public MethodDefSig GetMethodDefSig (uint index)
{
MethodDefSig m = m_signatures [index] as MethodDefSig;
if (m == null) {
m = new MethodDefSig (index);
m.Accept (this);
m_signatures [index] = m;
}
return m;
}
public MethodRefSig GetMethodRefSig (uint index)
{
MethodRefSig m = m_signatures [index] as MethodRefSig;
if (m == null) {
m = new MethodRefSig (index);
m.Accept (this);
m_signatures [index] = m;
}
return m;
}
public TypeSpec GetTypeSpec (uint index)
{
TypeSpec ts = m_signatures [index] as TypeSpec;
if (ts == null) {
ts = ReadTypeSpec (m_blobData, (int) index);
m_signatures [index] = ts;
}
return ts;
}
public MethodSpec GetMethodSpec (uint index)
{
MethodSpec ms = m_signatures [index] as MethodSpec;
if (ms == null) {
ms = ReadMethodSpec (m_blobData, (int) index);
m_signatures [index] = ms;
}
return ms;
}
public LocalVarSig GetLocalVarSig (uint index)
{
LocalVarSig lv = m_signatures [index] as LocalVarSig;
if (lv == null) {
lv = new LocalVarSig (index);
lv.Accept (this);
m_signatures [index] = lv;
}
return lv;
}
public CustomAttrib GetCustomAttrib (uint index, MethodReference ctor)
{
return GetCustomAttrib (index, ctor, false);
}
public CustomAttrib GetCustomAttrib (uint index, MethodReference ctor, bool resolve)
{
return ReadCustomAttrib ((int) index, ctor, resolve);
}
public CustomAttrib GetCustomAttrib (byte [] data, MethodReference ctor)
{
return GetCustomAttrib (data, ctor, false);
}
public CustomAttrib GetCustomAttrib (byte [] data, MethodReference ctor, bool resolve)
{
BinaryReader br = new BinaryReader (new MemoryStream (data));
return ReadCustomAttrib (br, data, ctor, resolve);
}
public Signature GetMemberRefSig (TokenType tt, uint index)
{
int start, callconv;
Utilities.ReadCompressedInteger (m_blobData, (int) index, out start);
callconv = m_blobData [start];
if ((callconv & 0x5) == 0x5 || (callconv & 0x10) == 0x10) // vararg || generic?
return GetMethodDefSig (index);
if ((callconv & 0x6) != 0) // field ?
return GetFieldSig (index);
switch (tt) {
case TokenType.TypeDef :
case TokenType.TypeRef :
case TokenType.TypeSpec :
return GetMethodRefSig (index);
case TokenType.ModuleRef :
case TokenType.Method :
return GetMethodDefSig (index);
}
return null;
}
public MarshalSig GetMarshalSig (uint index)
{
MarshalSig ms = m_signatures [index] as MarshalSig;
if (ms == null) {
byte [] data = m_root.Streams.BlobHeap.Read (index);
ms = ReadMarshalSig (data);
m_signatures [index] = ms;
}
return ms;
}
public MethodSig GetStandAloneMethodSig (uint index)
{
byte [] data = m_root.Streams.BlobHeap.Read (index);
int start;
if ((data [0] & 0x5) > 0) {
MethodRefSig mrs = new MethodRefSig (index);
ReadMethodRefSig (mrs, data, 0, out start);
return mrs;
} else {
MethodDefSig mds = new MethodDefSig (index);
ReadMethodDefSig (mds, data, 0, out start);
return mds;
}
}
public override void VisitMethodDefSig (MethodDefSig methodDef)
{
int start;
ReadMethodDefSig (methodDef, m_root.Streams.BlobHeap.Read (methodDef.BlobIndex), 0, out start);
}
public override void VisitMethodRefSig (MethodRefSig methodRef)
{
int start;
ReadMethodRefSig (methodRef, m_root.Streams.BlobHeap.Read (methodRef.BlobIndex), 0, out start);
}
public override void VisitFieldSig (FieldSig field)
{
int start;
Utilities.ReadCompressedInteger (m_blobData, (int) field.BlobIndex, out start);
field.CallingConvention = m_blobData [start];
field.Field = (field.CallingConvention & 0x6) != 0;
field.CustomMods = ReadCustomMods (m_blobData, start + 1, out start);
field.Type = ReadType (m_blobData, start, out start);
}
public override void VisitPropertySig (PropertySig property)
{
int start;
Utilities.ReadCompressedInteger (m_blobData, (int) property.BlobIndex, out start);
property.CallingConvention = m_blobData [start];
property.Property = (property.CallingConvention & 0x8) != 0;
property.ParamCount = Utilities.ReadCompressedInteger (m_blobData, start + 1, out start);
property.CustomMods = ReadCustomMods (m_blobData, start, out start);
property.Type = ReadType (m_blobData, start, out start);
property.Parameters = ReadParameters (property.ParamCount, m_blobData, start, out start);
}
public override void VisitLocalVarSig (LocalVarSig localvar)
{
int start;
Utilities.ReadCompressedInteger (m_blobData, (int) localvar.BlobIndex, out start);
localvar.CallingConvention = m_blobData [start];
localvar.Local = (localvar.CallingConvention & 0x7) != 0;
localvar.Count = Utilities.ReadCompressedInteger (m_blobData, start + 1, out start);
localvar.LocalVariables = ReadLocalVariables (localvar.Count, m_blobData, start);
}
void ReadMethodDefSig (MethodDefSig methodDef, byte [] data, int pos, out int start)
{
methodDef.CallingConvention = data [pos];
start = pos + 1;
methodDef.HasThis = (methodDef.CallingConvention & 0x20) != 0;
methodDef.ExplicitThis = (methodDef.CallingConvention & 0x40) != 0;
if ((methodDef.CallingConvention & 0x5) != 0)
methodDef.MethCallConv |= MethodCallingConvention.VarArg;
else if ((methodDef.CallingConvention & 0x10) != 0) {
methodDef.MethCallConv |= MethodCallingConvention.Generic;
methodDef.GenericParameterCount = Utilities.ReadCompressedInteger (data, start, out start);
} else
methodDef.MethCallConv |= MethodCallingConvention.Default;
methodDef.ParamCount = Utilities.ReadCompressedInteger (data, start, out start);
methodDef.RetType = ReadRetType (data, start, out start);
int sentpos;
methodDef.Parameters = ReadParameters (methodDef.ParamCount, data, start, out start, out sentpos);
methodDef.Sentinel = sentpos;
}
void ReadMethodRefSig (MethodRefSig methodRef, byte [] data, int pos, out int start)
{
methodRef.CallingConvention = data [pos];
start = pos + 1;
methodRef.HasThis = (methodRef.CallingConvention & 0x20) != 0;
methodRef.ExplicitThis = (methodRef.CallingConvention & 0x40) != 0;
if ((methodRef.CallingConvention & 0x1) != 0)
methodRef.MethCallConv |= MethodCallingConvention.C;
else if ((methodRef.CallingConvention & 0x2) != 0)
methodRef.MethCallConv |= MethodCallingConvention.StdCall;
else if ((methodRef.CallingConvention & 0x3) != 0)
methodRef.MethCallConv |= MethodCallingConvention.ThisCall;
else if ((methodRef.CallingConvention & 0x4) != 0)
methodRef.MethCallConv |= MethodCallingConvention.FastCall;
else if ((methodRef.CallingConvention & 0x5) != 0)
methodRef.MethCallConv |= MethodCallingConvention.VarArg;
else
methodRef.MethCallConv |= MethodCallingConvention.Default;
methodRef.ParamCount = Utilities.ReadCompressedInteger (data, start, out start);
methodRef.RetType = ReadRetType (data, start, out start);
int sentpos;
methodRef.Parameters = ReadParameters (methodRef.ParamCount, data, start, out start, out sentpos);
methodRef.Sentinel = sentpos;
}
LocalVarSig.LocalVariable [] ReadLocalVariables (int length, byte [] data, int pos)
{
int start = pos;
LocalVarSig.LocalVariable [] types = new LocalVarSig.LocalVariable [length];
for (int i = 0; i < length; i++)
types [i] = ReadLocalVariable (data, start, out start);
return types;
}
LocalVarSig.LocalVariable ReadLocalVariable (byte [] data, int pos, out int start)
{
start = pos;
LocalVarSig.LocalVariable lv = new LocalVarSig.LocalVariable ();
lv.ByRef = false;
int cursor;
while (true) {
lv.CustomMods = ReadCustomMods (data, start, out start);
cursor = start;
int current = Utilities.ReadCompressedInteger (data, start, out start);
if (current == (int) ElementType.Pinned) // the only possible constraint
lv.Constraint |= Constraint.Pinned;
else if (current == (int) ElementType.ByRef) {
lv.ByRef = true;
if (lv.CustomMods == null || lv.CustomMods.Length == 0)
lv.CustomMods = ReadCustomMods (data, start, out start);
} else {
lv.Type = ReadType (data, cursor, out start);
break;
}
}
return lv;
}
TypeSpec ReadTypeSpec (byte [] data, int pos)
{
int start = pos;
Utilities.ReadCompressedInteger (data, start, out start);
TypeSpec ts = new TypeSpec ();
ts.CustomMods = ReadCustomMods (data, start, out start);
ts.Type = ReadType (data, start, out start);
return ts;
}
MethodSpec ReadMethodSpec (byte [] data, int pos)
{
int start = pos;
Utilities.ReadCompressedInteger (data, start, out start);
if (Utilities.ReadCompressedInteger (data, start, out start) != 0x0a)
throw new ReflectionException ("Invalid MethodSpec signature");
return new MethodSpec (ReadGenericInstSignature (data, start, out start));
}
RetType ReadRetType (byte [] data, int pos, out int start)
{
RetType rt = new RetType ();
start = pos;
rt.CustomMods = ReadCustomMods (data, start, out start);
int curs = start;
ElementType flag = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
switch (flag) {
case ElementType.Void :
rt.ByRef = rt.TypedByRef = false;
rt.Void = true;
break;
case ElementType.TypedByRef :
rt.ByRef = rt.Void = false;
rt.TypedByRef = true;
break;
case ElementType.ByRef :
rt.TypedByRef = rt.Void = false;
rt.ByRef = true;
if (rt.CustomMods == null || rt.CustomMods.Length == 0)
rt.CustomMods = ReadCustomMods (data, start, out start);
rt.Type = ReadType (data, start, out start);
break;
default :
rt.TypedByRef = rt.Void = rt.ByRef = false;
rt.Type = ReadType (data, curs, out start);
break;
}
return rt;
}
Param [] ReadParameters (int length, byte [] data, int pos, out int start)
{
Param [] ret = new Param [length];
start = pos;
for (int i = 0; i < length; i++)
ret [i] = ReadParameter (data, start, out start);
return ret;
}
Param [] ReadParameters (int length, byte [] data, int pos, out int start, out int sentinelpos)
{
Param [] ret = new Param [length];
start = pos;
sentinelpos = -1;
for (int i = 0; i < length; i++) {
int curs = start;
int flag = Utilities.ReadCompressedInteger (data, start, out start);
if (flag == (int) ElementType.Sentinel) {
sentinelpos = i;
curs = start;
}
ret [i] = ReadParameter (data, curs, out start);
}
return ret;
}
Param ReadParameter (byte [] data, int pos, out int start)
{
Param p = new Param ();
start = pos;
p.CustomMods = ReadCustomMods (data, start, out start);
int curs = start;
ElementType flag = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
switch (flag) {
case ElementType.TypedByRef :
p.TypedByRef = true;
p.ByRef = false;
break;
case ElementType.ByRef :
p.TypedByRef = false;
p.ByRef = true;
if (p.CustomMods == null || p.CustomMods.Length == 0)
p.CustomMods = ReadCustomMods (data, start, out start);
p.Type = ReadType (data, start, out start);
break;
default :
p.TypedByRef = false;
p.ByRef = false;
p.Type = ReadType (data, curs, out start);
break;
}
return p;
}
SigType ReadType (byte [] data, int pos, out int start)
{
start = pos;
ElementType element = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
switch (element) {
case ElementType.ValueType :
VALUETYPE vt = new VALUETYPE ();
vt.Type = Utilities.GetMetadataToken(CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
return vt;
case ElementType.Class :
CLASS c = new CLASS ();
c.Type = Utilities.GetMetadataToken (CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
return c;
case ElementType.Ptr :
PTR p = new PTR ();
int buf = start;
int flag = Utilities.ReadCompressedInteger (data, start, out start);
p.Void = flag == (int) ElementType.Void;
if (p.Void)
return p;
start = buf;
p.CustomMods = ReadCustomMods (data, start, out start);
p.PtrType = ReadType (data, start, out start);
return p;
case ElementType.FnPtr :
FNPTR fp = new FNPTR ();
if ((data [start] & 0x5) != 0) {
MethodRefSig mr = new MethodRefSig ((uint) start);
ReadMethodRefSig (mr, data, start, out start);
fp.Method = mr;
} else {
MethodDefSig md = new MethodDefSig ((uint) start);
ReadMethodDefSig (md, data, start, out start);
fp.Method = md;
}
return fp;
case ElementType.Array :
ARRAY ary = new ARRAY ();
ary.CustomMods = ReadCustomMods (data, start, out start);
ArrayShape shape = new ArrayShape ();
ary.Type = ReadType (data, start, out start);
shape.Rank = Utilities.ReadCompressedInteger (data, start, out start);
shape.NumSizes = Utilities.ReadCompressedInteger (data, start, out start);
shape.Sizes = new int [shape.NumSizes];
for (int i = 0; i < shape.NumSizes; i++)
shape.Sizes [i] = Utilities.ReadCompressedInteger (data, start, out start);
shape.NumLoBounds = Utilities.ReadCompressedInteger (data, start, out start);
shape.LoBounds = new int [shape.NumLoBounds];
for (int i = 0; i < shape.NumLoBounds; i++)
shape.LoBounds [i] = Utilities.ReadCompressedInteger (data, start, out start);
ary.Shape = shape;
return ary;
case ElementType.SzArray :
SZARRAY sa = new SZARRAY ();
sa.CustomMods = ReadCustomMods (data, start, out start);
sa.Type = ReadType (data, start, out start);
return sa;
case ElementType.Var:
return new VAR (Utilities.ReadCompressedInteger (data, start, out start));
case ElementType.MVar:
return new MVAR (Utilities.ReadCompressedInteger (data, start, out start));
case ElementType.GenericInst:
GENERICINST ginst = new GENERICINST ();
ginst.ValueType = ((ElementType) Utilities.ReadCompressedInteger (
data, start, out start)) == ElementType.ValueType;
ginst.Type = Utilities.GetMetadataToken (CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
ginst.Signature = ReadGenericInstSignature (data, start, out start);
return ginst;
default :
return new SigType (element);
}
}
GenericInstSignature ReadGenericInstSignature (byte [] data, int pos, out int start)
{
start = pos;
GenericInstSignature gis = new GenericInstSignature ();
gis.Arity = Utilities.ReadCompressedInteger (data, start, out start);
gis.Types = new GenericArg [gis.Arity];
for (int i = 0; i < gis.Arity; i++)
gis.Types [i] = ReadGenericArg (data, start, out start);
return gis;
}
GenericArg ReadGenericArg (byte[] data, int pos, out int start)
{
start = pos;
CustomMod [] mods = ReadCustomMods (data, start, out start);
GenericArg arg = new GenericArg (ReadType (data, start, out start));
arg.CustomMods = mods;
return arg;
}
CustomMod [] ReadCustomMods (byte [] data, int pos, out int start)
{
ArrayList cmods = new ArrayList ();
start = pos;
while (true) {
int buf = start;
ElementType flag = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
start = buf;
if (!((flag == ElementType.CModOpt) || (flag == ElementType.CModReqD)))
break;
cmods.Add (ReadCustomMod (data, start, out start));
}
return cmods.ToArray (typeof (CustomMod)) as CustomMod [];
}
CustomMod ReadCustomMod (byte [] data, int pos, out int start)
{
CustomMod cm = new CustomMod ();
start = pos;
ElementType cmod = (ElementType) Utilities.ReadCompressedInteger (data, start, out start);
if (cmod == ElementType.CModOpt)
cm.CMOD = CustomMod.CMODType.OPT;
else if (cmod == ElementType.CModReqD)
cm.CMOD = CustomMod.CMODType.REQD;
else
cm.CMOD = CustomMod.CMODType.None;
cm.TypeDefOrRef = Utilities.GetMetadataToken (CodedIndex.TypeDefOrRef,
(uint) Utilities.ReadCompressedInteger (data, start, out start));
return cm;
}
CustomAttrib ReadCustomAttrib (int pos, MethodReference ctor, bool resolve)
{
int start, length = Utilities.ReadCompressedInteger (m_blobData, pos, out start);
byte [] data = new byte [length];
Buffer.BlockCopy (m_blobData, start, data, 0, length);
try {
return ReadCustomAttrib (new BinaryReader (
new MemoryStream (data)), data, ctor, resolve);
} catch {
CustomAttrib ca = new CustomAttrib (ctor);
ca.Read = false;
return ca;
}
}
CustomAttrib ReadCustomAttrib (BinaryReader br, byte [] data, MethodReference ctor, bool resolve)
{
CustomAttrib ca = new CustomAttrib (ctor);
if (data.Length == 0) {
ca.FixedArgs = new CustomAttrib.FixedArg [0];
ca.NamedArgs = new CustomAttrib.NamedArg [0];
return ca;
}
bool read = true;
ca.Prolog = br.ReadUInt16 ();
if (ca.Prolog != CustomAttrib.StdProlog)
throw new MetadataFormatException ("Non standard prolog for custom attribute");
ca.FixedArgs = new CustomAttrib.FixedArg [ctor.Parameters.Count];
for (int i = 0; i < ca.FixedArgs.Length && read; i++)
ca.FixedArgs [i] = ReadFixedArg (data, br,
ctor.Parameters [i].ParameterType, ref read, resolve);
if (br.BaseStream.Position == br.BaseStream.Length)
read = false;
if (!read) {
ca.Read = read;
return ca;
}
ca.NumNamed = br.ReadUInt16 ();
ca.NamedArgs = new CustomAttrib.NamedArg [ca.NumNamed];
for (int i = 0; i < ca.NumNamed && read; i++)
ca.NamedArgs [i] = ReadNamedArg (data, br, ref read, resolve);
ca.Read = read;
return ca;
}
CustomAttrib.FixedArg ReadFixedArg (byte [] data, BinaryReader br,
TypeReference param, ref bool read, bool resolve)
{
CustomAttrib.FixedArg fa = new CustomAttrib.FixedArg ();
if (param is ArrayType) {
param = ((ArrayType) param).ElementType;
fa.SzArray = true;
fa.NumElem = br.ReadUInt32 ();
if (fa.NumElem == 0 || fa.NumElem == 0xffffffff) {
fa.Elems = new CustomAttrib.Elem [0];
fa.NumElem = 0;
return fa;
}
fa.Elems = new CustomAttrib.Elem [fa.NumElem];
for (int i = 0; i < fa.NumElem; i++)
fa.Elems [i] = ReadElem (data, br, param, ref read, resolve);
} else
fa.Elems = new CustomAttrib.Elem [] { ReadElem (data, br, param, ref read, resolve) };
return fa;
}
TypeReference CreateEnumTypeReference (string enumName)
{
string asmName = null;
int asmStart = enumName.IndexOf (',');
if (asmStart != -1) {
asmName = enumName.Substring (asmStart + 1);
enumName = enumName.Substring (0, asmStart);
}
// Inner class style is reflection style.
enumName = enumName.Replace ('+', '/');
AssemblyNameReference asm;
if (asmName == null) {
// If no assembly is given then the ECMA standard says the
// assembly is either the current one or mscorlib.
if (m_reflectReader.Module.Types.Contains (enumName))
return m_reflectReader.Module.Types [enumName];
asm = m_reflectReader.Corlib;
} else
asm = AssemblyNameReference.Parse (asmName);
string [] outers = enumName.Split ('/');
string outerfullname = outers [0];
string ns = null;
int nsIndex = outerfullname.LastIndexOf ('.');
if (nsIndex != -1)
ns = outerfullname.Substring (0, nsIndex);
string name = outerfullname.Substring (nsIndex + 1);
TypeReference decType = new TypeReference (name, ns, asm);
for (int i = 1; i < outers.Length; i++) {
TypeReference t = new TypeReference (outers [i], null, asm);
t.DeclaringType = decType;
decType = t;
}
decType.IsValueType = true;
return decType;
}
TypeReference ReadTypeReference (byte [] data, BinaryReader br, out ElementType elemType)
{
bool array = false;
elemType = (ElementType) br.ReadByte ();
if (elemType == ElementType.SzArray) {
elemType = (ElementType) br.ReadByte ();
array = true;
}
TypeReference res;
if (elemType == ElementType.Enum)
res = CreateEnumTypeReference (ReadUTF8String (data, br));
else
res = TypeReferenceFromElemType (elemType);
if (array)
res = new ArrayType (res);
return res;
}
TypeReference TypeReferenceFromElemType (ElementType elemType)
{
switch (elemType) {
case ElementType.Boxed :
case ElementType.Object:
return m_reflectReader.SearchCoreType (Constants.Object);
case ElementType.String :
return m_reflectReader.SearchCoreType (Constants.String);
case ElementType.Type :
return m_reflectReader.SearchCoreType (Constants.Type);
case ElementType.Boolean :
return m_reflectReader.SearchCoreType (Constants.Boolean);
case ElementType.Char :
return m_reflectReader.SearchCoreType (Constants.Char);
case ElementType.R4 :
return m_reflectReader.SearchCoreType (Constants.Single);
case ElementType.R8 :
return m_reflectReader.SearchCoreType (Constants.Double);
case ElementType.I1 :
return m_reflectReader.SearchCoreType (Constants.SByte);
case ElementType.I2 :
return m_reflectReader.SearchCoreType (Constants.Int16);
case ElementType.I4 :
return m_reflectReader.SearchCoreType (Constants.Int32);
case ElementType.I8 :
return m_reflectReader.SearchCoreType (Constants.Int64);
case ElementType.U1 :
return m_reflectReader.SearchCoreType (Constants.Byte);
case ElementType.U2 :
return m_reflectReader.SearchCoreType (Constants.UInt16);
case ElementType.U4 :
return m_reflectReader.SearchCoreType (Constants.UInt32);
case ElementType.U8 :
return m_reflectReader.SearchCoreType (Constants.UInt64);
default :
throw new MetadataFormatException ("Non valid type in CustomAttrib.Elem: 0x{0}",
((byte) elemType).ToString("x2"));
}
}
internal CustomAttrib.NamedArg ReadNamedArg (byte [] data, BinaryReader br, ref bool read, bool resolve)
{
CustomAttrib.NamedArg na = new CustomAttrib.NamedArg ();
byte kind = br.ReadByte ();
if (kind == 0x53) { // field
na.Field = true;
na.Property = false;
} else if (kind == 0x54) { // property
na.Field = false;
na.Property = true;
} else
throw new MetadataFormatException ("Wrong kind of namedarg found: 0x" + kind.ToString("x2"));
TypeReference elemType = ReadTypeReference (data, br, out na.FieldOrPropType);
na.FieldOrPropName = ReadUTF8String (data, br);
na.FixedArg = ReadFixedArg (data, br, elemType, ref read, resolve);
return na;
}
CustomAttrib.Elem ReadElem (byte [] data, BinaryReader br, TypeReference elemType, ref bool read, bool resolve)
{
CustomAttrib.Elem elem = new CustomAttrib.Elem ();
string elemName = elemType.FullName;
if (elemName == Constants.Object) {
elemType = ReadTypeReference (data, br, out elem.FieldOrPropType);
if (elemType is ArrayType) {
read = false; // Don't know how to represent arrays as an object value.
return elem;
} else if (elemType.FullName == Constants.Object)
throw new MetadataFormatException ("Non valid type in CustomAttrib.Elem after boxed prefix: 0x{0}",
((byte) elem.FieldOrPropType).ToString ("x2"));
elem = ReadElem (data, br, elemType, ref read, resolve);
elem.String = elem.Simple = elem.Type = false;
elem.BoxedValueType = true;
return elem;
}
elem.ElemType = elemType;
if (elemName == Constants.Type || elemName == Constants.String) {
switch (elemType.FullName) {
case Constants.String:
elem.String = true;
elem.BoxedValueType = elem.Simple = elem.Type = false;
break;
case Constants.Type:
elem.Type = true;
elem.BoxedValueType = elem.Simple = elem.String = false;
break;
}
if (data [br.BaseStream.Position] == 0xff) { // null
elem.Value = null;
br.BaseStream.Position++;
} else {
elem.Value = ReadUTF8String (data, br);
}
return elem;
}
elem.String = elem.Type = elem.BoxedValueType = false;
if (!ReadSimpleValue (br, ref elem, elem.ElemType)) {
if (!resolve) { // until enums writing is implemented
read = false;
return elem;
}
TypeReference typeRef = GetEnumUnderlyingType (elem.ElemType, resolve);
if (typeRef == null || !ReadSimpleValue (br, ref elem, typeRef))
read = false;
}
return elem;
}
TypeReference GetEnumUnderlyingType (TypeReference enumType, bool resolve)
{
TypeDefinition type = enumType as TypeDefinition;
if (type == null && resolve && AssemblyResolver != null) {
if (enumType.Scope is ModuleDefinition)
throw new NotSupportedException ();
AssemblyDefinition asm = AssemblyResolver.Resolve (
((AssemblyNameReference) enumType.Scope).FullName);
type = asm.MainModule.Types [enumType.FullName];
}
if (type != null && type.IsEnum)
return type.Fields.GetField ("value__").FieldType;
return null;
}
bool ReadSimpleValue (BinaryReader br, ref CustomAttrib.Elem elem, TypeReference type)
{
switch (type.FullName) {
case Constants.Boolean :
elem.Value = br.ReadByte () == 1;
break;
case Constants.Char :
elem.Value = (char) br.ReadUInt16 ();
break;
case Constants.Single :
elem.Value = br.ReadSingle ();
break;
case Constants.Double :
elem.Value = br.ReadDouble ();
break;
case Constants.Byte :
elem.Value = br.ReadByte ();
break;
case Constants.Int16 :
elem.Value = br.ReadInt16 ();
break;
case Constants.Int32 :
elem.Value = br.ReadInt32 ();
break;
case Constants.Int64 :
elem.Value = br.ReadInt64 ();
break;
case Constants.SByte :
elem.Value = br.ReadSByte ();
break;
case Constants.UInt16 :
elem.Value = br.ReadUInt16 ();
break;
case Constants.UInt32 :
elem.Value = br.ReadUInt32 ();
break;
case Constants.UInt64 :
elem.Value = br.ReadUInt64 ();
break;
default : // enum
return false;
}
elem.Simple = true;
return true;
}
MarshalSig ReadMarshalSig (byte [] data)
{
int start;
MarshalSig ms = new MarshalSig ((NativeType) Utilities.ReadCompressedInteger (data, 0, out start));
switch (ms.NativeInstrinsic) {
case NativeType.ARRAY:
MarshalSig.Array ar = new MarshalSig.Array ();
ar.ArrayElemType = (NativeType) Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
ar.ParamNum = Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
ar.NumElem = Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
ar.ElemMult = Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = ar;
break;
case NativeType.CUSTOMMARSHALER:
MarshalSig.CustomMarshaler cm = new MarshalSig.CustomMarshaler ();
cm.Guid = ReadUTF8String (data, start, out start);
cm.UnmanagedType = ReadUTF8String (data, start, out start);
cm.ManagedType = ReadUTF8String (data, start, out start);
cm.Cookie = ReadUTF8String (data, start, out start);
ms.Spec = cm;
break;
case NativeType.FIXEDARRAY:
MarshalSig.FixedArray fa = new MarshalSig.FixedArray ();
fa.NumElem = Utilities.ReadCompressedInteger (data, start, out start);
if (start < data.Length)
fa.ArrayElemType = (NativeType) Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = fa;
break;
case NativeType.SAFEARRAY:
MarshalSig.SafeArray sa = new MarshalSig.SafeArray ();
if (start < data.Length)
sa.ArrayElemType = (VariantType) Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = sa;
break;
case NativeType.FIXEDSYSSTRING:
MarshalSig.FixedSysString fss = new MarshalSig.FixedSysString ();
if (start < data.Length)
fss.Size = Utilities.ReadCompressedInteger (data, start, out start);
ms.Spec = fss;
break;
}
return ms;
}
static internal string ReadUTF8String (byte [] data, BinaryReader br)
{
int start = (int)br.BaseStream.Position;
string val = ReadUTF8String (data, start, out start);
br.BaseStream.Position = start;
return val;
}
static internal string ReadUTF8String (byte [] data, int pos, out int start)
{
int length = Utilities.ReadCompressedInteger (data, pos, out start);
pos = start;
start += length;
// COMPACT FRAMEWORK NOTE: Encoding.GetString (byte[]) is not supported.
return Encoding.UTF8.GetString (data, pos, length);
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a JSON constructor.
/// </summary>
public class JConstructor : JContainer
{
private string _name;
private IList<JToken> _values = new List<JToken>();
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected override IList<JToken> ChildrenTokens
{
get { return _values; }
}
/// <summary>
/// Gets or sets the name of this constructor.
/// </summary>
/// <value>The constructor name.</value>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// Gets the node type for this <see cref="JToken"/>.
/// </summary>
/// <value>The type.</value>
public override JTokenType Type
{
get { return JTokenType.Constructor; }
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class.
/// </summary>
public JConstructor()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class from another <see cref="JConstructor"/> object.
/// </summary>
/// <param name="other">A <see cref="JConstructor"/> object to copy from.</param>
public JConstructor(JConstructor other)
: base(other)
{
_name = other.Name;
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content.
/// </summary>
/// <param name="name">The constructor name.</param>
/// <param name="content">The contents of the constructor.</param>
public JConstructor(string name, params object[] content)
: this(name, (object)content)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content.
/// </summary>
/// <param name="name">The constructor name.</param>
/// <param name="content">The contents of the constructor.</param>
public JConstructor(string name, object content)
: this(name)
{
Add(content);
}
/// <summary>
/// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name.
/// </summary>
/// <param name="name">The constructor name.</param>
public JConstructor(string name)
{
ValidationUtils.ArgumentNotNullOrEmpty(name, "name");
_name = name;
}
internal override bool DeepEquals(JToken node)
{
JConstructor c = node as JConstructor;
return (c != null && _name == c.Name && ContentsEqual(c));
}
internal override JToken CloneToken()
{
return new JConstructor(this);
}
/// <summary>
/// Writes this token to a <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
writer.WriteStartConstructor(_name);
foreach (JToken token in Children())
{
token.WriteTo(writer, converters);
}
writer.WriteEndConstructor();
}
/// <summary>
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public override JToken this[object key]
{
get
{
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
return GetItem((int)key);
}
set
{
ValidationUtils.ArgumentNotNull(key, "o");
if (!(key is int))
throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key)));
SetItem((int)key, value);
}
}
internal override int GetDeepHashCode()
{
return _name.GetHashCode() ^ ContentsHashCode();
}
/// <summary>
/// Loads an <see cref="JConstructor"/> from a <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param>
/// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public static new JConstructor Load(JsonReader reader)
{
if (reader.TokenType == JsonToken.None)
{
if (!reader.Read())
throw new Exception("Error reading JConstructor from JsonReader.");
}
if (reader.TokenType != JsonToken.StartConstructor)
throw new Exception("Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
JConstructor c = new JConstructor((string)reader.Value);
c.SetLineInfo(reader as IJsonLineInfo);
c.ReadTokenFrom(reader);
return c;
}
}
}
#endif
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
namespace OpenADK.Web.Http
{
/// <summary>
/// Summary description for HttpRequest.
/// </summary>
public class AdkHttpRequest
{
private Uri fUri;
private Stream fRequestStream;
private int fContentLength = -1;
private NameValueCollection fHeaders = new NameValueCollection();
private string fProtocol;
private AdkHttpConnection fConnection;
private string fMethod;
private string fPath;
private bool fIsGet = false;
public AdkHttpRequest( AdkHttpConnection connection )
{
fConnection = connection;
}
private void ParseRequestLine( TextReader reader )
{
// HTTP request lines are of the form:
// [METHOD] [Encoded URL] HTTP/1.?
string aRequestLine = reader.ReadLine();
if ( aRequestLine == null ) {
throw new AdkHttpException
( AdkHttpStatusCode.ClientError_400_Bad_Request, "Expected Http Headers" );
}
string [] tokens = aRequestLine.Split( new char [] {' '} );
if ( tokens.Length != 3 ) {
throw new AdkHttpException
( AdkHttpStatusCode.ClientError_400_Bad_Request,
"Improperly formed request line" );
}
fMethod = tokens[0];
fPath = tokens[1];
// Only accept valid urls
if ( !fPath.StartsWith( "/" ) ) {
throw new AdkHttpException
( AdkHttpStatusCode.ClientError_400_Bad_Request, "Bad Url" );
}
// Decode all encoded parts of the URL using the built in URI processing class
int i = 0;
while ( (i = fPath.IndexOf( "%", i )) != -1 ) {
fPath = fPath.Substring( 0, i ) + Uri.HexUnescape( fPath, ref i ) +
fPath.Substring( i );
}
fProtocol = tokens[2];
if ( !fProtocol.StartsWith( "HTTP/" ) ) {
throw new AdkHttpException
( AdkHttpStatusCode.ClientError_400_Bad_Request,
"Unknown protocol: " + fProtocol );
}
}
public void Receive( AdkSocketConnection connection )
{
if ( fContentLength == -1 ) {
MemoryStream initialBuffer =
new MemoryStream
( connection.RawBuffer, 0, connection.RawBufferLength, false, false );
AdkHttpHeadersReader reader = new AdkHttpHeadersReader( initialBuffer );
ParseRequestLine( reader );
ParseHeaders( reader );
// This server does not support transfer encoding
if ( this.Headers["Transfer-Encoding"] != null ) {
throw new AdkHttpException
( AdkHttpStatusCode.ServerError_501_Not_Implemented,
"'Transfer-Encoding' is not supported" );
}
IPEndPoint endPoint = (IPEndPoint) connection.Socket.LocalEndPoint;
string host = fHeaders["Host"];
if ( host == null ) {
host = endPoint.Address.ToString();
}
else {
int loc = host.IndexOf( ':' );
if ( loc > 0 ) {
host = host.Substring( 0, loc );
}
}
// TODO: Implement better parsing of the query string. This will sometimes blow up when it shouldn't.
string [] pathAndQuery = this.Path.Split( '?' );
UriBuilder builder =
new UriBuilder
( "http", host, connection.Binding.Port, pathAndQuery[0],
pathAndQuery.Length > 1 ? pathAndQuery[1] : "" );
fUri = new Uri( builder.ToString() );
// Now create the request stream, but chop of the headers
if ( this.ContentLength > 0 ) {
fRequestStream = new MemoryStream( (int) this.ContentLength );
fRequestStream.Write
( connection.RawBuffer, (int) reader.Position,
(int) (connection.RawBufferLength - reader.Position) );
}
}
else if ( ReceiveComplete ) {
throw new AdkHttpException
( AdkHttpStatusCode.ClientError_400_Bad_Request,
"Too much data received for specified Content-Length" );
}
else {
fRequestStream.Write( connection.RawBuffer, 0, connection.RawBufferLength );
}
}
public bool ReceiveComplete
{
get { return fIsGet || fRequestStream.Length >= this.ContentLength; }
}
public string Path
{
get { return fPath; }
}
public string Protocol
{
get { return fProtocol; }
}
public string Method
{
get { return fMethod; }
}
public NameValueCollection Headers
{
get { return fHeaders; }
}
public string HostName
{
get { return fHeaders["Host"]; }
}
public string ConnectionHeader
{
get { return fHeaders["Connection"]; }
}
public string RemoteAddress
{
get { return fConnection.ClientEndPoint.Address.ToString(); }
}
public string ContentType
{
get { return fHeaders["Content-Type"]; }
}
public long ContentLength
{
get
{
if ( fContentLength == -1 ) {
string length = fHeaders["Content-Length"];
if ( length == null ) {
fContentLength = 0;
}
try {
fContentLength = int.Parse( length );
}
catch {
fContentLength = 0;
}
}
return fContentLength;
}
}
private void ParseHeaders( TextReader reader )
{
string aLine;
string aHeaderName = null;
// The headers end with either a socket close (!) or an empty line
while ( (aLine = reader.ReadLine()) != null ) {
if ( aLine.Length > 0 ) {
// If the value begins with a space or a hard tab then this
// is an extension of the value of the previous header and
// should be appended
if ( aHeaderName != null && Char.IsWhiteSpace( aLine[0] ) ) {
string aVal = fHeaders[aHeaderName];
aVal += aLine;
fHeaders[aHeaderName] = aVal;
continue;
}
// Headers consist of [NAME]: [VALUE] + possible extension lines
int firstColon = aLine.IndexOf( ":" );
if ( firstColon > -1 ) {
aHeaderName = aLine.Substring( 0, firstColon );
string value = aLine.Substring( firstColon + 1 ).Trim();
fHeaders[aHeaderName] = value;
}
else {
throw new ArgumentException( "Bad header: " + aLine );
}
}
}
if ( fMethod == "GET" ) {
fContentLength = 0;
fIsGet = true;
}
else {
if ( fHeaders["Content-Length"] == null ) {
throw new AdkHttpException
( AdkHttpStatusCode.ClientError_411_Length_Required,
"Expected Content-Length header" );
}
fIsGet = false;
}
}
/// <summary>
/// Returns the entire stream of data that has been read from the transport
/// </summary>
/// <returns></returns>
public Stream GetRequestStream()
{
if ( !(fRequestStream.Position == 0) ) {
fRequestStream.Seek( 0, SeekOrigin.Begin );
}
return fRequestStream;
}
public Uri Url
{
get { return fUri; }
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// File Store for streaming files to eMaze Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SPFSTOREDataSet : EduHubDataSet<SPFSTORE>
{
/// <inheritdoc />
public override string Name { get { return "SPFSTORE"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SPFSTOREDataSet(EduHubContext Context)
: base(Context)
{
Index_FILE_ID = new Lazy<Dictionary<int, SPFSTORE>>(() => this.ToDictionary(i => i.FILE_ID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SPFSTORE" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SPFSTORE" /> fields for each CSV column header</returns>
internal override Action<SPFSTORE, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SPFSTORE, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "FILE_ID":
mapper[i] = (e, v) => e.FILE_ID = int.Parse(v);
break;
case "PHYSICAL_LOCATION":
mapper[i] = (e, v) => e.PHYSICAL_LOCATION = v;
break;
case "ROOT_ID":
mapper[i] = (e, v) => e.ROOT_ID = v;
break;
case "DISPLAY_NAME":
mapper[i] = (e, v) => e.DISPLAY_NAME = v;
break;
case "MIME_TYPE":
mapper[i] = (e, v) => e.MIME_TYPE = v;
break;
case "ASSOCIATION_TYPE":
mapper[i] = (e, v) => e.ASSOCIATION_TYPE = int.Parse(v);
break;
case "PAGE_ID":
mapper[i] = (e, v) => e.PAGE_ID = v;
break;
case "FILE_SIZE":
mapper[i] = (e, v) => e.FILE_SIZE = v == null ? (int?)null : int.Parse(v);
break;
case "FILE_EXTENSION":
mapper[i] = (e, v) => e.FILE_EXTENSION = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SPFSTORE" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SPFSTORE" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SPFSTORE" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SPFSTORE}"/> of entities</returns>
internal override IEnumerable<SPFSTORE> ApplyDeltaEntities(IEnumerable<SPFSTORE> Entities, List<SPFSTORE> DeltaEntities)
{
HashSet<int> Index_FILE_ID = new HashSet<int>(DeltaEntities.Select(i => i.FILE_ID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.FILE_ID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_FILE_ID.Remove(entity.FILE_ID);
if (entity.FILE_ID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, SPFSTORE>> Index_FILE_ID;
#endregion
#region Index Methods
/// <summary>
/// Find SPFSTORE by FILE_ID field
/// </summary>
/// <param name="FILE_ID">FILE_ID value used to find SPFSTORE</param>
/// <returns>Related SPFSTORE entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SPFSTORE FindByFILE_ID(int FILE_ID)
{
return Index_FILE_ID.Value[FILE_ID];
}
/// <summary>
/// Attempt to find SPFSTORE by FILE_ID field
/// </summary>
/// <param name="FILE_ID">FILE_ID value used to find SPFSTORE</param>
/// <param name="Value">Related SPFSTORE entity</param>
/// <returns>True if the related SPFSTORE entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByFILE_ID(int FILE_ID, out SPFSTORE Value)
{
return Index_FILE_ID.Value.TryGetValue(FILE_ID, out Value);
}
/// <summary>
/// Attempt to find SPFSTORE by FILE_ID field
/// </summary>
/// <param name="FILE_ID">FILE_ID value used to find SPFSTORE</param>
/// <returns>Related SPFSTORE entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SPFSTORE TryFindByFILE_ID(int FILE_ID)
{
SPFSTORE value;
if (Index_FILE_ID.Value.TryGetValue(FILE_ID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SPFSTORE table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SPFSTORE]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SPFSTORE](
[FILE_ID] int IDENTITY NOT NULL,
[PHYSICAL_LOCATION] varchar(500) NOT NULL,
[ROOT_ID] varchar(255) NULL,
[DISPLAY_NAME] varchar(50) NOT NULL,
[MIME_TYPE] varchar(100) NOT NULL,
[ASSOCIATION_TYPE] int NOT NULL,
[PAGE_ID] varchar(200) NULL,
[FILE_SIZE] int NULL,
[FILE_EXTENSION] varchar(10) NULL,
[LW_DATE] datetime NOT NULL,
[LW_USER] varchar(128) NOT NULL,
CONSTRAINT [SPFSTORE_Index_FILE_ID] PRIMARY KEY CLUSTERED (
[FILE_ID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="SPFSTOREDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="SPFSTOREDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SPFSTORE"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SPFSTORE"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SPFSTORE> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_FILE_ID = new List<int>();
foreach (var entity in Entities)
{
Index_FILE_ID.Add(entity.FILE_ID);
}
builder.AppendLine("DELETE [dbo].[SPFSTORE] WHERE");
// Index_FILE_ID
builder.Append("[FILE_ID] IN (");
for (int index = 0; index < Index_FILE_ID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// FILE_ID
var parameterFILE_ID = $"@p{parameterIndex++}";
builder.Append(parameterFILE_ID);
command.Parameters.Add(parameterFILE_ID, SqlDbType.Int).Value = Index_FILE_ID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SPFSTORE data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SPFSTORE data set</returns>
public override EduHubDataSetDataReader<SPFSTORE> GetDataSetDataReader()
{
return new SPFSTOREDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SPFSTORE data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SPFSTORE data set</returns>
public override EduHubDataSetDataReader<SPFSTORE> GetDataSetDataReader(List<SPFSTORE> Entities)
{
return new SPFSTOREDataReader(new EduHubDataSetLoadedReader<SPFSTORE>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SPFSTOREDataReader : EduHubDataSetDataReader<SPFSTORE>
{
public SPFSTOREDataReader(IEduHubDataSetReader<SPFSTORE> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 11; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // FILE_ID
return Current.FILE_ID;
case 1: // PHYSICAL_LOCATION
return Current.PHYSICAL_LOCATION;
case 2: // ROOT_ID
return Current.ROOT_ID;
case 3: // DISPLAY_NAME
return Current.DISPLAY_NAME;
case 4: // MIME_TYPE
return Current.MIME_TYPE;
case 5: // ASSOCIATION_TYPE
return Current.ASSOCIATION_TYPE;
case 6: // PAGE_ID
return Current.PAGE_ID;
case 7: // FILE_SIZE
return Current.FILE_SIZE;
case 8: // FILE_EXTENSION
return Current.FILE_EXTENSION;
case 9: // LW_DATE
return Current.LW_DATE;
case 10: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // ROOT_ID
return Current.ROOT_ID == null;
case 6: // PAGE_ID
return Current.PAGE_ID == null;
case 7: // FILE_SIZE
return Current.FILE_SIZE == null;
case 8: // FILE_EXTENSION
return Current.FILE_EXTENSION == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // FILE_ID
return "FILE_ID";
case 1: // PHYSICAL_LOCATION
return "PHYSICAL_LOCATION";
case 2: // ROOT_ID
return "ROOT_ID";
case 3: // DISPLAY_NAME
return "DISPLAY_NAME";
case 4: // MIME_TYPE
return "MIME_TYPE";
case 5: // ASSOCIATION_TYPE
return "ASSOCIATION_TYPE";
case 6: // PAGE_ID
return "PAGE_ID";
case 7: // FILE_SIZE
return "FILE_SIZE";
case 8: // FILE_EXTENSION
return "FILE_EXTENSION";
case 9: // LW_DATE
return "LW_DATE";
case 10: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "FILE_ID":
return 0;
case "PHYSICAL_LOCATION":
return 1;
case "ROOT_ID":
return 2;
case "DISPLAY_NAME":
return 3;
case "MIME_TYPE":
return 4;
case "ASSOCIATION_TYPE":
return 5;
case "PAGE_ID":
return 6;
case "FILE_SIZE":
return 7;
case "FILE_EXTENSION":
return 8;
case "LW_DATE":
return 9;
case "LW_USER":
return 10;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPoco;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Dtos;
using Umbraco.Core.Configuration;
using Umbraco.Core.Scoping;
namespace Umbraco.Core.Sync
{
/// <summary>
/// An <see cref="IServerMessenger"/> that works by storing messages in the database.
/// </summary>
//
// this messenger writes ALL instructions to the database,
// but only processes instructions coming from remote servers,
// thus ensuring that instructions run only once
//
public class DatabaseServerMessenger : ServerMessengerBase
{
private readonly IRuntimeState _runtime;
private readonly ManualResetEvent _syncIdle;
private readonly object _locko = new object();
private readonly IProfilingLogger _profilingLogger;
private readonly ISqlContext _sqlContext;
private readonly Lazy<string> _distCacheFilePath;
private int _lastId = -1;
private DateTime _lastSync;
private DateTime _lastPruned;
private bool _initialized;
private bool _syncing;
private bool _released;
public DatabaseServerMessengerOptions Options { get; }
public DatabaseServerMessenger(
IRuntimeState runtime, IScopeProvider scopeProvider, ISqlContext sqlContext, IProfilingLogger proflog, IGlobalSettings globalSettings,
bool distributedEnabled, DatabaseServerMessengerOptions options)
: base(distributedEnabled)
{
ScopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider));
_sqlContext = sqlContext;
_runtime = runtime;
_profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog));
Logger = proflog;
Options = options ?? throw new ArgumentNullException(nameof(options));
_lastPruned = _lastSync = DateTime.UtcNow;
_syncIdle = new ManualResetEvent(true);
_distCacheFilePath = new Lazy<string>(() => GetDistCacheFilePath(globalSettings));
}
protected ILogger Logger { get; }
protected IScopeProvider ScopeProvider { get; }
protected Sql<ISqlContext> Sql() => _sqlContext.Sql();
private string DistCacheFilePath => _distCacheFilePath.Value;
#region Messenger
protected override bool RequiresDistributed(ICacheRefresher refresher, MessageType dispatchType)
{
// we don't care if there's servers listed or not,
// if distributed call is enabled we will make the call
return _initialized && DistributedEnabled;
}
protected override void DeliverRemote(
ICacheRefresher refresher,
MessageType messageType,
IEnumerable<object> ids = null,
string json = null)
{
var idsA = ids?.ToArray();
if (GetArrayType(idsA, out var idType) == false)
throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids));
var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json);
var dto = new CacheInstructionDto
{
UtcStamp = DateTime.UtcNow,
Instructions = JsonConvert.SerializeObject(instructions, Formatting.None),
OriginIdentity = LocalIdentity,
InstructionCount = instructions.Sum(x => x.JsonIdCount)
};
using (var scope = ScopeProvider.CreateScope())
{
scope.Database.Insert(dto);
scope.Complete();
}
}
#endregion
#region Sync
/// <summary>
/// Boots the messenger.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
protected void Boot()
{
// weight:10, must release *before* the published snapshot service, because once released
// the service will *not* be able to properly handle our notifications anymore
const int weight = 10;
if (!(_runtime is RuntimeState runtime))
throw new NotSupportedException($"Unsupported IRuntimeState implementation {_runtime.GetType().FullName}, expecting {typeof(RuntimeState).FullName}.");
var registered = runtime.MainDom.Register(
() =>
{
lock (_locko)
{
_released = true; // no more syncs
}
// wait a max of 5 seconds and then return, so that we don't block
// the entire MainDom callbacks chain and prevent the AppDomain from
// properly releasing MainDom - a timeout here means that one refresher
// is taking too much time processing, however when it's done we will
// not update lastId and stop everything
var idle =_syncIdle.WaitOne(5000);
if (idle == false)
{
Logger.Warn<DatabaseServerMessenger>("The wait lock timed out, application is shutting down. The current instruction batch will be re-processed.");
}
},
weight);
if (registered == false)
return;
ReadLastSynced(); // get _lastId
using (var scope = ScopeProvider.CreateScope())
{
EnsureInstructions(scope.Database); // reset _lastId if instrs are missing
Initialize(scope.Database); // boot
scope.Complete();
}
}
/// <summary>
/// Initializes a server that has never synchronized before.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
private void Initialize(IUmbracoDatabase database)
{
lock (_locko)
{
if (_released) return;
var coldboot = false;
if (_lastId < 0) // never synced before
{
// we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new
// server and it will need to rebuild it's own caches, eg Lucene or the xml cache file.
Logger.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install."
+ " The server will build its caches and indexes, and then adjust its last synced Id to the latest found in"
+ " the database and maintain cache updates based on that Id.");
coldboot = true;
}
else
{
//check for how many instructions there are to process, each row contains a count of the number of instructions contained in each
//row so we will sum these numbers to get the actual count.
var count = database.ExecuteScalar<int>("SELECT SUM(instructionCount) FROM umbracoCacheInstruction WHERE id > @lastId", new {lastId = _lastId});
if (count > Options.MaxProcessingInstructionCount)
{
//too many instructions, proceed to cold boot
Logger.Warn<DatabaseServerMessenger>(
"The instruction count ({InstructionCount}) exceeds the specified MaxProcessingInstructionCount ({MaxProcessingInstructionCount})."
+ " The server will skip existing instructions, rebuild its caches and indexes entirely, adjust its last synced Id"
+ " to the latest found in the database and maintain cache updates based on that Id.",
count, Options.MaxProcessingInstructionCount);
coldboot = true;
}
}
if (coldboot)
{
// go get the last id in the db and store it
// note: do it BEFORE initializing otherwise some instructions might get lost
// when doing it before, some instructions might run twice - not an issue
var maxId = database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction");
//if there is a max currently, or if we've never synced
if (maxId > 0 || _lastId < 0)
SaveLastSynced(maxId);
// execute initializing callbacks
if (Options.InitializingCallbacks != null)
foreach (var callback in Options.InitializingCallbacks)
callback();
}
_initialized = true;
}
}
/// <summary>
/// Synchronize the server (throttled).
/// </summary>
protected internal void Sync()
{
lock (_locko)
{
if (_syncing)
return;
//Don't continue if we are released
if (_released)
return;
if ((DateTime.UtcNow - _lastSync).TotalSeconds <= Options.ThrottleSeconds)
return;
//Set our flag and the lock to be in it's original state (i.e. it can be awaited)
_syncing = true;
_syncIdle.Reset();
_lastSync = DateTime.UtcNow;
}
try
{
using (_profilingLogger.DebugDuration<DatabaseServerMessenger>("Syncing from database..."))
using (var scope = ScopeProvider.CreateScope())
{
ProcessDatabaseInstructions(scope.Database);
//Check for pruning throttling
if (_released || (DateTime.UtcNow - _lastPruned).TotalSeconds <= Options.PruneThrottleSeconds)
{
scope.Complete();
return;
}
_lastPruned = _lastSync;
switch (Current.RuntimeState.ServerRole)
{
case ServerRole.Single:
case ServerRole.Master:
PruneOldInstructions(scope.Database);
break;
}
scope.Complete();
}
}
finally
{
lock (_locko)
{
//We must reset our flag and signal any waiting locks
_syncing = false;
}
_syncIdle.Set();
}
}
/// <summary>
/// Process instructions from the database.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
/// <returns>
/// Returns the number of processed instructions
/// </returns>
private void ProcessDatabaseInstructions(IUmbracoDatabase database)
{
// NOTE
// we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that
// would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests
// (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are
// pending requests after being processed, they'll just be processed on the next poll.
//
// FIXME not true if we're running on a background thread, assuming we can?
var sql = Sql().SelectAll()
.From<CacheInstructionDto>()
.Where<CacheInstructionDto>(dto => dto.Id > _lastId)
.OrderBy<CacheInstructionDto>(dto => dto.Id);
//only retrieve the top 100 (just in case there's tons)
// even though MaxProcessingInstructionCount is by default 1000 we still don't want to process that many
// rows in one request thread since each row can contain a ton of instructions (until 7.5.5 in which case
// a row can only contain MaxProcessingInstructionCount)
var topSql = sql.SelectTop(100);
// only process instructions coming from a remote server, and ignore instructions coming from
// the local server as they've already been processed. We should NOT assume that the sequence of
// instructions in the database makes any sense whatsoever, because it's all async.
var localIdentity = LocalIdentity;
var lastId = 0;
//tracks which ones have already been processed to avoid duplicates
var processed = new HashSet<RefreshInstruction>();
//It would have been nice to do this in a Query instead of Fetch using a data reader to save
// some memory however we cannot do thta because inside of this loop the cache refreshers are also
// performing some lookups which cannot be done with an active reader open
foreach (var dto in database.Fetch<CacheInstructionDto>(topSql))
{
//If this flag gets set it means we're shutting down! In this case, we need to exit asap and cannot
// continue processing anything otherwise we'll hold up the app domain shutdown
if (_released)
{
break;
}
if (dto.OriginIdentity == localIdentity)
{
// just skip that local one but update lastId nevertheless
lastId = dto.Id;
continue;
}
// deserialize remote instructions & skip if it fails
JArray jsonA;
try
{
jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions);
}
catch (JsonException ex)
{
Logger.Error<DatabaseServerMessenger>(ex, "Failed to deserialize instructions ({DtoId}: '{DtoInstructions}').",
dto.Id,
dto.Instructions);
lastId = dto.Id; // skip
continue;
}
var instructionBatch = GetAllInstructions(jsonA);
//process as per-normal
var success = ProcessDatabaseInstructions(instructionBatch, dto, processed, ref lastId);
//if they couldn't be all processed (i.e. we're shutting down) then exit
if (success == false)
{
Logger.Info<DatabaseServerMessenger>("The current batch of instructions was not processed, app is shutting down");
break;
}
}
if (lastId > 0)
SaveLastSynced(lastId);
}
/// <summary>
/// Processes the instruction batch and checks for errors
/// </summary>
/// <param name="instructionBatch"></param>
/// <param name="dto"></param>
/// <param name="processed">
/// Tracks which instructions have already been processed to avoid duplicates
/// </param>
/// <param name="lastId"></param>
/// <returns>
/// returns true if all instructions in the batch were processed, otherwise false if they could not be due to the app being shut down
/// </returns>
private bool ProcessDatabaseInstructions(IReadOnlyCollection<RefreshInstruction> instructionBatch, CacheInstructionDto dto, HashSet<RefreshInstruction> processed, ref int lastId)
{
// execute remote instructions & update lastId
try
{
var result = NotifyRefreshers(instructionBatch, processed);
if (result)
{
//if all instructions we're processed, set the last id
lastId = dto.Id;
}
return result;
}
//catch (ThreadAbortException ex)
//{
// //This will occur if the instructions processing is taking too long since this is occuring on a request thread.
// // Or possibly if IIS terminates the appdomain. In any case, we should deal with this differently perhaps...
//}
catch (Exception ex)
{
Logger.Error<DatabaseServerMessenger>(
ex,
"DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({DtoId}: '{DtoInstructions}'). Instruction is being skipped/ignored",
dto.Id,
dto.Instructions);
//we cannot throw here because this invalid instruction will just keep getting processed over and over and errors
// will be thrown over and over. The only thing we can do is ignore and move on.
lastId = dto.Id;
return false;
}
////if this is returned it will not be saved
//return -1;
}
/// <summary>
/// Remove old instructions from the database
/// </summary>
/// <remarks>
/// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause
/// the site to cold boot if there's been no instruction activity for more than DaysToRetainInstructions.
/// See: http://issues.umbraco.org/issue/U4-7643#comment=67-25085
/// </remarks>
private void PruneOldInstructions(IUmbracoDatabase database)
{
var pruneDate = DateTime.UtcNow.AddDays(-Options.DaysToRetainInstructions);
// using 2 queries is faster than convoluted joins
var maxId = database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction;");
var delete = new Sql().Append(@"DELETE FROM umbracoCacheInstruction WHERE utcStamp < @pruneDate AND id < @maxId",
new { pruneDate, maxId });
database.Execute(delete);
}
/// <summary>
/// Ensure that the last instruction that was processed is still in the database.
/// </summary>
/// <remarks>
/// If the last instruction is not in the database anymore, then the messenger
/// should not try to process any instructions, because some instructions might be lost,
/// and it should instead cold-boot.
/// However, if the last synced instruction id is '0' and there are '0' records, then this indicates
/// that it's a fresh site and no user actions have taken place, in this circumstance we do not want to cold
/// boot. See: http://issues.umbraco.org/issue/U4-8627
/// </remarks>
private void EnsureInstructions(IUmbracoDatabase database)
{
if (_lastId == 0)
{
var sql = Sql().Select("COUNT(*)")
.From<CacheInstructionDto>();
var count = database.ExecuteScalar<int>(sql);
//if there are instructions but we haven't synced, then a cold boot is necessary
if (count > 0)
_lastId = -1;
}
else
{
var sql = Sql().SelectAll()
.From<CacheInstructionDto>()
.Where<CacheInstructionDto>(dto => dto.Id == _lastId);
var dtos = database.Fetch<CacheInstructionDto>(sql);
//if the last synced instruction is not found in the db, then a cold boot is necessary
if (dtos.Count == 0)
_lastId = -1;
}
}
/// <summary>
/// Reads the last-synced id from file into memory.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void ReadLastSynced()
{
if (File.Exists(DistCacheFilePath) == false) return;
var content = File.ReadAllText(DistCacheFilePath);
if (int.TryParse(content, out var last))
_lastId = last;
}
/// <summary>
/// Updates the in-memory last-synced id and persists it to file.
/// </summary>
/// <param name="id">The id.</param>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void SaveLastSynced(int id)
{
File.WriteAllText(DistCacheFilePath, id.ToString(CultureInfo.InvariantCulture));
_lastId = id;
}
/// <summary>
/// Gets the unique local identity of the executing AppDomain.
/// </summary>
/// <remarks>
/// <para>It is not only about the "server" (machine name and appDomainappId), but also about
/// an AppDomain, within a Process, on that server - because two AppDomains running at the same
/// time on the same server (eg during a restart) are, practically, a LB setup.</para>
/// <para>Practically, all we really need is the guid, the other infos are here for information
/// and debugging purposes.</para>
/// </remarks>
protected static readonly string LocalIdentity = NetworkHelper.MachineName // eg DOMAIN\SERVER
+ "/" + HttpRuntime.AppDomainAppId // eg /LM/S3SVC/11/ROOT
+ " [P" + Process.GetCurrentProcess().Id // eg 1234
+ "/D" + AppDomain.CurrentDomain.Id // eg 22
+ "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique
private string GetDistCacheFilePath(IGlobalSettings globalSettings)
{
var fileName = HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt";
string distCacheFilePath;
switch (globalSettings.LocalTempStorageLocation)
{
case LocalTempStorage.AspNetTemp:
distCacheFilePath = Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData", fileName);
break;
case LocalTempStorage.EnvironmentTemp:
var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1();
var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData",
//include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back
// to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not
// utilizing an old path
appDomainHash);
distCacheFilePath = Path.Combine(cachePath, fileName);
break;
case LocalTempStorage.Default:
default:
var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/DistCache");
distCacheFilePath = Path.Combine(tempFolder, fileName);
break;
}
//ensure the folder exists
var folder = Path.GetDirectoryName(distCacheFilePath);
if (folder == null)
throw new InvalidOperationException("The folder could not be determined for the file " + distCacheFilePath);
if (Directory.Exists(folder) == false)
Directory.CreateDirectory(folder);
return distCacheFilePath;
}
#endregion
#region Notify refreshers
private static ICacheRefresher GetRefresher(Guid id)
{
var refresher = Current.CacheRefreshers[id];
if (refresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
return refresher;
}
private static IJsonCacheRefresher GetJsonRefresher(Guid id)
{
return GetJsonRefresher(GetRefresher(id));
}
private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
{
var jsonRefresher = refresher as IJsonCacheRefresher;
if (jsonRefresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + refresher.RefresherUniqueId + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
return jsonRefresher;
}
/// <summary>
/// Parses out the individual instructions to be processed
/// </summary>
/// <param name="jsonArray"></param>
/// <returns></returns>
private static List<RefreshInstruction> GetAllInstructions(IEnumerable<JToken> jsonArray)
{
var result = new List<RefreshInstruction>();
foreach (var jsonItem in jsonArray)
{
// could be a JObject in which case we can convert to a RefreshInstruction,
// otherwise it could be another JArray - in which case we'll iterate that.
var jsonObj = jsonItem as JObject;
if (jsonObj != null)
{
var instruction = jsonObj.ToObject<RefreshInstruction>();
result.Add(instruction);
}
else
{
var jsonInnerArray = (JArray)jsonItem;
result.AddRange(GetAllInstructions(jsonInnerArray)); // recurse
}
}
return result;
}
/// <summary>
/// executes the instructions against the cache refresher instances
/// </summary>
/// <param name="instructions"></param>
/// <param name="processed"></param>
/// <returns>
/// Returns true if all instructions were processed, otherwise false if the processing was interupted (i.e. app shutdown)
/// </returns>
private bool NotifyRefreshers(IEnumerable<RefreshInstruction> instructions, HashSet<RefreshInstruction> processed)
{
foreach (var instruction in instructions)
{
//Check if the app is shutting down, we need to exit if this happens.
if (_released)
{
return false;
}
//this has already been processed
if (processed.Contains(instruction))
continue;
switch (instruction.RefreshType)
{
case RefreshMethodType.RefreshAll:
RefreshAll(instruction.RefresherId);
break;
case RefreshMethodType.RefreshByGuid:
RefreshByGuid(instruction.RefresherId, instruction.GuidId);
break;
case RefreshMethodType.RefreshById:
RefreshById(instruction.RefresherId, instruction.IntId);
break;
case RefreshMethodType.RefreshByIds:
RefreshByIds(instruction.RefresherId, instruction.JsonIds);
break;
case RefreshMethodType.RefreshByJson:
RefreshByJson(instruction.RefresherId, instruction.JsonPayload);
break;
case RefreshMethodType.RemoveById:
RemoveById(instruction.RefresherId, instruction.IntId);
break;
}
processed.Add(instruction);
}
return true;
}
private static void RefreshAll(Guid uniqueIdentifier)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.RefreshAll();
}
private static void RefreshByGuid(Guid uniqueIdentifier, Guid id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds)
{
var refresher = GetRefresher(uniqueIdentifier);
foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds))
refresher.Refresh(id);
}
private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload)
{
var refresher = GetJsonRefresher(uniqueIdentifier);
refresher.Refresh(jsonPayload);
}
private static void RemoveById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Remove(id);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.MappingModel.Identity;
namespace FluentNHibernate.Conventions.Inspections
{
public class ClassInspector : IClassInspector
{
private readonly ClassMapping mapping;
private readonly InspectorModelMapper<IClassInspector, ClassMapping> propertyMappings = new InspectorModelMapper<IClassInspector, ClassMapping>();
public ClassInspector(ClassMapping mapping)
{
this.mapping = mapping;
propertyMappings.Map(x => x.LazyLoad, x => x.Lazy);
propertyMappings.Map(x => x.ReadOnly, x => x.Mutable);
propertyMappings.Map(x => x.EntityType, x => x.Type);
}
public Type EntityType
{
get { return mapping.Type; }
}
public string StringIdentifierForModel
{
get { return mapping.Name; }
}
public bool LazyLoad
{
get { return mapping.Lazy; }
}
public bool ReadOnly
{
get { return !mapping.Mutable; }
}
public string TableName
{
get { return mapping.TableName; }
}
ICacheInspector IClassInspector.Cache
{
get { return Cache; }
}
public ICacheInstance Cache
{
get
{
if (mapping.Cache == null)
// conventions are hitting it, user must want a cache
mapping.Set(x => x.Cache, Layer.Conventions, new CacheMapping());
return new CacheInstance(mapping.Cache);
}
}
public OptimisticLock OptimisticLock
{
get { return OptimisticLock.FromString(mapping.OptimisticLock); }
}
public SchemaAction SchemaAction
{
get { return SchemaAction.FromString(mapping.SchemaAction); }
}
public string Schema
{
get { return mapping.Schema; }
}
public bool DynamicUpdate
{
get { return mapping.DynamicUpdate; }
}
public bool DynamicInsert
{
get { return mapping.DynamicInsert; }
}
public int BatchSize
{
get { return mapping.BatchSize; }
}
public bool Abstract
{
get { return mapping.Abstract; }
}
public IVersionInspector Version
{
get
{
if (mapping.Version == null)
return new VersionInspector(new VersionMapping());
return new VersionInspector(mapping.Version);
}
}
public IEnumerable<IAnyInspector> Anys
{
get
{
return mapping.Anys
.Select(x => new AnyInspector(x))
.Cast<IAnyInspector>();
}
}
public string Check
{
get { return mapping.Check; }
}
public IEnumerable<ICollectionInspector> Collections
{
get
{
return mapping.Collections
.Select(x => new CollectionInspector(x))
.Cast<ICollectionInspector>();
}
}
public IEnumerable<IComponentBaseInspector> Components
{
get
{
return mapping.Components
.Select(x =>
{
if (x.ComponentType == ComponentType.Component)
return (IComponentBaseInspector)new ComponentInspector((ComponentMapping)x);
return (IComponentBaseInspector)new DynamicComponentInspector((ComponentMapping)x);
});
}
}
public IEnumerable<IJoinInspector> Joins
{
get
{
return mapping.Joins
.Select(x => new JoinInspector(x))
.Cast<IJoinInspector>();
}
}
public IEnumerable<IOneToOneInspector> OneToOnes
{
get
{
return mapping.OneToOnes
.Select(x => new OneToOneInspector(x))
.Cast<IOneToOneInspector>();
}
}
public IEnumerable<IPropertyInspector> Properties
{
get
{
return mapping.Properties
.Select(x => new PropertyInspector(x))
.Cast<IPropertyInspector>();
}
}
public IEnumerable<IManyToOneInspector> References
{
get
{
return mapping.References
.Select(x => new ManyToOneInspector(x))
.Cast<IManyToOneInspector>();
}
}
public IEnumerable<ISubclassInspectorBase> Subclasses
{
get
{
return mapping.Subclasses
.Where(x => x.SubclassType == SubclassType.Subclass)
.Select(x => (ISubclassInspectorBase)new SubclassInspector(x));
}
}
public IDiscriminatorInspector Discriminator
{
get
{
if (mapping.Discriminator == null)
// deliberately empty so nothing evaluates to true
return new DiscriminatorInspector(new DiscriminatorMapping());
return new DiscriminatorInspector(mapping.Discriminator);
}
}
public object DiscriminatorValue
{
get { return mapping.DiscriminatorValue; }
}
public string Name
{
get { return mapping.Name; }
}
public string Persister
{
get { return mapping.Persister; }
}
public Polymorphism Polymorphism
{
get { return Polymorphism.FromString(mapping.Polymorphism); }
}
public string Proxy
{
get { return mapping.Proxy; }
}
public string Where
{
get { return mapping.Where; }
}
public string Subselect
{
get { return mapping.Subselect; }
}
public bool SelectBeforeUpdate
{
get { return mapping.SelectBeforeUpdate; }
}
public IIdentityInspectorBase Id
{
get
{
if (mapping.Id == null)
return new IdentityInspector(new IdMapping());
if (mapping.Id is CompositeIdMapping)
return new CompositeIdentityInspector((CompositeIdMapping)mapping.Id);
return new IdentityInspector((IdMapping)mapping.Id);
}
}
public bool IsSet(Member property)
{
return mapping.IsSpecified(propertyMappings.Get(property));
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using 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>
/// ExpressRouteServiceProvidersOperations operations.
/// </summary>
internal partial class ExpressRouteServiceProvidersOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteServiceProvidersOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteServiceProvidersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ExpressRouteServiceProvidersOperations(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>
/// Gets all the available express route service providers.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteServiceProvider>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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<ExpressRouteServiceProvider>>();
_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<ExpressRouteServiceProvider>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the available express route service providers.
/// </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<ExpressRouteServiceProvider>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.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<ExpressRouteServiceProvider>>();
_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<ExpressRouteServiceProvider>>(_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;
}
}
}
| |
namespace Sharpen
{
using System;
public class ByteBuffer
{
private byte[] buffer;
private DataConverter c;
private int capacity;
private int index;
private int limit;
private int mark;
private int offset;
private ByteOrder order;
public ByteBuffer ()
{
this.c = DataConverter.BigEndian;
}
private ByteBuffer (byte[] buf, int start, int len)
{
this.buffer = buf;
this.offset = 0;
this.limit = start + len;
this.index = start;
this.mark = start;
this.capacity = buf.Length;
this.c = DataConverter.BigEndian;
}
public static ByteBuffer Allocate (int size)
{
return new ByteBuffer (new byte[size], 0, size);
}
public static ByteBuffer AllocateDirect (int size)
{
return Allocate (size);
}
public byte[] Array ()
{
return buffer;
}
public int ArrayOffset ()
{
return offset;
}
public int Capacity ()
{
return capacity;
}
private void CheckGetLimit (int inc)
{
if ((index + inc) > limit) {
throw new BufferUnderflowException ();
}
}
private void CheckPutLimit (int inc)
{
if ((index + inc) > limit) {
throw new BufferUnderflowException ();
}
}
public void Clear ()
{
index = offset;
limit = offset + capacity;
}
public void Flip ()
{
limit = index;
index = offset;
}
public byte Get ()
{
CheckGetLimit (1);
return buffer[index++];
}
public void Get (byte[] data)
{
Get (data, 0, data.Length);
}
public void Get (byte[] data, int start, int len)
{
CheckGetLimit (len);
for (int i = 0; i < len; i++) {
data[i + start] = buffer[index++];
}
}
public int GetInt ()
{
CheckGetLimit (4);
int num = c.GetInt32 (buffer, index);
index += 4;
return num;
}
public short GetShort ()
{
CheckGetLimit (2);
short num = c.GetInt16 (buffer, index);
index += 2;
return num;
}
public bool HasArray ()
{
return true;
}
public int Limit ()
{
return (limit - offset);
}
public void Limit (int newLimit)
{
limit = newLimit;
}
public void Mark ()
{
mark = index;
}
public void Order (ByteOrder order)
{
this.order = order;
if (order == ByteOrder.BIG_ENDIAN) {
c = DataConverter.BigEndian;
} else {
c = DataConverter.LittleEndian;
}
}
public int Position ()
{
return (index - offset);
}
public void Position (int pos)
{
if ((pos < offset) || (pos > limit)) {
throw new BufferUnderflowException ();
}
index = pos + offset;
}
public void Put (byte[] data)
{
Put (data, 0, data.Length);
}
public void Put (byte data)
{
CheckPutLimit (1);
buffer[index++] = data;
}
public void Put (byte[] data, int start, int len)
{
CheckPutLimit (len);
for (int i = 0; i < len; i++) {
buffer[index++] = data[i + start];
}
}
public void PutInt (int i)
{
Put (c.GetBytes (i));
}
public void PutShort (short i)
{
Put (c.GetBytes (i));
}
public int Remaining ()
{
return (limit - index);
}
public void Reset ()
{
index = mark;
}
public ByteBuffer Slice ()
{
ByteBuffer b = Wrap (buffer, index, buffer.Length - index);
b.offset = index;
b.limit = limit;
b.order = order;
b.c = c;
b.capacity = limit - index;
return b;
}
public static ByteBuffer Wrap (byte[] buf)
{
return new ByteBuffer (buf, 0, buf.Length);
}
public static ByteBuffer Wrap (byte[] buf, int start, int len)
{
return new ByteBuffer (buf, start, len);
}
}
}
| |
// Copyright 2016 Tom Deseyn <tom.deseyn@gmail.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Tmds.DBus.CodeGen;
using Tmds.DBus.Protocol;
namespace Tmds.DBus
{
/// <summary>
/// Connection with a D-Bus peer.
/// </summary>
public class Connection : IConnection
{
[Flags]
private enum ConnectionType
{
None = 0,
ClientManual = 1,
ClientAutoConnect = 2,
Server = 4
}
/// <summary>
/// Assembly name where the dynamically generated code resides.
/// </summary>
public const string DynamicAssemblyName = "Tmds.DBus.Emit, PublicKey=002400000480000094000000060200000024000052534131000400000100010071a8770f460cce31df0feb6f94b328aebd55bffeb5c69504593df097fdd9b29586dbd155419031834411c8919516cc565dee6b813c033676218496edcbe7939c0dd1f919f3d1a228ebe83b05a3bbdbae53ce11bcf4c04a42d8df1a83c2d06cb4ebb0b447e3963f48a1ca968996f3f0db8ab0e840a89d0a5d5a237e2f09189ed3";
private static Connection s_systemConnection;
private static Connection s_sessionConnection;
private static readonly object NoDispose = new object();
/// <summary>
/// An AutoConnect Connection to the system bus.
/// </summary>
public static Connection System => s_systemConnection ?? CreateSystemConnection();
/// <summary>
/// An AutoConnect Connection to the session bus.
/// </summary>
public static Connection Session => s_sessionConnection ?? CreateSessionConnection();
private class ProxyFactory : IProxyFactory
{
public Connection Connection { get; }
public ProxyFactory(Connection connection)
{
Connection = connection;
}
public T CreateProxy<T>(string serviceName, ObjectPath path)
{
return Connection.CreateProxy<T>(serviceName, path);
}
}
private readonly object _gate = new object();
private readonly Dictionary<ObjectPath, DBusAdapter> _registeredObjects = new Dictionary<ObjectPath, DBusAdapter>();
private readonly Func<Task<ClientSetupResult>> _connectFunction;
private readonly Action<object> _disposeAction;
private readonly SynchronizationContext _synchronizationContext;
private readonly bool _runContinuationsAsynchronously;
private readonly ConnectionType _connectionType;
private ConnectionState _state = ConnectionState.Created;
private bool _disposed = false;
private IProxyFactory _factory;
private DBusConnection _dbusConnection;
private Task<DBusConnection> _dbusConnectionTask;
private TaskCompletionSource<DBusConnection> _dbusConnectionTcs;
private CancellationTokenSource _connectCts;
private Exception _disconnectReason;
private IDBus _bus;
private EventHandler<ConnectionStateChangedEventArgs> _stateChangedEvent;
private object _disposeUserToken = NoDispose;
private IDBus DBus
{
get
{
if (_bus != null)
{
return _bus;
}
lock (_gate)
{
_bus = _bus ?? CreateProxy<IDBus>(DBusConnection.DBusServiceName, DBusConnection.DBusObjectPath);
return _bus;
}
}
}
/// <summary>
/// Occurs when the state changes.
/// </summary>
/// <remarks>
/// The event handler will be called when it is added to the event.
/// The event handler is invoked on the ConnectionOptions.SynchronizationContext.
/// </remarks>
public event EventHandler<ConnectionStateChangedEventArgs> StateChanged
{
add
{
lock (_gate)
{
_stateChangedEvent += value;
if (_state != ConnectionState.Created)
{
EmitConnectionStateChanged(value);
}
}
}
remove
{
lock (_gate)
{
_stateChangedEvent -= value;
}
}
}
/// <summary>
/// Creates a new Connection with a specific address.
/// </summary>
/// <param name="address">Address of the D-Bus peer.</param>
public Connection(string address) :
this(new ClientConnectionOptions(address))
{ }
/// <summary>
/// Creates a new Connection with specific ConnectionOptions.
/// </summary>
/// <param name="connectionOptions"></param>
public Connection(ConnectionOptions connectionOptions)
{
if (connectionOptions == null)
throw new ArgumentNullException(nameof(connectionOptions));
_factory = new ProxyFactory(this);
_synchronizationContext = connectionOptions.SynchronizationContext;
if (connectionOptions is ClientConnectionOptions clientConnectionOptions)
{
_connectionType = clientConnectionOptions.AutoConnect ? ConnectionType.ClientAutoConnect : ConnectionType.ClientManual ;
_connectFunction = clientConnectionOptions.SetupAsync;
_disposeAction = clientConnectionOptions.Teardown;
_runContinuationsAsynchronously = clientConnectionOptions.RunContinuationsAsynchronously;
}
else if (connectionOptions is ServerConnectionOptions serverConnectionOptions)
{
_connectionType = ConnectionType.Server;
_state = ConnectionState.Connected;
_dbusConnection = new DBusConnection(localServer: true, runContinuationsAsynchronously: false);
_dbusConnectionTask = Task.FromResult(_dbusConnection);
serverConnectionOptions.Connection = this;
}
else
{
throw new NotSupportedException($"Unknown ConnectionOptions type: '{typeof(ConnectionOptions).FullName}'");
}
}
/// <summary>
/// Connect with the remote peer.
/// </summary>
/// <returns>
/// Information about the established connection.
/// </returns>
/// <exception cref="ConnectException">There was an error establishing the connection.</exception>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
public async Task<ConnectionInfo> ConnectAsync()
=> (await DoConnectAsync().ConfigureAwait(false)).ConnectionInfo;
private async Task<DBusConnection> DoConnectAsync()
{
Task<DBusConnection> connectionTask = null;
bool alreadyConnecting = false;
lock (_gate)
{
if (_disposed)
{
ThrowDisposed();
}
if (_connectionType == ConnectionType.ClientManual)
{
if (_state != ConnectionState.Created)
{
throw new InvalidOperationException("Can only connect once");
}
}
else
{
if (_state == ConnectionState.Connecting || _state == ConnectionState.Connected)
{
connectionTask = _dbusConnectionTask;
alreadyConnecting = true;
}
}
if (!alreadyConnecting)
{
_connectCts = new CancellationTokenSource();
_dbusConnectionTcs = new TaskCompletionSource<DBusConnection>();
_dbusConnectionTask = _dbusConnectionTcs.Task;
connectionTask = _dbusConnectionTask;
_state = ConnectionState.Connecting;
EmitConnectionStateChanged();
}
}
if (alreadyConnecting)
{
return await connectionTask.ConfigureAwait(false);
}
DBusConnection connection;
object disposeUserToken = NoDispose;
try
{
ClientSetupResult connectionContext = await _connectFunction().ConfigureAwait(false);
disposeUserToken = connectionContext.TeardownToken;
connection = await DBusConnection.ConnectAsync(connectionContext, _runContinuationsAsynchronously, OnDisconnect, _connectCts.Token).ConfigureAwait(false);
}
catch (ConnectException ce)
{
if (disposeUserToken != NoDispose)
{
_disposeAction?.Invoke(disposeUserToken);
}
Disconnect(dispose: false, exception: ce);
throw;
}
catch (Exception e)
{
if (disposeUserToken != NoDispose)
{
_disposeAction?.Invoke(disposeUserToken);
}
var ce = new ConnectException(e.Message, e);
Disconnect(dispose: false, exception: ce);
throw ce;
}
lock (_gate)
{
if (_state == ConnectionState.Connecting)
{
_disposeUserToken = disposeUserToken;
_dbusConnection = connection;
_connectCts.Dispose();
_connectCts = null;
_state = ConnectionState.Connected;
_dbusConnectionTcs.SetResult(connection);
_dbusConnectionTcs = null;
EmitConnectionStateChanged();
}
else
{
connection.Dispose();
if (disposeUserToken != NoDispose)
{
_disposeAction?.Invoke(disposeUserToken);
}
}
ThrowIfNotConnected();
}
return connection;
}
/// <summary>
/// Disposes the connection.
/// </summary>
public void Dispose()
{
Disconnect(dispose: true, exception: CreateDisposedException());
}
/// <summary>
/// Creates a proxy object that represents a remote D-Bus object.
/// </summary>
/// <typeparam name="T">Interface of the D-Bus object.</typeparam>
/// <param name="serviceName">Name of the service that exposes the object.</param>
/// <param name="path">Object path of the object.</param>
/// <returns>
/// Proxy object.
/// </returns>
public T CreateProxy<T>(string serviceName, ObjectPath path)
{
CheckNotConnectionType(ConnectionType.Server);
return (T)CreateProxy(typeof(T), serviceName, path);
}
/// <summary>
/// Releases a service name assigned to the connection.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <returns>
/// <c>true</c> when the name was assigned to this connection; <c>false</c> when the name was not assigned to this connection.
/// </returns>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
/// <exception cref="DBusException">Error returned by remote peer.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public async Task<bool> UnregisterServiceAsync(string serviceName)
{
CheckNotConnectionType(ConnectionType.ClientAutoConnect);
var connection = GetConnectedConnection();
var reply = await connection.ReleaseNameAsync(serviceName).ConfigureAwait(false);
return reply == ReleaseNameReply.ReplyReleased;
}
/// <summary>
/// Queues a service name registration for the connection.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <param name="onAquired">Action invoked when the service name is assigned to the connection.</param>
/// <param name="onLost">Action invoked when the service name is no longer assigned to the connection.</param>
/// <param name="options">Options for the registration.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
/// <exception cref="DBusException">Error returned by remote peer.</exception>
/// <exception cref="ProtocolException">Unexpected reply.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public async Task QueueServiceRegistrationAsync(string serviceName, Action onAquired = null, Action onLost = null, ServiceRegistrationOptions options = ServiceRegistrationOptions.Default)
{
CheckNotConnectionType(ConnectionType.ClientAutoConnect);
var connection = GetConnectedConnection();
if (!options.HasFlag(ServiceRegistrationOptions.AllowReplacement) && (onLost != null))
{
throw new ArgumentException($"{nameof(onLost)} can only be set when {nameof(ServiceRegistrationOptions.AllowReplacement)} is also set", nameof(onLost));
}
RequestNameOptions requestOptions = RequestNameOptions.None;
if (options.HasFlag(ServiceRegistrationOptions.ReplaceExisting))
{
requestOptions |= RequestNameOptions.ReplaceExisting;
}
if (options.HasFlag(ServiceRegistrationOptions.AllowReplacement))
{
requestOptions |= RequestNameOptions.AllowReplacement;
}
var reply = await connection.RequestNameAsync(serviceName, requestOptions, onAquired, onLost, CaptureSynchronizationContext()).ConfigureAwait(false);
switch (reply)
{
case RequestNameReply.PrimaryOwner:
case RequestNameReply.InQueue:
return;
case RequestNameReply.Exists:
case RequestNameReply.AlreadyOwner:
default:
throw new ProtocolException("Unexpected reply");
}
}
/// <summary>
/// Queues a service name registration for the connection.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <param name="options">Options for the registration.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
/// <exception cref="DBusException">Error returned by remote peer.</exception>
/// <exception cref="ProtocolException">Unexpected reply.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public Task QueueServiceRegistrationAsync(string serviceName, ServiceRegistrationOptions options)
=> QueueServiceRegistrationAsync(serviceName, null, null, options);
/// <summary>
/// Requests a service name to be assigned to the connection.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <param name="onLost">Action invoked when the service name is no longer assigned to the connection.</param>
/// <param name="options"></param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
/// <exception cref="DBusException">Error returned by remote peer.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public async Task RegisterServiceAsync(string serviceName, Action onLost = null, ServiceRegistrationOptions options = ServiceRegistrationOptions.Default)
{
CheckNotConnectionType(ConnectionType.ClientAutoConnect);
var connection = GetConnectedConnection();
if (!options.HasFlag(ServiceRegistrationOptions.AllowReplacement) && (onLost != null))
{
throw new ArgumentException($"{nameof(onLost)} can only be set when {nameof(ServiceRegistrationOptions.AllowReplacement)} is also set", nameof(onLost));
}
RequestNameOptions requestOptions = RequestNameOptions.DoNotQueue;
if (options.HasFlag(ServiceRegistrationOptions.ReplaceExisting))
{
requestOptions |= RequestNameOptions.ReplaceExisting;
}
if (options.HasFlag(ServiceRegistrationOptions.AllowReplacement))
{
requestOptions |= RequestNameOptions.AllowReplacement;
}
var reply = await connection.RequestNameAsync(serviceName, requestOptions, null, onLost, CaptureSynchronizationContext()).ConfigureAwait(false);
switch (reply)
{
case RequestNameReply.PrimaryOwner:
return;
case RequestNameReply.Exists:
throw new InvalidOperationException("Service is registered by another connection");
case RequestNameReply.AlreadyOwner:
throw new InvalidOperationException("Service is already registered by this connection");
case RequestNameReply.InQueue:
default:
throw new ProtocolException("Unexpected reply");
}
}
/// <summary>
/// Requests a service name to be assigned to the connection.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <param name="options"></param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
/// <exception cref="DBusException">Error returned by remote peer.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public Task RegisterServiceAsync(string serviceName, ServiceRegistrationOptions options)
=> RegisterServiceAsync(serviceName, null, options);
/// <summary>
/// Publishes an object.
/// </summary>
/// <param name="o">Object to publish.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed.</exception>
public Task RegisterObjectAsync(IDBusObject o)
{
return RegisterObjectsAsync(new[] { o });
}
/// <summary>
/// Publishes objects.
/// </summary>
/// <param name="objects">Objects to publish.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection was closed.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public async Task RegisterObjectsAsync(IEnumerable<IDBusObject> objects)
{
CheckNotConnectionType(ConnectionType.ClientAutoConnect);
var connection = GetConnectedConnection();
var assembly = DynamicAssembly.Instance;
var registrations = new List<DBusAdapter>();
foreach (var o in objects)
{
var implementationType = assembly.GetExportTypeInfo(o.GetType());
var objectPath = o.ObjectPath;
var registration = (DBusAdapter)Activator.CreateInstance(implementationType.AsType(), _dbusConnection, objectPath, o, _factory, CaptureSynchronizationContext());
registrations.Add(registration);
}
lock (_gate)
{
connection.AddMethodHandlers(registrations.Select(r => new KeyValuePair<ObjectPath, MethodHandler>(r.Path, r.HandleMethodCall)));
foreach (var registration in registrations)
{
_registeredObjects.Add(registration.Path, registration);
}
}
try
{
foreach (var registration in registrations)
{
await registration.WatchSignalsAsync().ConfigureAwait(false);
}
lock (_gate)
{
foreach (var registration in registrations)
{
registration.CompleteRegistration();
}
}
}
catch
{
lock (_gate)
{
foreach (var registration in registrations)
{
registration.Unregister();
_registeredObjects.Remove(registration.Path);
}
connection.RemoveMethodHandlers(registrations.Select(r => r.Path));
}
throw;
}
}
/// <summary>
/// Unpublishes an object.
/// </summary>
/// <param name="path">Path of object to unpublish.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
public void UnregisterObject(ObjectPath path)
=> UnregisterObjects(new[] { path });
/// <summary>
/// Unpublishes an object.
/// </summary>
/// <param name="o">object to unpublish.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
public void UnregisterObject(IDBusObject o)
=> UnregisterObject(o.ObjectPath);
/// <summary>
/// Unpublishes objects.
/// </summary>
/// <param name="paths">Paths of objects to unpublish.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public void UnregisterObjects(IEnumerable<ObjectPath> paths)
{
CheckNotConnectionType(ConnectionType.ClientAutoConnect);
lock (_gate)
{
var connection = GetConnectedConnection();
foreach(var objectPath in paths)
{
DBusAdapter registration;
if (_registeredObjects.TryGetValue(objectPath, out registration))
{
registration.Unregister();
_registeredObjects.Remove(objectPath);
}
}
connection.RemoveMethodHandlers(paths);
}
}
/// <summary>
/// Unpublishes objects.
/// </summary>
/// <param name="objects">Objects to unpublish.</param>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
/// <remarks>
/// This operation is not supported for AutoConnection connections.
/// </remarks>
public void UnregisterObjects(IEnumerable<IDBusObject> objects)
=> UnregisterObjects(objects.Select(o => o.ObjectPath));
/// <summary>
/// List services that can be activated.
/// </summary>
/// <returns>
/// List of activatable services.
/// </returns>
/// <exception cref="ConnectException">There was an error establishing the connection.</exception>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
public Task<string[]> ListActivatableServicesAsync()
=> DBus.ListActivatableNamesAsync();
/// <summary>
/// Resolves the local address for a service.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <returns>
/// Local address of service. <c>null</c> is returned when the service name is not available.
/// </returns>
/// <exception cref="ConnectException">There was an error establishing the connection.</exception>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
public async Task<string> ResolveServiceOwnerAsync(string serviceName)
{
try
{
return await DBus.GetNameOwnerAsync(serviceName).ConfigureAwait(false);
}
catch (DBusException e) when (e.ErrorName == "org.freedesktop.DBus.Error.NameHasNoOwner")
{
return null;
}
catch
{
throw;
}
}
/// <summary>
/// Activates a service.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <returns>
/// The result of the activation.
/// </returns>
/// <exception cref="ConnectException">There was an error establishing the connection.</exception>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
public Task<ServiceStartResult> ActivateServiceAsync(string serviceName)
=> DBus.StartServiceByNameAsync(serviceName, 0);
/// <summary>
/// Checks if a service is available.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <returns>
/// <c>true</c> when the service is available, <c>false</c> otherwise.
/// </returns>
/// <exception cref="ConnectException">There was an error establishing the connection.</exception>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
public Task<bool> IsServiceActiveAsync(string serviceName)
=> DBus.NameHasOwnerAsync(serviceName);
/// <summary>
/// Resolves the local address for a service.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <param name="handler">Action invoked when the local name of the service changes.</param>
/// <param name="onError">Action invoked when the connection closes.</param>
/// <returns>
/// Disposable that allows to stop receiving notifications.
/// </returns>
/// <exception cref="ConnectException">There was an error establishing the connection.</exception>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
/// <remarks>
/// The event handler will be called when the service name is already registered.
/// </remarks>
public async Task<IDisposable> ResolveServiceOwnerAsync(string serviceName, Action<ServiceOwnerChangedEventArgs> handler, Action<Exception> onError = null)
{
if (serviceName == "*")
{
serviceName = ".*";
}
var synchronizationContext = CaptureSynchronizationContext();
var wrappedDisposable = new WrappedDisposable(synchronizationContext);
bool namespaceLookup = serviceName.EndsWith(".*", StringComparison.Ordinal);
bool _eventEmitted = false;
var _gate = new object();
var _emittedServices = namespaceLookup ? new List<string>() : null;
Action<ServiceOwnerChangedEventArgs, Exception> handleEvent = (ownerChange, ex) => {
if (ex != null)
{
if (onError == null)
{
return;
}
wrappedDisposable.Call(onError, ex, disposes: true);
return;
}
bool first = false;
lock (_gate)
{
if (namespaceLookup)
{
first = _emittedServices?.Contains(ownerChange.ServiceName) == false;
_emittedServices?.Add(ownerChange.ServiceName);
}
else
{
first = _eventEmitted == false;
_eventEmitted = true;
}
}
if (first)
{
if (ownerChange.NewOwner == null)
{
return;
}
ownerChange.OldOwner = null;
}
wrappedDisposable.Call(handler, ownerChange);
};
var connection = await GetConnectionTask().ConfigureAwait(false);
wrappedDisposable.Disposable = await connection.WatchNameOwnerChangedAsync(serviceName, handleEvent).ConfigureAwait(false);
if (namespaceLookup)
{
serviceName = serviceName.Substring(0, serviceName.Length - 2);
}
try
{
if (namespaceLookup)
{
var services = await ListServicesAsync().ConfigureAwait(false);
foreach (var service in services)
{
if (service.StartsWith(serviceName, StringComparison.Ordinal)
&& ( (service.Length == serviceName.Length)
|| (service[serviceName.Length] == '.')
|| (serviceName.Length == 0 && service[0] != ':')))
{
var currentName = await ResolveServiceOwnerAsync(service).ConfigureAwait(false);
lock (_gate)
{
if (currentName != null && !_emittedServices.Contains(serviceName))
{
var e = new ServiceOwnerChangedEventArgs(service, null, currentName);
handleEvent(e, null);
}
}
}
}
lock (_gate)
{
_emittedServices = null;
}
}
else
{
var currentName = await ResolveServiceOwnerAsync(serviceName).ConfigureAwait(false);
lock (_gate)
{
if (currentName != null && !_eventEmitted)
{
var e = new ServiceOwnerChangedEventArgs(serviceName, null, currentName);
handleEvent(e, null);
}
}
}
return wrappedDisposable;
}
catch (Exception ex)
{
handleEvent(default(ServiceOwnerChangedEventArgs), ex);
}
return wrappedDisposable;
}
/// <summary>
/// List services that are available.
/// </summary>
/// <returns>
/// List of available services.
/// </returns>
/// <exception cref="ConnectException">There was an error establishing the connection.</exception>
/// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
/// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
/// <exception cref="DisconnectedException">The connection is closed.</exception>
public Task<string[]> ListServicesAsync()
=> DBus.ListNamesAsync();
internal Task<string> StartServerAsync(string address)
{
lock (_gate)
{
ThrowIfNotConnected();
return _dbusConnection.StartServerAsync(address);
}
}
// Used by tests
internal void Connect(DBusConnection dbusConnection)
{
lock (_gate)
{
if (_state != ConnectionState.Created)
{
throw new InvalidOperationException("Can only connect once");
}
_dbusConnection = dbusConnection;
_dbusConnectionTask = Task.FromResult(_dbusConnection);
_state = ConnectionState.Connected;
}
}
private object CreateProxy(Type interfaceType, string busName, ObjectPath path)
{
var assembly = DynamicAssembly.Instance;
var implementationType = assembly.GetProxyTypeInfo(interfaceType);
DBusObjectProxy instance = (DBusObjectProxy)Activator.CreateInstance(implementationType.AsType(),
new object[] { this, _factory, busName, path });
return instance;
}
private void OnDisconnect(Exception e)
{
Disconnect(dispose: false, exception: e);
}
private void ThrowIfNotConnected()
=> ThrowIfNotConnected(_disposed, _state, _disconnectReason);
internal static void ThrowIfNotConnected(bool disposed, ConnectionState state, Exception disconnectReason)
{
if (disposed)
{
ThrowDisposed();
}
if (state == ConnectionState.Disconnected)
{
throw new DisconnectedException(disconnectReason);
}
else if (state == ConnectionState.Created)
{
throw new InvalidOperationException("Not Connected");
}
else if (state == ConnectionState.Connecting)
{
throw new InvalidOperationException("Connecting");
}
}
internal static Exception CreateDisposedException()
=> new ObjectDisposedException(typeof(Connection).FullName);
private static void ThrowDisposed()
{
throw CreateDisposedException();
}
internal static void ThrowIfNotConnecting(bool disposed, ConnectionState state, Exception disconnectReason)
{
if (disposed)
{
ThrowDisposed();
}
if (state == ConnectionState.Disconnected)
{
throw new DisconnectedException(disconnectReason);
}
else if (state == ConnectionState.Created)
{
throw new InvalidOperationException("Not Connected");
}
else if (state == ConnectionState.Connected)
{
throw new InvalidOperationException("Already Connected");
}
}
private Task<DBusConnection> GetConnectionTask()
{
var connectionTask = Volatile.Read(ref _dbusConnectionTask);
if (connectionTask != null)
{
return connectionTask;
}
if (_connectionType == ConnectionType.ClientAutoConnect)
{
return DoConnectAsync();
}
else
{
return Task.FromResult(GetConnectedConnection());
}
}
private DBusConnection GetConnectedConnection()
{
var connection = Volatile.Read(ref _dbusConnection);
if (connection != null)
{
return connection;
}
lock (_gate)
{
ThrowIfNotConnected();
return _dbusConnection;
}
}
private void CheckNotConnectionType(ConnectionType disallowed)
{
if ((_connectionType & disallowed) != ConnectionType.None)
{
if (_connectionType == ConnectionType.ClientAutoConnect)
{
throw new InvalidOperationException($"Operation not supported for {nameof(ClientConnectionOptions.AutoConnect)} Connection.");
}
else if (_connectionType == ConnectionType.Server)
{
throw new InvalidOperationException($"Operation not supported for Server-based Connection.");
}
}
}
private void Disconnect(bool dispose, Exception exception)
{
lock (_gate)
{
if (dispose)
{
_disposed = true;
}
var previousState = _state;
if (previousState == ConnectionState.Disconnecting || previousState == ConnectionState.Disconnected || previousState == ConnectionState.Created)
{
return;
}
_disconnectReason = exception;
var connection = _dbusConnection;
var connectionCts = _connectCts;;
var dbusConnectionTask = _dbusConnectionTask;
var dbusConnectionTcs = _dbusConnectionTcs;
var disposeUserToken = _disposeUserToken;
_dbusConnection = null;
_connectCts = null;
_dbusConnectionTask = null;
_dbusConnectionTcs = null;
_disposeUserToken = NoDispose;
foreach (var registeredObject in _registeredObjects)
{
registeredObject.Value.Unregister();
}
_registeredObjects.Clear();
_state = ConnectionState.Disconnecting;
EmitConnectionStateChanged();
connectionCts?.Cancel();
connectionCts?.Dispose();
dbusConnectionTcs?.SetException(
dispose ? CreateDisposedException() :
exception.GetType() == typeof(ConnectException) ? exception :
new DisconnectedException(exception));
connection?.Disconnect(dispose, exception);
if (disposeUserToken != NoDispose)
{
_disposeAction?.Invoke(disposeUserToken);
}
if (_state == ConnectionState.Disconnecting)
{
_state = ConnectionState.Disconnected;
EmitConnectionStateChanged();
}
}
}
private void EmitConnectionStateChanged(EventHandler<ConnectionStateChangedEventArgs> handler = null)
{
var disconnectReason = _disconnectReason;
if (_state == ConnectionState.Connecting)
{
_disconnectReason = null;
}
if (handler == null)
{
handler = _stateChangedEvent;
}
if (handler == null)
{
return;
}
if (disconnectReason != null
&& disconnectReason.GetType() != typeof(ConnectException)
&& disconnectReason.GetType() != typeof(ObjectDisposedException)
&& disconnectReason.GetType() != typeof(DisconnectedException))
{
disconnectReason = new DisconnectedException(disconnectReason);
}
var connectionInfo = _state == ConnectionState.Connected ? _dbusConnection.ConnectionInfo : null;
var stateChangeEvent = new ConnectionStateChangedEventArgs(_state, disconnectReason, connectionInfo);
if (_synchronizationContext != null && SynchronizationContext.Current != _synchronizationContext)
{
_synchronizationContext.Post(_ => handler(this, stateChangeEvent), null);
}
else
{
handler(this, stateChangeEvent);
}
}
internal async Task<Message> CallMethodAsync(Message message)
{
var connection = await GetConnectionTask().ConfigureAwait(false);
try
{
return await connection.CallMethodAsync(message).ConfigureAwait(false);
}
catch (DisconnectedException) when (_connectionType == ConnectionType.ClientAutoConnect)
{
connection = await GetConnectionTask().ConfigureAwait(false);
return await connection.CallMethodAsync(message).ConfigureAwait(false);
}
}
internal async Task<IDisposable> WatchSignalAsync(ObjectPath path, string @interface, string signalName, SignalHandler handler)
{
var connection = await GetConnectionTask().ConfigureAwait(false);
try
{
return await connection.WatchSignalAsync(path, @interface, signalName, handler).ConfigureAwait(false);
}
catch (DisconnectedException) when (_connectionType == ConnectionType.ClientAutoConnect)
{
connection = await GetConnectionTask().ConfigureAwait(false);
return await connection.WatchSignalAsync(path, @interface, signalName, handler).ConfigureAwait(false);
}
}
internal SynchronizationContext CaptureSynchronizationContext() => _synchronizationContext;
private static Connection CreateSessionConnection() => CreateConnection(Address.Session, ref s_sessionConnection);
private static Connection CreateSystemConnection() => CreateConnection(Address.System, ref s_systemConnection);
private static Connection CreateConnection(string address, ref Connection connection)
{
address = address ?? "unix:";
if (Volatile.Read(ref connection) != null)
{
return connection;
}
var newConnection = new Connection(new ClientConnectionOptions(address) { AutoConnect = true, SynchronizationContext = null });
Interlocked.CompareExchange(ref connection, newConnection, null);
return connection;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.IO;
using System.Reflection;
using Grpc.Core.Logging;
namespace Grpc.Core.Internal
{
/// <summary>
/// Takes care of loading C# native extension and provides access to PInvoke calls the library exports.
/// </summary>
internal sealed class NativeExtension
{
// Enviroment variable can be used to force loading the native extension from given location.
private const string CsharpExtOverrideLocationEnvVarName = "GRPC_CSHARP_EXT_OVERRIDE_LOCATION";
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<NativeExtension>();
static readonly object staticLock = new object();
static volatile NativeExtension instance;
readonly NativeMethods nativeMethods;
private NativeExtension()
{
this.nativeMethods = LoadNativeMethods();
// Redirect the native logs as the very first thing after loading the native extension
// to make sure we don't lose any logs.
NativeLogRedirector.Redirect(this.nativeMethods);
// Initialize
NativeCallbackDispatcher.Init(this.nativeMethods);
DefaultSslRootsOverride.Override(this.nativeMethods);
Logger.Debug("gRPC native library loaded successfully.");
}
/// <summary>
/// Gets singleton instance of this class.
/// The native extension is loaded when called for the first time.
/// </summary>
public static NativeExtension Get()
{
if (instance == null)
{
lock (staticLock)
{
if (instance == null) {
instance = new NativeExtension();
}
}
}
return instance;
}
/// <summary>
/// Provides access to the exported native methods.
/// </summary>
public NativeMethods NativeMethods
{
get { return this.nativeMethods; }
}
/// <summary>
/// Detects which configuration of native extension to load and explicitly loads the dynamic library.
/// The explicit load makes sure that we can detect any loading problems early on.
/// </summary>
private static NativeMethods LoadNativeMethodsUsingExplicitLoad()
{
// NOTE: a side effect of searching the native extension's library file relatively to the assembly location is that when Grpc.Core assembly
// is loaded via reflection from a different app's context, the native extension is still loaded correctly
// (while if we used [DllImport], the native extension won't be on the other app's search path for shared libraries).
var assemblyDirectory = GetAssemblyDirectory();
// With "classic" VS projects, the native libraries get copied using a .targets rule to the build output folder
// alongside the compiled assembly.
// With dotnet SDK projects targeting net45 framework, the native libraries (just the required ones)
// are similarly copied to the built output folder, through the magic of Microsoft.NETCore.Platforms.
var classicPath = Path.Combine(assemblyDirectory, GetNativeLibraryFilename());
// With dotnet SDK project targeting netcoreappX.Y, projects will use Grpc.Core assembly directly in the location where it got restored
// by nuget. We locate the native libraries based on known structure of Grpc.Core nuget package.
// When "dotnet publish" is used, the runtimes directory is copied next to the published assemblies.
string runtimesDirectory = string.Format("runtimes/{0}/native", GetRuntimeIdString());
var netCorePublishedAppStylePath = Path.Combine(assemblyDirectory, runtimesDirectory, GetNativeLibraryFilename());
var netCoreAppStylePath = Path.Combine(assemblyDirectory, "../..", runtimesDirectory, GetNativeLibraryFilename());
// Look for the native library in all possible locations in given order.
string[] paths = new[] { classicPath, netCorePublishedAppStylePath, netCoreAppStylePath};
// The UnmanagedLibrary mechanism for loading the native extension while avoiding
// direct use of DllImport is quite complicated but it is currently needed to ensure:
// 1.) the native extension is loaded eagerly (needed to avoid startup issues)
// 2.) less common scenarios (such as loading Grpc.Core.dll by reflection) still work
// 3.) loading native extension from an arbitrary location when set by an enviroment variable
// TODO(jtattermusch): revisit the possibility of eliminating UnmanagedLibrary completely in the future.
return new NativeMethods(new UnmanagedLibrary(paths));
}
/// <summary>
/// Loads native methods using the <c>[DllImport(LIBRARY_NAME)]</c> attributes.
/// Note that this way of loading the native extension is "lazy" and doesn't
/// detect any "missing library" problems until we actually try to invoke the native methods
/// (which could be too late and could cause weird hangs at startup)
/// </summary>
private static NativeMethods LoadNativeMethodsUsingDllImports()
{
// While in theory, we could just use [DllImport("grpc_csharp_ext")] for all the platforms
// and operating systems, the native libraries in the nuget package
// need to be laid out in a way that still allows things to work well under
// the legacy .NET Framework (where native libraries are a concept unknown to the runtime).
// Therefore, we use several flavors of the DllImport attribute
// (e.g. the ".x86" vs ".x64" suffix) and we choose the one we want at runtime.
// The classes with the list of DllImport'd methods are code generated,
// so having more than just one doesn't really bother us.
// on Windows, the DllImport("grpc_csharp_ext.x64") doesn't work
// but DllImport("grpc_csharp_ext.x64.dll") does, so we need a special case for that.
// See https://github.com/dotnet/coreclr/pull/17505 (fixed in .NET Core 3.1+)
bool useDllSuffix = PlatformApis.IsWindows;
if (PlatformApis.ProcessArchitecture == CommonPlatformDetection.CpuArchitecture.X64)
{
if (useDllSuffix)
{
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib_x64_dll());
}
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib_x64());
}
else if (PlatformApis.ProcessArchitecture == CommonPlatformDetection.CpuArchitecture.X86)
{
if (useDllSuffix)
{
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib_x86_dll());
}
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib_x86());
}
else if (PlatformApis.ProcessArchitecture == CommonPlatformDetection.CpuArchitecture.Arm64)
{
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib_arm64());
}
else
{
throw new InvalidOperationException($"Unsupported architecture \"{PlatformApis.ProcessArchitecture}\".");
}
}
/// <summary>
/// Loads native extension and return native methods delegates.
/// </summary>
private static NativeMethods LoadNativeMethods()
{
if (PlatformApis.IsUnity)
{
return LoadNativeMethodsUnity();
}
if (PlatformApis.IsXamarin)
{
return LoadNativeMethodsXamarin();
}
// Override location of grpc_csharp_ext native library with an environment variable
// Use at your own risk! By doing this you take all the responsibility that the dynamic library
// is of the correct version (needs to match the Grpc.Core assembly exactly) and of the correct platform/architecture.
var nativeExtPathFromEnv = System.Environment.GetEnvironmentVariable(CsharpExtOverrideLocationEnvVarName);
if (!string.IsNullOrEmpty(nativeExtPathFromEnv))
{
return new NativeMethods(new UnmanagedLibrary(new string[] { nativeExtPathFromEnv }));
}
if (IsNet5SingleFileApp())
{
// Ideally we'd want to always load the native extension explicitly
// (to detect any potential problems early on and to avoid hard-to-debug startup issues)
// but the mechanism we normally use doesn't work when running
// as a single file app (see https://github.com/grpc/grpc/pull/24744).
// Therefore in this case we simply rely
// on the automatic [DllImport] loading logic to do the right thing.
return LoadNativeMethodsUsingDllImports();
}
return LoadNativeMethodsUsingExplicitLoad();
}
/// <summary>
/// Return native method delegates when running on Unity platform.
/// Unity does not use standard NuGet packages and the native library is treated
/// there as a "native plugin" which is (provided it has the right metadata)
/// automatically made available to <c>[DllImport]</c> loading logic.
/// WARNING: Unity support is experimental and work-in-progress. Don't expect it to work.
/// </summary>
private static NativeMethods LoadNativeMethodsUnity()
{
if (PlatformApis.IsUnityIOS)
{
return new NativeMethods(new NativeMethods.DllImportsFromStaticLib());
}
// most other platforms load unity plugins as a shared library
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib());
}
/// <summary>
/// Return native method delegates when running on the Xamarin platform.
/// On Xamarin, the standard <c>[DllImport]</c> loading logic just works
/// as the native library metadata is provided by the <c>AndroidNativeLibrary</c> or
/// <c>NativeReference</c> items in the Xamarin projects (injected automatically
/// by the Grpc.Core.Xamarin nuget).
/// WARNING: Xamarin support is experimental and work-in-progress. Don't expect it to work.
/// </summary>
private static NativeMethods LoadNativeMethodsXamarin()
{
if (PlatformApis.IsXamarinAndroid)
{
return new NativeMethods(new NativeMethods.DllImportsFromSharedLib());
}
return new NativeMethods(new NativeMethods.DllImportsFromStaticLib());
}
private static string GetAssemblyDirectory()
{
var assembly = typeof(NativeExtension).GetTypeInfo().Assembly;
#if NETSTANDARD
// Assembly.EscapedCodeBase does not exist under CoreCLR, but assemblies imported from a nuget package
// don't seem to be shadowed by DNX-based projects at all.
var assemblyLocation = assembly.Location;
if (string.IsNullOrEmpty(assemblyLocation))
{
// In .NET5 single-file deployments, assembly.Location won't be available
// and we can use it for detecting whether we are running as a single file app.
// Also see https://docs.microsoft.com/en-us/dotnet/core/deploying/single-file#other-considerations
return null;
}
return Path.GetDirectoryName(assemblyLocation);
#else
// If assembly is shadowed (e.g. in a webapp), EscapedCodeBase is pointing
// to the original location of the assembly, and Location is pointing
// to the shadow copy. We care about the original location because
// the native dlls don't get shadowed.
var escapedCodeBase = assembly.EscapedCodeBase;
if (IsFileUri(escapedCodeBase))
{
return Path.GetDirectoryName(new Uri(escapedCodeBase).LocalPath);
}
return Path.GetDirectoryName(assembly.Location);
#endif
}
private static bool IsNet5SingleFileApp()
{
// Use a heuristic that GetAssemblyDirectory() will return null for single file apps.
return PlatformApis.IsNet5OrHigher && GetAssemblyDirectory() == null;
}
#if !NETSTANDARD
private static bool IsFileUri(string uri)
{
return uri.ToLowerInvariant().StartsWith(Uri.UriSchemeFile);
}
#endif
private static string GetRuntimeIdString()
{
string architecture = GetArchitectureString();
if (PlatformApis.IsWindows)
{
return string.Format("win-{0}", architecture);
}
if (PlatformApis.IsLinux)
{
return string.Format("linux-{0}", architecture);
}
if (PlatformApis.IsMacOSX)
{
return string.Format("osx-{0}", architecture);
}
throw new InvalidOperationException("Unsupported platform.");
}
private static string GetArchitectureString()
{
switch (PlatformApis.ProcessArchitecture)
{
case CommonPlatformDetection.CpuArchitecture.X86:
return "x86";
case CommonPlatformDetection.CpuArchitecture.X64:
return "x64";
case CommonPlatformDetection.CpuArchitecture.Arm64:
return "arm64";
default:
throw new InvalidOperationException($"Unsupported architecture \"{PlatformApis.ProcessArchitecture}\".");
}
}
// platform specific file name of the extension library
private static string GetNativeLibraryFilename()
{
string architecture = GetArchitectureString();
if (PlatformApis.IsWindows)
{
return string.Format("grpc_csharp_ext.{0}.dll", architecture);
}
if (PlatformApis.IsLinux)
{
return string.Format("libgrpc_csharp_ext.{0}.so", architecture);
}
if (PlatformApis.IsMacOSX)
{
return string.Format("libgrpc_csharp_ext.{0}.dylib", architecture);
}
throw new InvalidOperationException("Unsupported platform.");
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: MediaPlayer.cs
//
// 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 Dot42;
namespace Android.Media
{
partial class MediaPlayer
{
#region System resource ID's
#pragma warning disable 649
[Dot42.ResourceId("__dot42_mediaplayer_bufferingupdate_listener")]
private static readonly int bufferingUpdateListenerKey;
[Dot42.ResourceId("__dot42_mediaplayer_completion_listener")]
private static readonly int completionListenerKey;
[Dot42.ResourceId("__dot42_mediaplayer_error_listener")]
private static readonly int errorListenerKey;
[Dot42.ResourceId("__dot42_mediaplayer_info_listener")]
private static readonly int infoListenerKey;
[Dot42.ResourceId("__dot42_mediaplayer_prepared_listener")]
private static readonly int preparedListenerKey;
[Dot42.ResourceId("__dot42_mediaplayer_seekComplete_listener")]
private static readonly int seekCompleteListenerKey;
#if ANDROID_16P
[Dot42.ResourceId("__dot42_mediaplayer_timedText_listener")]
private static readonly int timedTextListenerKey;
#endif
[Dot42.ResourceId("__dot42_mediaplayer_videoSizeChanged_listener")]
private static readonly int videoSizeChangedListenerKey;
#pragma warning restore 649
#endregion // System resource ID's
/// <summary>
/// Called to update status in buffering a media stream received through progressive HTTP download.
/// </summary>
public event EventHandler<BufferingUpdateEventArgs> BufferingUpdate
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnBufferingUpdateListener>(this, bufferingUpdateListenerKey, true, SetOnBufferingUpdateListener);
l.Add(value);
}
remove { }
}
/// <summary>
/// Called when the end of a media source is reached during playback.
/// </summary>
public event EventHandler Completion
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnNoArgsListener>(this, completionListenerKey, true, SetOnCompletionListener);
l.Add(value);
}
remove { }
}
/// <summary>
/// Called to indicate an error.
/// </summary>
public event EventHandler<InfoEventArgs> Error
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnInfoOrErrorListener>(this, errorListenerKey, true, SetOnErrorListener);
l.Add(value);
}
remove { }
}
/// <summary>
/// Called to indicate an info or warning.
/// </summary>
public event EventHandler<InfoEventArgs> Info
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnInfoOrErrorListener>(this, infoListenerKey, true, SetOnInfoListener);
l.Add(value);
}
remove { }
}
/// <summary>
/// Called when the media file is ready for playback.
/// </summary>
public event EventHandler Prepared
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnNoArgsListener>(this, preparedListenerKey, true, SetOnPreparedListener);
l.Add(value);
}
remove { }
}
/// <summary>
/// Called to indicate the completion of a seek operation.
/// </summary>
public event EventHandler SeekComplete
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnNoArgsListener>(this, seekCompleteListenerKey, true, SetOnSeekCompleteListener);
l.Add(value);
}
remove { }
}
#if ANDROID_16P
/// <summary>
/// Called to indicate an avaliable timed text
/// </summary>
public event EventHandler<TimedTextEventArgs> TimedText
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnTimedTextListener>(this, timedTextListenerKey, true, SetOnTimedTextListener);
l.Add(value);
}
remove { }
}
#endif
/// <summary>
/// Called to update status in buffering a media stream received through progressive HTTP download.
/// </summary>
public event EventHandler<VideoSizeEventArgs> VideoSizeChanged
{
add
{
var l = EventHandlers.GetOrCreate<MediaPlayerOnVideoSizeChangedListener>(this, videoSizeChangedListenerKey, true, SetOnVideoSizeChangedListener);
l.Add(value);
}
remove { }
}
}
/// <summary>
/// Implementation of the <see cref="MediaPlayer.BufferingUpdate"/> event.
/// </summary>
internal sealed class MediaPlayerOnBufferingUpdateListener : EventHandlerListener<BufferingUpdateEventArgs>, MediaPlayer.IOnBufferingUpdateListener
{
/// <summary>
/// Invoke
/// </summary>
public void OnBufferingUpdate(MediaPlayer mediaPlayer, int percent)
{
Invoke(mediaPlayer, new BufferingUpdateEventArgs(percent));
}
}
/// <summary>
/// Implementation of the <see cref="MediaPlayer.Completion"/> event.
/// </summary>
internal sealed class MediaPlayerOnNoArgsListener : EventHandlerListener, MediaPlayer.IOnCompletionListener, MediaPlayer.IOnPreparedListener, MediaPlayer.IOnSeekCompleteListener
{
/// <summary>
/// Invoke
/// </summary>
public void OnCompletion(MediaPlayer mediaPlayer)
{
Invoke(mediaPlayer, EventArgs.Empty);
}
public void OnPrepared(MediaPlayer mediaPlayer)
{
Invoke(mediaPlayer, EventArgs.Empty);
}
public void OnSeekComplete(MediaPlayer mediaPlayer)
{
Invoke(mediaPlayer, EventArgs.Empty);
}
}
/// <summary>
/// Implementation of the <see cref="MediaPlayer.Error"/> and <see cref="MediaPlayer.Info"/> event.
/// </summary>
internal sealed class MediaPlayerOnInfoOrErrorListener : EventHandlerListener<InfoEventArgs>, MediaPlayer.IOnErrorListener, MediaPlayer.IOnInfoListener
{
/// <summary>
/// Invoke
/// </summary>
public bool OnError(MediaPlayer mediaPlayer, int what, int extra)
{
var args = new InfoEventArgs(what, extra);
Invoke(mediaPlayer, args);
return args.IsHandled;
}
public bool OnInfo(MediaPlayer mediaPlayer, int what, int extra)
{
var args = new InfoEventArgs(what, extra);
Invoke(mediaPlayer, args);
return args.IsHandled;
}
}
#if ANDROID_16P
/// <summary>
/// Implementation of the <see cref="MediaPlayer.Error"/> and <see cref="MediaPlayer.Info"/> event.
/// </summary>
internal sealed class MediaPlayerOnTimedTextListener : EventHandlerListener<TimedTextEventArgs>, MediaPlayer.IOnTimedTextListener
{
/// <summary>
/// Invoke
/// </summary>
public void OnTimedText(MediaPlayer mediaPlayer, TimedText text)
{
Invoke(mediaPlayer, new TimedTextEventArgs(text));
}
}
#endif
/// <summary>
/// Implementation of the <see cref="MediaPlayer.Error"/> and <see cref="MediaPlayer.Info"/> event.
/// </summary>
internal sealed class MediaPlayerOnVideoSizeChangedListener : EventHandlerListener<VideoSizeEventArgs>, MediaPlayer.IOnVideoSizeChangedListener
{
/// <summary>
/// Invoke
/// </summary>
public void OnVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height)
{
Invoke(mediaPlayer, new VideoSizeEventArgs(width, height));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace hangrife_api.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for compute.
/// </summary>
public partial class ComputeApiTest
{
/** Java binary class name. */
private const string JavaBinaryCls = "PlatformComputeJavaBinarizable";
/** */
public const string DefaultCacheName = "default";
/** First node. */
private IIgnite _grid1;
/** Second node. */
private IIgnite _grid2;
/** Third node. */
private IIgnite _grid3;
/** Thin client. */
private IIgniteClient _igniteClient;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
var configs = GetConfigs();
_grid1 = Ignition.Start(Configuration(configs.Item1));
_grid2 = Ignition.Start(Configuration(configs.Item2));
AffinityTopologyVersion waitingTop = new AffinityTopologyVersion(2, 1);
Assert.True(_grid1.WaitTopology(waitingTop), "Failed to wait topology " + waitingTop);
_grid3 = Ignition.Start(Configuration(configs.Item3));
// Start thin client.
_igniteClient = Ignition.StartClient(GetThinClientConfiguration());
}
/// <summary>
/// Gets the configs.
/// </summary>
protected virtual Tuple<string, string, string> GetConfigs()
{
var path = Path.Combine("Config", "Compute", "compute-grid");
return Tuple.Create(path + "1.xml", path + "2.xml", path + "3.xml");
}
/// <summary>
/// Gets the thin client configuration.
/// </summary>
private static IgniteClientConfiguration GetThinClientConfiguration()
{
return new IgniteClientConfiguration
{
Endpoints = new List<string> { IPAddress.Loopback.ToString() },
SocketTimeout = TimeSpan.FromSeconds(15)
};
}
/// <summary>
/// Gets the expected compact footers setting.
/// </summary>
protected virtual bool CompactFooter
{
get { return true; }
}
[TestFixtureTearDown]
public void StopClient()
{
Ignition.StopAll(true);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
}
/// <summary>
/// Test that it is possible to get projection from grid.
/// </summary>
[Test]
public void TestProjection()
{
IClusterGroup prj = _grid1.GetCluster();
Assert.NotNull(prj);
Assert.AreEqual(prj, prj.Ignite);
// Check that default Compute projection excludes client nodes.
CollectionAssert.AreEquivalent(prj.ForServers().GetNodes(), prj.GetCompute().ClusterGroup.GetNodes());
}
/// <summary>
/// Test non-existent cache.
/// </summary>
[Test]
public void TestNonExistentCache()
{
Assert.Catch(typeof(ArgumentException), () =>
{
_grid1.GetCache<int, int>("bad_name");
});
}
/// <summary>
/// Test node content.
/// </summary>
[Test]
public void TestNodeContent()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
foreach (IClusterNode node in nodes)
{
Assert.NotNull(node.Addresses);
Assert.IsTrue(node.Addresses.Count > 0);
Assert.Throws<NotSupportedException>(() => node.Addresses.Add("addr"));
Assert.NotNull(node.Attributes);
Assert.IsTrue(node.Attributes.Count > 0);
Assert.Throws<NotSupportedException>(() => node.Attributes.Add("key", "val"));
#pragma warning disable 618
Assert.AreSame(node.Attributes, node.GetAttributes());
#pragma warning restore 618
Assert.NotNull(node.HostNames);
Assert.Throws<NotSupportedException>(() => node.HostNames.Add("h"));
Assert.IsTrue(node.Id != Guid.Empty);
Assert.IsTrue(node.Order > 0);
Assert.NotNull(node.GetMetrics());
}
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestClusterMetrics()
{
var cluster = _grid1.GetCluster();
var metrics = cluster.GetMetrics();
Assert.IsNotNull(metrics);
Assert.AreEqual(cluster.GetNodes().Count, metrics.TotalNodes);
TestUtils.WaitForTrueCondition(() => cluster.GetMetrics().LastUpdateTime > metrics.LastUpdateTime, 2000);
var newMetrics = cluster.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestNodeMetrics()
{
var node = _grid1.GetCluster().GetNode();
IClusterMetrics metrics = node.GetMetrics();
Assert.IsNotNull(metrics);
Assert.IsTrue(metrics == node.GetMetrics());
Thread.Sleep(2000);
IClusterMetrics newMetrics = node.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestResetMetrics()
{
var cluster = _grid1.GetCluster();
Thread.Sleep(2000);
var metrics1 = cluster.GetMetrics();
cluster.ResetMetrics();
var metrics2 = cluster.GetMetrics();
Assert.IsNotNull(metrics1);
Assert.IsNotNull(metrics2);
}
/// <summary>
/// Test node ping.
/// </summary>
[Test]
public void TestPingNode()
{
var cluster = _grid1.GetCluster();
Assert.IsTrue(cluster.GetNodes().Select(node => node.Id).All(cluster.PingNode));
Assert.IsFalse(cluster.PingNode(Guid.NewGuid()));
}
/// <summary>
/// Tests the topology version.
/// </summary>
[Test]
public void TestTopologyVersion()
{
var cluster = _grid1.GetCluster();
var topVer = cluster.TopologyVersion;
Ignition.Stop(_grid3.Name, true);
Assert.AreEqual(topVer + 1, _grid1.GetCluster().TopologyVersion);
_grid3 = Ignition.Start(Configuration(GetConfigs().Item3));
Assert.AreEqual(topVer + 2, _grid1.GetCluster().TopologyVersion);
}
/// <summary>
/// Tests the topology by version.
/// </summary>
[Test]
public void TestTopology()
{
var cluster = _grid1.GetCluster();
Assert.AreEqual(1, cluster.GetTopology(1).Count);
Assert.AreEqual(null, cluster.GetTopology(int.MaxValue));
// Check that Nodes and Topology return the same for current version
var topVer = cluster.TopologyVersion;
var top = cluster.GetTopology(topVer);
var nodes = cluster.GetNodes();
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
// Stop/start node to advance version and check that history is still correct
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
try
{
top = cluster.GetTopology(topVer);
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
}
finally
{
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
}
}
/// <summary>
/// Test nodes in full topology.
/// </summary>
[Test]
public void TestNodes()
{
Assert.IsNotNull(_grid1.GetCluster().GetNode());
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
// Check subsequent call on the same topology.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
// Check subsequent calls on updating topologies.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds".
/// </summary>
[Test]
public void TestForNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterNode first = nodes.ElementAt(0);
IClusterNode second = nodes.ElementAt(1);
IClusterGroup singleNodePrj = _grid1.GetCluster().ForNodeIds(first.Id);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodeIds(new List<Guid> { first.Id });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(first);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
IClusterGroup multiNodePrj = _grid1.GetCluster().ForNodeIds(first.Id, second.Id);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodeIds(new[] {first, second}.Select(x => x.Id));
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(first, second);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first, second });
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds". Make sure lazy enumerables are enumerated only once.
/// </summary>
[Test]
public void TestForNodesLaziness()
{
var nodes = _grid1.GetCluster().GetNodes().Take(2).ToArray();
var callCount = 0;
Func<IClusterNode, IClusterNode> nodeSelector = node =>
{
callCount++;
return node;
};
Func<IClusterNode, Guid> idSelector = node =>
{
callCount++;
return node.Id;
};
var projection = _grid1.GetCluster().ForNodes(nodes.Select(nodeSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(2, callCount);
projection = _grid1.GetCluster().ForNodeIds(nodes.Select(idSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(4, callCount);
}
/// <summary>
/// Test for local node projection.
/// </summary>
[Test]
public void TestForLocal()
{
IClusterGroup prj = _grid1.GetCluster().ForLocal();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(_grid1.GetCluster().GetLocalNode(), prj.GetNodes().First());
}
/// <summary>
/// Test for remote nodes projection.
/// </summary>
[Test]
public void TestForRemotes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForRemotes();
Assert.AreEqual(2, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
}
/// <summary>
/// Test for daemon nodes projection.
/// </summary>
[Test]
public void TestForDaemons()
{
Assert.AreEqual(0, _grid1.GetCluster().ForDaemons().GetNodes().Count);
using (var ignite = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = GetConfigs().Item1,
IgniteInstanceName = "daemonGrid",
IsDaemon = true
})
)
{
var prj = _grid1.GetCluster().ForDaemons();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(ignite.GetCluster().GetLocalNode().Id, prj.GetNode().Id);
Assert.IsTrue(prj.GetNode().IsDaemon);
Assert.IsTrue(ignite.GetCluster().GetLocalNode().IsDaemon);
}
}
/// <summary>
/// Test for host nodes projection.
/// </summary>
[Test]
public void TestForHost()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForHost(nodes.First());
Assert.AreEqual(3, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(2)));
}
/// <summary>
/// Test for oldest, youngest and random projections.
/// </summary>
[Test]
public void TestForOldestYoungestRandom()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForYoungest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForOldest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForRandom();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
}
/// <summary>
/// Tests ForServers projection.
/// </summary>
[Test]
public void TestForServers()
{
var cluster = _grid1.GetCluster();
var servers = cluster.ForServers().GetNodes();
Assert.AreEqual(2, servers.Count);
Assert.IsTrue(servers.All(x => !x.IsClient));
var serverAndClient =
cluster.ForNodeIds(new[] { _grid2, _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(1, serverAndClient.ForServers().GetNodes().Count);
var client = cluster.ForNodeIds(new[] { _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(0, client.ForServers().GetNodes().Count);
}
/// <summary>
/// Tests thin client ForServers projection.
/// </summary>
[Test]
public void TestThinClientForServers()
{
var cluster = _igniteClient.GetCluster();
var servers = cluster.ForServers().GetNodes();
Assert.AreEqual(2, servers.Count);
Assert.IsTrue(servers.All(x => !x.IsClient));
}
/// <summary>
/// Test for attribute projection.
/// </summary>
[Test]
public void TestForAttribute()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForAttribute("my_attr", "value1");
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
Assert.AreEqual("value1", prj.GetNodes().First().GetAttribute<string>("my_attr"));
}
/// <summary>
/// Test thin client for attribute projection.
/// </summary>
[Test]
public void TestClientForAttribute()
{
IClientClusterGroup clientPrj = _igniteClient.GetCluster().ForAttribute("my_attr", "value1");
Assert.AreEqual(1,clientPrj.GetNodes().Count);
var nodeId = _grid1.GetCluster().ForAttribute("my_attr", "value1").GetNodes().Single().Id;
Assert.AreEqual(nodeId, clientPrj.GetNode().Id);
}
/// <summary>
/// Test for cache/data/client projections.
/// </summary>
[Test]
public void TestForCacheNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
// Cache nodes.
IClusterGroup prjCache = _grid1.GetCluster().ForCacheNodes("cache1");
Assert.AreEqual(2, prjCache.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(1)));
// Data nodes.
IClusterGroup prjData = _grid1.GetCluster().ForDataNodes("cache1");
Assert.AreEqual(2, prjData.GetNodes().Count);
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(0)));
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(1)));
// Client nodes.
IClusterGroup prjClient = _grid1.GetCluster().ForClientNodes("cache1");
Assert.AreEqual(0, prjClient.GetNodes().Count);
}
/// <summary>
/// Test for cache predicate.
/// </summary>
[Test]
public void TestForPredicate()
{
IClusterGroup prj1 = _grid1.GetCluster()
.ForPredicate(new NotAttributePredicate<IClusterNode>("value1").Apply);
Assert.AreEqual(2, prj1.GetNodes().Count);
IClusterGroup prj2 = prj1
.ForPredicate(new NotAttributePredicate<IClusterNode>("value2").Apply);
Assert.AreEqual(1, prj2.GetNodes().Count);
string val;
prj2.GetNodes().First().TryGetAttribute("my_attr", out val);
Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2")));
}
/// <summary>
/// Test thin client for cache predicate.
/// </summary>
[Test]
public void TestClientForPredicate()
{
var prj1 = _igniteClient.GetCluster()
.ForPredicate(new NotAttributePredicate<IClientClusterNode>("value1").Apply);
Assert.AreEqual(2, prj1.GetNodes().Count);
var prj2 = prj1
.ForPredicate(new NotAttributePredicate<IClientClusterNode>("value2").Apply);
Assert.AreEqual(1, prj2.GetNodes().Count);
var val = (string) prj2.GetNodes().First().Attributes.FirstOrDefault(attr => attr.Key == "my_attr").Value;
Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2")));
}
/// <summary>
/// Attribute predicate.
/// </summary>
private class NotAttributePredicate<T> where T: IBaselineNode
{
/** Required attribute value. */
private readonly string _attrVal;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="attrVal">Required attribute value.</param>
public NotAttributePredicate(string attrVal)
{
_attrVal = attrVal;
}
/** <inhreitDoc /> */
public bool Apply(T node)
{
object val;
node.Attributes.TryGetValue("my_attr", out val);
return val == null || !val.Equals(_attrVal);
}
}
/// <summary>
/// Tests the action broadcast.
/// </summary>
[Test]
public void TestBroadcastAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Broadcast(new ComputeAction(id));
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().BroadcastAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(new ComputeAction(id));
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().RunAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunActionAsyncCancel()
{
using (var cts = new CancellationTokenSource())
{
// Cancel while executing
var task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
cts.Cancel();
TestUtils.WaitForTrueCondition(() => task.IsCanceled);
// Use cancelled token
var task2 = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
Assert.IsTrue(task2.IsCanceled);
}
}
/// <summary>
/// Tests multiple actions run.
/// </summary>
[Test]
public void TestRunActions()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(Enumerable.Range(0, 10).Select(x => new ComputeAction(id)));
Assert.AreEqual(10, ComputeAction.InvokeCount(id));
var id2 = Guid.NewGuid();
_grid1.GetCompute().RunAsync(Enumerable.Range(0, 10).Select(x => new ComputeAction(id2))).Wait();
Assert.AreEqual(10, ComputeAction.InvokeCount(id2));
}
/// <summary>
/// Tests affinity run.
/// </summary>
[Test]
public void TestAffinityRun()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] {_grid1, _grid2}.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
var computeAction = new ComputeAction
{
ReservedPartition = aff.GetPartition(primaryKey),
CacheNames = new[] {cacheName}
};
_grid1.GetCompute().AffinityRun(cacheName, affinityKey, computeAction);
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
_grid1.GetCompute().AffinityRunAsync(cacheName, affinityKey, computeAction).Wait();
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
}
}
/// <summary>
/// Tests affinity call.
/// </summary>
[Test]
public void TestAffinityCall()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] { _grid1, _grid2 }.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
var result = _grid1.GetCompute().AffinityCall(cacheName, affinityKey, new ComputeFunc());
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
// Async.
ComputeFunc.InvokeCount = 0;
result = _grid1.GetCompute().AffinityCallAsync(cacheName, affinityKey, new ComputeFunc()).Result;
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
}
}
/// <summary>
/// Tests affinity call with partition.
/// </summary>
[Test]
public void TestAffinityCallWithPartition([Values(true, false)] bool async)
{
var cacheName = DefaultCacheName;
var aff = _grid1.GetAffinity(cacheName);
var localNode = _grid1.GetCluster().GetLocalNode();
var part = aff.GetPrimaryPartitions(localNode).First();
var compute = _grid1.GetCompute();
Func<IEnumerable<string>, int> action = names => async
? compute.AffinityCallAsync(names, part, new ComputeFunc()).Result
: compute.AffinityCall(names, part, new ComputeFunc());
// One cache.
var res = action(new[] {cacheName});
Assert.AreEqual(res, ComputeFunc.InvokeCount);
Assert.AreEqual(localNode.Id, ComputeFunc.LastNodeId);
// Two caches.
var cache = _grid1.CreateCache<int, int>(TestUtils.TestName);
res = action(new[] {cacheName, cache.Name});
Assert.AreEqual(res, ComputeFunc.InvokeCount);
Assert.AreEqual(localNode.Id, ComputeFunc.LastNodeId);
// Empty caches.
var ex = Assert.Throws<ArgumentException>(() => action(new string[0]));
StringAssert.StartsWith("cacheNames can not be empty", ex.Message);
// Invalid cache name.
Assert.Throws<AggregateException>(() => action(new[] {"bad"}));
// Invalid partition.
Assert.Throws<ArgumentException>(() => compute.AffinityCall(new[] {cacheName}, -1, new ComputeFunc()));
}
/// <summary>
/// Tests affinity run with partition.
/// </summary>
[Test]
public void TestAffinityRunWithPartition([Values(true, false)] bool local,
[Values(true, false)] bool multiCache, [Values(true, false)] bool async)
{
var cacheNames = new List<string> {DefaultCacheName};
if (multiCache)
{
var cache2 = _grid1.CreateCache<int, int>(TestUtils.TestName);
cacheNames.Add(cache2.Name);
}
var node = local
? _grid1.GetCluster().GetLocalNode()
: _grid2.GetCluster().GetLocalNode();
var aff = _grid1.GetAffinity(cacheNames[0]);
// Wait for some partitions to be assigned to the node.
TestUtils.WaitForTrueCondition(() => aff.GetPrimaryPartitions(node).Any());
var part = aff.GetPrimaryPartitions(node).First();
var computeAction = new ComputeAction
{
ReservedPartition = part,
CacheNames = cacheNames
};
var action = async
? (Action) (() => _grid1.GetCompute().AffinityRunAsync(cacheNames, part, computeAction).Wait())
: () => _grid1.GetCompute().AffinityRun(cacheNames, part, computeAction);
// Good case.
action();
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
// Exception in user code.
computeAction.ShouldThrow = true;
var aex = Assert.Throws<AggregateException>(() => action());
var ex = aex.GetBaseException();
StringAssert.StartsWith("Remote job threw user exception", ex.Message);
Assert.AreEqual("Error in ComputeAction", ex.GetInnermostException().Message);
}
/// <summary>
/// Tests affinity operations with cancellation.
/// </summary>
[Test]
public void TestAffinityOpAsyncWithCancellation([Values(true, false)] bool callOrRun,
[Values(true, false)] bool keyOrPart)
{
var compute = _grid1.GetCompute();
Action<CancellationToken> action = token =>
{
if (callOrRun)
{
if (keyOrPart)
{
compute.AffinityCallAsync(DefaultCacheName, 1, new ComputeFunc(), token).Wait();
}
else
{
compute.AffinityCallAsync(new[] {DefaultCacheName}, 1, new ComputeFunc(), token).Wait();
}
}
else
{
if (keyOrPart)
{
compute.AffinityRunAsync(DefaultCacheName, 1, new ComputeAction(), token).Wait();
}
else
{
compute.AffinityRunAsync(new[] {DefaultCacheName}, 1, new ComputeAction(), token).Wait();
}
}
};
// Not cancelled.
Assert.DoesNotThrow(() => action(CancellationToken.None));
// Cancelled.
var ex = Assert.Throws<AggregateException>(() => action(new CancellationToken(true)));
Assert.IsInstanceOf<TaskCanceledException>(ex.GetInnermostException());
}
/// <summary>
/// Test simple dotNet task execution.
/// </summary>
[Test]
public void TestNetTaskSimple()
{
Assert.AreEqual(2, _grid1.GetCompute()
.Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Res);
Assert.AreEqual(2, _grid1.GetCompute()
.ExecuteAsync<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Result.Res);
Assert.AreEqual(4, _grid1.GetCompute().Execute(new NetSimpleTask(), new NetSimpleJobArgument(2)).Res);
Assert.AreEqual(6, _grid1.GetCompute().ExecuteAsync(new NetSimpleTask(), new NetSimpleJobArgument(3))
.Result.Res);
}
/// <summary>
/// Tests the exceptions.
/// </summary>
[Test]
public void TestExceptions()
{
Assert.Throws<AggregateException>(() => _grid1.GetCompute().Broadcast(new InvalidComputeAction()));
Assert.Throws<AggregateException>(
() => _grid1.GetCompute().Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof (NetSimpleTask), new NetSimpleJobArgument(-1)));
// Local.
var ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForLocal().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Compute job has failed on local node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
// Remote.
ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForRemotes().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Compute job has failed on remote node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
}
/// <summary>
/// Tests the footer setting.
/// </summary>
[Test]
public void TestFooterSetting()
{
Assert.AreEqual(CompactFooter, ((Ignite) _grid1).Marshaller.CompactFooter);
foreach (var g in new[] {_grid1, _grid2, _grid3})
Assert.AreEqual(CompactFooter, g.GetConfiguration().BinaryConfiguration.CompactFooter);
}
/// <summary>
/// Create configuration.
/// </summary>
/// <param name="path">XML config path.</param>
private static IgniteConfiguration Configuration(string path)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(PlatformComputeBinarizable)),
new BinaryTypeConfiguration(typeof(PlatformComputeNetBinarizable)),
new BinaryTypeConfiguration(JavaBinaryCls),
new BinaryTypeConfiguration(typeof(PlatformComputeEnum)),
new BinaryTypeConfiguration(typeof(InteropComputeEnumFieldTest))
},
NameMapper = new BinaryBasicNameMapper { IsSimpleName = true }
},
SpringConfigUrl = path
};
}
}
class PlatformComputeNetBinarizable : PlatformComputeBinarizable
{
}
[Serializable]
class NetSimpleTask : IComputeTask<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>
{
/** <inheritDoc /> */
public IDictionary<IComputeJob<NetSimpleJobResult>, IClusterNode> Map(IList<IClusterNode> subgrid,
NetSimpleJobArgument arg)
{
var jobs = new Dictionary<IComputeJob<NetSimpleJobResult>, IClusterNode>();
for (int i = 0; i < subgrid.Count; i++)
{
var job = arg.Arg > 0 ? new NetSimpleJob {Arg = arg} : new InvalidNetSimpleJob();
jobs[job] = subgrid[i];
}
return jobs;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<NetSimpleJobResult> res,
IList<IComputeJobResult<NetSimpleJobResult>> rcvd)
{
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public NetSimpleTaskResult Reduce(IList<IComputeJobResult<NetSimpleJobResult>> results)
{
return new NetSimpleTaskResult(results.Sum(res => res.Data.Res));
}
}
[Serializable]
class NetSimpleJob : IComputeJob<NetSimpleJobResult>
{
public NetSimpleJobArgument Arg;
/** <inheritDoc /> */
public NetSimpleJobResult Execute()
{
return new NetSimpleJobResult(Arg.Arg);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
class InvalidNetSimpleJob : NetSimpleJob, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
[Serializable]
class NetSimpleJobArgument
{
public int Arg;
public NetSimpleJobArgument(int arg)
{
Arg = arg;
}
}
[Serializable]
class NetSimpleTaskResult
{
public int Res;
public NetSimpleTaskResult(int res)
{
Res = res;
}
}
[Serializable]
class NetSimpleJobResult
{
public int Res;
public NetSimpleJobResult(int res)
{
Res = res;
}
}
[Serializable]
class ComputeAction : IComputeAction
{
[InstanceResource]
#pragma warning disable 649
// ReSharper disable once UnassignedField.Local
private IIgnite _grid;
public static ConcurrentBag<Guid> Invokes = new ConcurrentBag<Guid>();
public static Guid LastNodeId;
public Guid Id { get; set; }
public int? ReservedPartition { get; set; }
public ICollection<string> CacheNames { get; set; }
public bool ShouldThrow { get; set; }
public ComputeAction()
{
// No-op.
}
public ComputeAction(Guid id)
{
Id = id;
}
public void Invoke()
{
Thread.Sleep(10);
Invokes.Add(Id);
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
if (ReservedPartition != null)
{
Assert.IsNotNull(CacheNames);
foreach (var cacheName in CacheNames)
{
Assert.IsTrue(TestUtils.IsPartitionReserved(_grid, cacheName, ReservedPartition.Value));
}
}
if (ShouldThrow)
{
throw new Exception("Error in ComputeAction");
}
}
public static int InvokeCount(Guid id)
{
return Invokes.Count(x => x == id);
}
}
class InvalidComputeAction : ComputeAction, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
class ExceptionalComputeAction : IComputeAction
{
public const string ErrorText = "Expected user exception";
public void Invoke()
{
throw new OverflowException(ErrorText);
}
}
interface IUserInterface<out T>
{
T Invoke();
}
interface INestedComputeFunc : IComputeFunc<int>
{
}
[Serializable]
class ComputeFunc : INestedComputeFunc, IUserInterface<int>
{
[InstanceResource]
// ReSharper disable once UnassignedField.Local
private IIgnite _grid;
public static int InvokeCount;
public static Guid LastNodeId;
int IComputeFunc<int>.Invoke()
{
Thread.Sleep(10);
InvokeCount++;
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
return InvokeCount;
}
int IUserInterface<int>.Invoke()
{
// Same signature as IComputeFunc<int>, but from different interface
throw new Exception("Invalid method");
}
public int Invoke()
{
// Same signature as IComputeFunc<int>, but due to explicit interface implementation this is a wrong method
throw new Exception("Invalid method");
}
}
public enum PlatformComputeEnum : ushort
{
Foo,
Bar,
Baz
}
public class InteropComputeEnumFieldTest
{
public PlatformComputeEnum InteropEnum { get; set; }
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Internal.NetworkSenders
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using NLog.Internal.NetworkSenders;
using Xunit;
public class TcpNetworkSenderTests : NLogTestBase
{
[Fact]
public void TcpHappyPathTest()
{
foreach (bool async in new[] { false, true })
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
Async = async,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
mre.Reset();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
sender.Close(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.True(actual.IndexOf("close") != -1);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
}
}
[Fact]
public void TcpProxyTest()
{
var sender = new TcpNetworkSender("tcp://foo:1234", AddressFamily.Unspecified);
var socket = sender.CreateSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.IsType<SocketProxy>(socket);
}
[Fact]
public void TcpConnectFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
ConnectFailure = 1,
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
var allSent = new ManualResetEvent(false);
for (int i = 1; i < 8; i++)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (exceptions.Count == 7)
{
allSent.Set();
}
}
});
}
Assert.True(allSent.WaitOne(3000, false));
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex => mre.Set());
mre.WaitOne(3000, false);
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("failed") != -1);
foreach (var ex in exceptions)
{
Assert.NotNull(ex);
}
}
[Fact]
public void TcpSendFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
SendFailureIn = 3, // will cause failure on 3rd send
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new Exception[9];
var writeFinished = new ManualResetEvent(false);
int remaining = exceptions.Length;
for (int i = 1; i < 10; i++)
{
int pos = i - 1;
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions[pos] = ex;
if (--remaining == 0)
{
writeFinished.Set();
}
}
});
}
var mre = new ManualResetEvent(false);
writeFinished.WaitOne();
sender.Close(ex => mre.Set());
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 3 'qui'") != -1);
Assert.True(actual.IndexOf("failed") != -1);
Assert.True(actual.IndexOf("close") != -1);
for (int i = 0; i < exceptions.Length; ++i)
{
if (i < 2)
{
Assert.Null(exceptions[i]);
}
else
{
Assert.NotNull(exceptions[i]);
}
}
}
internal class MyTcpNetworkSender : TcpNetworkSender
{
public StringWriter Log { get; set; }
public MyTcpNetworkSender(string url, AddressFamily addressFamily)
: base(url, addressFamily)
{
this.Log = new StringWriter();
}
protected internal override ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
return new MockSocket(addressFamily, socketType, protocolType, this);
}
protected override EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily)
{
this.Log.WriteLine("Parse endpoint address {0} {1}", uri, addressFamily);
return new MockEndPoint(uri);
}
public int ConnectFailure { get; set; }
public bool Async { get; set; }
public int SendFailureIn { get; set; }
}
internal class MockSocket : ISocket
{
private readonly MyTcpNetworkSender sender;
private readonly StringWriter log;
private bool faulted = false;
public MockSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, MyTcpNetworkSender sender)
{
this.sender = sender;
this.log = sender.Log;
this.log.WriteLine("create socket {0} {1} {2}", addressFamily, socketType, protocolType);
}
public bool ConnectAsync(SocketAsyncEventArgs args)
{
this.log.WriteLine("connect async to {0}", args.RemoteEndPoint);
lock (this)
{
if (this.sender.ConnectFailure > 0)
{
this.sender.ConnectFailure--;
this.faulted = true;
args.SocketError = SocketError.SocketError;
this.log.WriteLine("failed");
}
}
return InvokeCallback(args);
}
private bool InvokeCallback(SocketAsyncEventArgs args)
{
lock (this)
{
var args2 = args as TcpNetworkSender.MySocketAsyncEventArgs;
if (this.sender.Async)
{
ThreadPool.QueueUserWorkItem(s =>
{
Thread.Sleep(10);
args2.RaiseCompleted();
});
return true;
}
else
{
return false;
}
}
}
public void Close()
{
lock (this)
{
this.log.WriteLine("close");
}
}
public bool SendAsync(SocketAsyncEventArgs args)
{
lock (this)
{
this.log.WriteLine("send async {0} {1} '{2}'", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count));
if (this.sender.SendFailureIn > 0)
{
this.sender.SendFailureIn--;
if (this.sender.SendFailureIn == 0)
{
this.faulted = true;
}
}
if (this.faulted)
{
this.log.WriteLine("failed");
args.SocketError = SocketError.SocketError;
}
}
return InvokeCallback(args);
}
public bool SendToAsync(SocketAsyncEventArgs args)
{
lock (this)
{
this.log.WriteLine("sendto async {0} {1} '{2}' {3}", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count), args.RemoteEndPoint);
return InvokeCallback(args);
}
}
}
internal class MockEndPoint : EndPoint
{
private readonly Uri uri;
public MockEndPoint(Uri uri)
{
this.uri = uri;
}
public override AddressFamily AddressFamily
{
get
{
return (System.Net.Sockets.AddressFamily)10000;
}
}
public override string ToString()
{
return "{mock end point: " + this.uri + "}";
}
}
}
}
| |
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// This file is based on or incorporates material from the project Selenium, licensed under the Apache License, Version 2.0. More info in THIRD-PARTY-NOTICES file.
using System;
using System.Threading;
using System.Threading.Tasks;
using Zu.AsyncWebDriver.Internal;
using Zu.WebBrowser.AsyncInteractions;
using Zu.WebBrowser.BasicTypes;
namespace Zu.AsyncWebDriver.Interactions
{
/// <summary>
/// Provides a mechanism for building advanced interactions with the browser.
/// </summary>
public class Actions : IAction
{
private IWebDriver driver;
private ActionBuilder actionBuilder = new ActionBuilder();
public PointerInputDevice defaultMouse = new PointerInputDevice(PointerKind.Mouse, "default mouse");
public KeyInputDevice defaultKeyboard = new KeyInputDevice("default keyboard");
private IKeyboard keyboard;
private IMouse mouse;
private CompositeAction action = new CompositeAction();
public CompositeAction Action => action;
public ActionBuilder ActionBuilder => actionBuilder;
/// <summary>
/// Initializes a new instance of the <see cref = "Actions"/> class.
/// </summary>
/// <param name = "driver">The <see cref = "IWebDriver"/> object on which the actions built will be performed.</param>
public Actions(IWebDriver driver)
{
this.driver = driver;
IHasInputDevices inputDevicesDriver = driver as IHasInputDevices;
if (inputDevicesDriver == null)
{
IWrapsDriver wrapper = driver as IWrapsDriver;
while (wrapper != null)
{
inputDevicesDriver = wrapper.WrappedDriver as IHasInputDevices;
if (inputDevicesDriver != null)
{
this.driver = wrapper.WrappedDriver;
break;
}
wrapper = wrapper.WrappedDriver as IWrapsDriver;
}
}
if (inputDevicesDriver == null)
{
throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IHasInputDevices.", "driver");
}
this.keyboard = inputDevicesDriver.Keyboard;
this.mouse = inputDevicesDriver.Mouse;
}
/// <summary>
/// Sends a modifier key down message to the browser.
/// </summary>
/// <param name = "theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
/// <exception cref = "ArgumentException">If the key sent is not is not one
/// of <see cref = "Keys.Shift"/>, <see cref = "Keys.Control"/>, or <see cref = "Keys.Alt"/>.</exception>
public Actions KeyDown(string theKey)
{
return this.KeyDown(null, theKey);
}
/// <summary>
/// Sends a modifier key down message to the specified element in the browser.
/// </summary>
/// <param name = "element">The element to which to send the key command.</param>
/// <param name = "theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
/// <exception cref = "ArgumentException">If the key sent is not is not one
/// of <see cref = "Keys.Shift"/>, <see cref = "Keys.Control"/>, or <see cref = "Keys.Alt"/>.</exception>
public Actions KeyDown(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new KeyDownAction(this.keyboard, this.mouse, target, theKey));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, TimeSpan.FromMilliseconds(250)));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(theKey[0]));
this.actionBuilder.AddAction(new PauseInteraction(this.defaultKeyboard, TimeSpan.FromMilliseconds(100)));
return this;
}
/// <summary>
/// Sends a modifier key up message to the browser.
/// </summary>
/// <param name = "theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
/// <exception cref = "ArgumentException">If the key sent is not is not one
/// of <see cref = "Keys.Shift"/>, <see cref = "Keys.Control"/>, or <see cref = "Keys.Alt"/>.</exception>
public Actions KeyUp(string theKey)
{
return this.KeyUp(null, theKey);
}
/// <summary>
/// Sends a modifier up down message to the specified element in the browser.
/// </summary>
/// <param name = "element">The element to which to send the key command.</param>
/// <param name = "theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
/// <exception cref = "ArgumentException">If the key sent is not is not one
/// of <see cref = "Keys.Shift"/>, <see cref = "Keys.Control"/>, or <see cref = "Keys.Alt"/>.</exception>
public Actions KeyUp(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new KeyUpAction(this.keyboard, this.mouse, target, theKey));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, TimeSpan.FromMilliseconds(250)));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(theKey[0]));
return this;
}
/// <summary>
/// Sends a sequence of keystrokes to the browser.
/// </summary>
/// <param name = "keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions SendKeys(string keysToSend)
{
return this.SendKeys(null, keysToSend);
}
/// <summary>
/// Sends a sequence of keystrokes to the specified element in the browser.
/// </summary>
/// <param name = "element">The element to which to send the keystrokes.</param>
/// <param name = "keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions SendKeys(IWebElement element, string keysToSend)
{
if (string.IsNullOrEmpty(keysToSend))
{
throw new ArgumentException("The key value must not be null or empty", "keysToSend");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new SendKeysAction(this.keyboard, this.mouse, target, keysToSend));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, TimeSpan.FromMilliseconds(250)));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
foreach (char key in keysToSend)
{
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(key));
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(key));
}
return this;
}
/// <summary>
/// Clicks and holds the mouse button down on the specified element.
/// </summary>
/// <param name = "onElement">The element on which to click and hold.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions ClickAndHold(IWebElement onElement)
{
this.MoveToElement(onElement).ClickAndHold();
return this;
}
/// <summary>
/// Clicks and holds the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions ClickAndHold()
{
this.action.AddAction(new ClickAndHoldAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
return this;
}
/// <summary>
/// Releases the mouse button on the specified element.
/// </summary>
/// <param name = "onElement">The element on which to release the button.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions Release(IWebElement onElement)
{
this.MoveToElement(onElement).Release();
return this;
}
/// <summary>
/// Releases the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions Release()
{
this.action.AddAction(new ButtonReleaseAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Clicks the mouse on the specified element.
/// </summary>
/// <param name = "onElement">The element on which to click.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions Click(IWebElement onElement)
{
this.MoveToElement(onElement).Click();
return this;
}
/// <summary>
/// Clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions Click()
{
this.action.AddAction(new ClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Double-clicks the mouse on the specified element.
/// </summary>
/// <param name = "onElement">The element on which to double-click.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions DoubleClick(IWebElement onElement)
{
this.MoveToElement(onElement).DoubleClick();
return this;
}
/// <summary>
/// Double-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions DoubleClick()
{
this.action.AddAction(new DoubleClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Moves the mouse to the specified element.
/// </summary>
/// <param name = "toElement">The element to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement)
{
if (toElement == null)
{
throw new ArgumentException("MoveToElement cannot move to a null element with no offset.", "toElement");
}
ILocatable target = GetLocatableFromElement(toElement);
this.action.AddAction(new MoveMouseAction(this.mouse, target));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, 0, 0, TimeSpan.FromMilliseconds(250)));
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the top-left corner of the specified element.
/// </summary>
/// <param name = "toElement">The element to which to move the mouse.</param>
/// <param name = "offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name = "offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY)
{
ILocatable target = GetLocatableFromElement(toElement);
this.action.AddAction(new MoveToOffsetAction(this.mouse, target, offsetX, offsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, offsetX, offsetY, TimeSpan.FromMilliseconds(250)));
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the last known mouse coordinates.
/// </summary>
/// <param name = "offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name = "offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions MoveByOffset(int offsetX, int offsetY)
{
this.action.AddAction(new MoveToOffsetAction(this.mouse, null, offsetX, offsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(CoordinateOrigin.Pointer, offsetX, offsetY, TimeSpan.FromMilliseconds(250)));
return this;
}
/// <summary>
/// Right-clicks the mouse on the specified element.
/// </summary>
/// <param name = "onElement">The element on which to right-click.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions ContextClick(IWebElement onElement)
{
this.MoveToElement(onElement).ContextClick();
return this;
}
/// <summary>
/// Right-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions ContextClick()
{
this.action.AddAction(new ContextClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Right));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Right));
return this;
}
/// <summary>
/// Performs a drag-and-drop operation from one element to another.
/// </summary>
/// <param name = "source">The element on which the drag operation is started.</param>
/// <param name = "target">The element on which the drop is performed.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions DragAndDrop(IWebElement source, IWebElement target)
{
this.ClickAndHold(source).MoveToElement(target).Release(target);
return this;
}
/// <summary>
/// Performs a drag-and-drop operation on one element to a specified offset.
/// </summary>
/// <param name = "source">The element on which the drag operation is started.</param>
/// <param name = "offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name = "offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref = "Actions"/>.</returns>
public Actions DragAndDropToOffset(IWebElement source, int offsetX, int offsetY)
{
this.ClickAndHold(source).MoveByOffset(offsetX, offsetY).Release();
return this;
}
/// <summary>
/// Builds the sequence of actions.
/// </summary>
/// <returns>A composite <see cref = "IAction"/> which can be used to perform the actions.</returns>
public IAction Build()
{
IAction toReturn = new BuiltAction(driver, actionBuilder, action);
action = new CompositeAction();
actionBuilder = new ActionBuilder();
return toReturn;
}
/// <summary>
/// Performs the currently built action.
/// </summary>
public async Task Perform(CancellationToken cancellationToken = default (CancellationToken))
{
IActionExecutor actionExecutor = this.driver as IActionExecutor;
if (await actionExecutor.IsActionExecutor(cancellationToken).ConfigureAwait(false))
{
await actionExecutor.PerformActions(this.actionBuilder.ToActionSequenceList()).ConfigureAwait(false);
}
else
{
await action.Perform().ConfigureAwait(false);
}
}
/// <summary>
/// Gets the <see cref = "ILocatable"/> instance of the specified <see cref = "IWebElement"/>.
/// </summary>
/// <param name = "element">The <see cref = "IWebElement"/> to get the location of.</param>
/// <returns>The <see cref = "ILocatable"/> of the <see cref = "IWebElement"/>.</returns>
protected static ILocatable GetLocatableFromElement(IWebElement element)
{
if (element == null)
{
return null;
}
ILocatable target = element as ILocatable;
if (target == null)
{
IWrapsElement wrapper = element as IWrapsElement;
while (wrapper != null)
{
target = wrapper.WrappedElement as ILocatable;
if (target != null)
{
break;
}
wrapper = wrapper.WrappedElement as IWrapsElement;
}
}
if (target == null)
{
throw new ArgumentException("The IWebElement object must implement or wrap an element that implements ILocatable.", "element");
}
return target;
}
/// <summary>
/// Adds an action to current list of actions to be performed.
/// </summary>
/// <param name = "actionToAdd">The <see cref = "IAction"/> to be added.</param>
protected void AddAction(IAction actionToAdd)
{
this.action.AddAction(actionToAdd);
}
}
}
| |
// 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.
/*
Note on transaction support:
Eventually we will want to add support for NT's transactions to our
RegistryKey API's (possibly Whidbey M3?). When we do this, here's
the list of API's we need to make transaction-aware:
RegCreateKeyEx
RegDeleteKey
RegDeleteValue
RegEnumKeyEx
RegEnumValue
RegOpenKeyEx
RegQueryInfoKey
RegQueryValueEx
RegSetValueEx
We can ignore RegConnectRegistry (remote registry access doesn't yet have
transaction support) and RegFlushKey. RegCloseKey doesn't require any
additional work. .
*/
/*
Note on ACL support:
The key thing to note about ACL's is you set them on a kernel object like a
registry key, then the ACL only gets checked when you construct handles to
them. So if you set an ACL to deny read access to yourself, you'll still be
able to read with that handle, but not with new handles.
Another peculiarity is a Terminal Server app compatibility workaround. The OS
will second guess your attempt to open a handle sometimes. If a certain
combination of Terminal Server app compat registry keys are set, then the
OS will try to reopen your handle with lesser permissions if you couldn't
open it in the specified mode. So on some machines, we will see handles that
may not be able to read or write to a registry key. It's very strange. But
the real test of these handles is attempting to read or set a value in an
affected registry key.
For reference, at least two registry keys must be set to particular values
for this behavior:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1.
HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1
There might possibly be an interaction with yet a third registry key as well.
*/
using Microsoft.Win32.SafeHandles;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Microsoft.Win32
{
/**
* Registry encapsulation. To get an instance of a RegistryKey use the
* Registry class's static members then call OpenSubKey.
*
* @see Registry
* @security(checkDllCalls=off)
* @security(checkClassLinking=on)
*/
internal sealed class RegistryKey : MarshalByRefObject, IDisposable
{
// We could use const here, if C# supported ELEMENT_TYPE_I fully.
internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000));
internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004));
internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));
// Dirty indicates that we have munged data that should be potentially
// written to disk.
//
private const int STATE_DIRTY = 0x0001;
// SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened"
// or "closed".
//
private const int STATE_SYSTEMKEY = 0x0002;
// Access
//
private const int STATE_WRITEACCESS = 0x0004;
// Indicates if this key is for HKEY_PERFORMANCE_DATA
private const int STATE_PERF_DATA = 0x0008;
// Names of keys. This array must be in the same order as the HKEY values listed above.
//
private static readonly String[] hkeyNames = new String[] {
"HKEY_CLASSES_ROOT",
"HKEY_CURRENT_USER",
"HKEY_LOCAL_MACHINE",
"HKEY_USERS",
"HKEY_PERFORMANCE_DATA",
"HKEY_CURRENT_CONFIG",
};
// MSDN defines the following limits for registry key names & values:
// Key Name: 255 characters
// Value name: 16,383 Unicode characters
// Value: either 1 MB or current available memory, depending on registry format.
private const int MaxKeyLength = 255;
private const int MaxValueLength = 16383;
private volatile SafeRegistryHandle hkey = null;
private volatile int state = 0;
private volatile String keyName;
private volatile bool remoteKey = false;
private volatile RegistryKeyPermissionCheck checkMode;
private volatile RegistryView regView = RegistryView.Default;
/**
* Creates a RegistryKey.
*
* This key is bound to hkey, if writable is <b>false</b> then no write operations
* will be allowed. If systemkey is set then the hkey won't be released
* when the object is GC'ed.
* The remoteKey flag when set to true indicates that we are dealing with registry entries
* on a remote machine and requires the program making these calls to have full trust.
*/
private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view)
{
this.hkey = hkey;
keyName = "";
this.remoteKey = remoteKey;
regView = view;
if (systemkey)
{
state |= STATE_SYSTEMKEY;
}
if (writable)
{
state |= STATE_WRITEACCESS;
}
if (isPerfData)
state |= STATE_PERF_DATA;
ValidateKeyView(view);
}
/**
* Closes this key, flushes it to disk if the contents have been modified.
*/
public void Close()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (hkey != null)
{
if (!IsSystemKey())
{
try
{
hkey.Dispose();
}
catch (IOException)
{
// we don't really care if the handle is invalid at this point
}
finally
{
hkey = null;
}
}
else if (disposing && IsPerfDataKey())
{
// System keys should never be closed. However, we want to call RegCloseKey
// on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources
// (i.e. when disposing is true) so that we release the PERFLIB cache and cause it
// to be refreshed (by re-reading the registry) when accessed subsequently.
// This is the only way we can see the just installed perf counter.
// NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race condition in closing
// the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources
// in this situation the down level OSes are not. We have a small window between
// the dispose below and usage elsewhere (other threads). This is By Design.
// This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey
// (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary.
SafeRegistryHandle.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA);
}
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
public void DeleteValue(String name, bool throwOnMissingValue)
{
EnsureWriteable();
int errorCode = Win32Native.RegDeleteValue(hkey, name);
//
// From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
// This still means the name doesn't exist. We need to be consistent with previous OS.
//
if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE)
{
if (throwOnMissingValue)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyValueAbsent);
}
// Otherwise, just return giving no indication to the user.
// (For compatibility)
}
// We really should throw an exception here if errorCode was bad,
// but we can't for compatibility reasons.
Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode);
}
/**
* Retrieves a new RegistryKey that represents the requested key. Valid
* values are:
*
* HKEY_CLASSES_ROOT,
* HKEY_CURRENT_USER,
* HKEY_LOCAL_MACHINE,
* HKEY_USERS,
* HKEY_PERFORMANCE_DATA,
* HKEY_CURRENT_CONFIG,
* HKEY_DYN_DATA.
*
* @param hKey HKEY_* to open.
*
* @return the RegistryKey requested.
*/
internal static RegistryKey GetBaseKey(IntPtr hKey)
{
return GetBaseKey(hKey, RegistryView.Default);
}
internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view)
{
int index = ((int)hKey) & 0x0FFFFFFF;
Debug.Assert(index >= 0 && index < hkeyNames.Length, "index is out of range!");
Debug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!");
bool isPerf = hKey == HKEY_PERFORMANCE_DATA;
// only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA.
SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf);
RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view);
key.checkMode = RegistryKeyPermissionCheck.Default;
key.keyName = hkeyNames[index];
return key;
}
/**
* Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with
* read-only access.
*
* @param name Name or path of subkey to open.
* @param readonly Set to <b>true</b> if you only need readonly access.
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
public RegistryKey OpenSubKey(string name, bool writable)
{
ValidateKeyName(name);
EnsureNotDisposed();
name = FixupName(name); // Fixup multiple slashes to a single slash
SafeRegistryHandle result = null;
int ret = Win32Native.RegOpenKeyEx(hkey,
name,
0,
GetRegistryKeyAccess(writable) | (int)regView,
out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
key.checkMode = GetSubKeyPermissonCheck(writable);
key.keyName = keyName + "\\" + name;
return key;
}
// Return null if we didn't find the key.
if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL)
{
// We need to throw SecurityException here for compatibility reasons,
// although UnauthorizedAccessException will make more sense.
ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);
}
return null;
}
/**
* Returns a subkey with read only permissions.
*
* @param name Name or path of subkey to open.
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
public RegistryKey OpenSubKey(String name)
{
return OpenSubKey(name, false);
}
/// <summary>
/// Retrieves an array of strings containing all the subkey names.
/// </summary>
public string[] GetSubKeyNames()
{
EnsureNotDisposed();
var names = new List<string>();
char[] name = ArrayPool<char>.Shared.Rent(MaxKeyLength + 1);
try
{
int result;
int nameLength = name.Length;
while ((result = Win32Native.RegEnumKeyEx(
hkey,
names.Count,
name,
ref nameLength,
null,
null,
null,
null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
switch (result)
{
case Interop.Errors.ERROR_SUCCESS:
names.Add(new string(name, 0, nameLength));
nameLength = name.Length;
break;
default:
// Throw the error
Win32Error(result, null);
break;
}
}
}
finally
{
ArrayPool<char>.Shared.Return(name);
}
return names.ToArray();
}
/// <summary>
/// Retrieves an array of strings containing all the value names.
/// </summary>
public unsafe string[] GetValueNames()
{
EnsureNotDisposed();
var names = new List<string>();
// Names in the registry aren't usually very long, although they can go to as large
// as 16383 characters (MaxValueLength).
//
// Every call to RegEnumValue will allocate another buffer to get the data from
// NtEnumerateValueKey before copying it back out to our passed in buffer. This can
// add up quickly- we'll try to keep the memory pressure low and grow the buffer
// only if needed.
char[] name = ArrayPool<char>.Shared.Rent(100);
try
{
int result;
int nameLength = name.Length;
while ((result = Win32Native.RegEnumValue(
hkey,
names.Count,
name,
ref nameLength,
IntPtr.Zero,
null,
null,
null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
switch (result)
{
// The size is only ever reported back correctly in the case
// of ERROR_SUCCESS. It will almost always be changed, however.
case Interop.Errors.ERROR_SUCCESS:
names.Add(new string(name, 0, nameLength));
break;
case Interop.Errors.ERROR_MORE_DATA:
if (IsPerfDataKey())
{
// Enumerating the values for Perf keys always returns
// ERROR_MORE_DATA, but has a valid name. Buffer does need
// to be big enough however. 8 characters is the largest
// known name. The size isn't returned, but the string is
// null terminated.
fixed (char* c = &name[0])
{
names.Add(new string(c));
}
}
else
{
char[] oldName = name;
int oldLength = oldName.Length;
name = null;
ArrayPool<char>.Shared.Return(oldName);
name = ArrayPool<char>.Shared.Rent(checked(oldLength * 2));
}
break;
default:
// Throw the error
Win32Error(result, null);
break;
}
// Always set the name length back to the buffer size
nameLength = name.Length;
}
}
finally
{
if (name != null)
ArrayPool<char>.Shared.Return(name);
}
return names.ToArray();
}
/**
* Retrieves the specified value. <b>null</b> is returned if the value
* doesn't exist.
*
* Note that <var>name</var> can be null or "", at which point the
* unnamed or default value of this Registry key is returned, if any.
*
* @param name Name of value to retrieve.
*
* @return the data associated with the value.
*/
public Object GetValue(String name)
{
return InternalGetValue(name, null, false, true);
}
/**
* Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist.
*
* Note that <var>name</var> can be null or "", at which point the
* unnamed or default value of this Registry key is returned, if any.
* The default values for RegistryKeys are OS-dependent. NT doesn't
* have them by default, but they can exist and be of any type.
*
* @param name Name of value to retrieve.
* @param defaultValue Value to return if <i>name</i> doesn't exist.
*
* @return the data associated with the value.
*/
public Object GetValue(String name, Object defaultValue)
{
return InternalGetValue(name, defaultValue, false, true);
}
public Object GetValue(String name, Object defaultValue, RegistryValueOptions options)
{
if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options));
}
bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames);
return InternalGetValue(name, defaultValue, doNotExpand, true);
}
internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity)
{
if (checkSecurity)
{
// Name can be null! It's the most common use of RegQueryValueEx
EnsureNotDisposed();
}
Object data = defaultValue;
int type = 0;
int datasize = 0;
int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
{
if (IsPerfDataKey())
{
int size = 65000;
int sizeInput = size;
int r;
byte[] blob = new byte[size];
while (Win32Native.ERROR_MORE_DATA == (r = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref sizeInput)))
{
if (size == Int32.MaxValue)
{
// ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue
Win32Error(r, name);
}
else if (size > (Int32.MaxValue / 2))
{
// at this point in the loop "size * 2" would cause an overflow
size = Int32.MaxValue;
}
else
{
size *= 2;
}
sizeInput = size;
blob = new byte[size];
}
if (r != 0)
Win32Error(r, name);
return blob;
}
else
{
// For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
// Some OS's returned ERROR_MORE_DATA even in success cases, so we
// want to continue on through the function.
if (ret != Win32Native.ERROR_MORE_DATA)
return data;
}
}
if (datasize < 0)
{
// unexpected code path
Debug.Fail("[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
datasize = 0;
}
switch (type)
{
case Win32Native.REG_NONE:
case Win32Native.REG_DWORD_BIG_ENDIAN:
case Win32Native.REG_BINARY:
{
byte[] blob = new byte[datasize];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
data = blob;
}
break;
case Win32Native.REG_QWORD:
{ // also REG_QWORD_LITTLE_ENDIAN
if (datasize > 8)
{
// prevent an AV in the edge case that datasize is larger than sizeof(long)
goto case Win32Native.REG_BINARY;
}
long blob = 0;
Debug.Assert(datasize == 8, "datasize==8");
// Here, datasize must be 8 when calling this
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Win32Native.REG_DWORD:
{ // also REG_DWORD_LITTLE_ENDIAN
if (datasize > 4)
{
// prevent an AV in the edge case that datasize is larger than sizeof(int)
goto case Win32Native.REG_QWORD;
}
int blob = 0;
Debug.Assert(datasize == 4, "datasize==4");
// Here, datasize must be four when calling this
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Win32Native.REG_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new String(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new String(blob);
}
}
break;
case Win32Native.REG_EXPAND_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new String(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new String(blob);
}
if (!doNotExpand)
data = Environment.ExpandEnvironmentVariables((String)data);
}
break;
case Win32Native.REG_MULTI_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
// make sure the string is null terminated before processing the data
if (blob.Length > 0 && blob[blob.Length - 1] != (char)0)
{
try
{
char[] newBlob = new char[checked(blob.Length + 1)];
for (int i = 0; i < blob.Length; i++)
{
newBlob[i] = blob[i];
}
newBlob[newBlob.Length - 1] = (char)0;
blob = newBlob;
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
blob[blob.Length - 1] = (char)0;
}
IList<String> strings = new List<String>();
int cur = 0;
int len = blob.Length;
while (ret == 0 && cur < len)
{
int nextNull = cur;
while (nextNull < len && blob[nextNull] != (char)0)
{
nextNull++;
}
if (nextNull < len)
{
Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
if (nextNull - cur > 0)
{
strings.Add(new String(blob, cur, nextNull - cur));
}
else
{
// we found an empty string. But if we're at the end of the data,
// it's just the extra null terminator.
if (nextNull != len - 1)
strings.Add(String.Empty);
}
}
else
{
strings.Add(new String(blob, cur, len - cur));
}
cur = nextNull + 1;
}
data = new String[strings.Count];
strings.CopyTo((String[])data, 0);
}
break;
case Win32Native.REG_LINK:
default:
break;
}
return data;
}
private bool IsSystemKey()
{
return (state & STATE_SYSTEMKEY) != 0;
}
private bool IsWritable()
{
return (state & STATE_WRITEACCESS) != 0;
}
private bool IsPerfDataKey()
{
return (state & STATE_PERF_DATA) != 0;
}
private void SetDirty()
{
state |= STATE_DIRTY;
}
/**
* Sets the specified value.
*
* @param name Name of value to store data in.
* @param value Data to store.
*/
public void SetValue(String name, Object value)
{
SetValue(name, value, RegistryValueKind.Unknown);
}
public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (name != null && name.Length > MaxValueLength)
{
throw new ArgumentException(SR.Arg_RegValStrLenBug);
}
if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind));
EnsureWriteable();
if (valueKind == RegistryValueKind.Unknown)
{
// this is to maintain compatibility with the old way of autodetecting the type.
// SetValue(string, object) will come through this codepath.
valueKind = CalculateValueKind(value);
}
int ret = 0;
try
{
switch (valueKind)
{
case RegistryValueKind.ExpandString:
case RegistryValueKind.String:
{
String data = value.ToString();
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
valueKind,
data,
checked(data.Length * 2 + 2));
break;
}
case RegistryValueKind.MultiString:
{
// Other thread might modify the input array after we calculate the buffer length.
// Make a copy of the input array to be safe.
string[] dataStrings = (string[])(((string[])value).Clone());
int sizeInBytes = 0;
// First determine the size of the array
//
for (int i = 0; i < dataStrings.Length; i++)
{
if (dataStrings[i] == null)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull);
}
sizeInBytes = checked(sizeInBytes + (dataStrings[i].Length + 1) * 2);
}
sizeInBytes = checked(sizeInBytes + 2);
byte[] basePtr = new byte[sizeInBytes];
fixed (byte* b = basePtr)
{
IntPtr currentPtr = new IntPtr((void*)b);
// Write out the strings...
//
for (int i = 0; i < dataStrings.Length; i++)
{
// Assumes that the Strings are always null terminated.
String.InternalCopy(dataStrings[i], currentPtr, (checked(dataStrings[i].Length * 2)));
currentPtr = new IntPtr((long)currentPtr + (checked(dataStrings[i].Length * 2)));
*(char*)(currentPtr.ToPointer()) = '\0';
currentPtr = new IntPtr((long)currentPtr + 2);
}
*(char*)(currentPtr.ToPointer()) = '\0';
currentPtr = new IntPtr((long)currentPtr + 2);
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.MultiString,
basePtr,
sizeInBytes);
}
break;
}
case RegistryValueKind.None:
case RegistryValueKind.Binary:
byte[] dataBytes = (byte[])value;
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
(valueKind == RegistryValueKind.None ? Win32Native.REG_NONE : RegistryValueKind.Binary),
dataBytes,
dataBytes.Length);
break;
case RegistryValueKind.DWord:
{
// We need to use Convert here because we could have a boxed type cannot be
// unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail.
int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.DWord,
ref data,
4);
break;
}
case RegistryValueKind.QWord:
{
long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.QWord,
ref data,
8);
break;
}
}
}
catch (OverflowException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
catch (InvalidOperationException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
catch (FormatException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
if (ret == 0)
{
SetDirty();
}
else
Win32Error(ret, null);
}
private RegistryValueKind CalculateValueKind(Object value)
{
// This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days.
// Even though we could add detection for an int64 in here, we want to maintain compatibility with the
// old behavior.
if (value is Int32)
return RegistryValueKind.DWord;
else if (value is Array)
{
if (value is byte[])
return RegistryValueKind.Binary;
else if (value is String[])
return RegistryValueKind.MultiString;
else
throw new ArgumentException(SR.Format(SR.Arg_RegSetBadArrType, value.GetType().Name));
}
else
return RegistryValueKind.String;
}
/**
* Retrieves a string representation of this key.
*
* @return a string representing the key.
*/
public override String ToString()
{
EnsureNotDisposed();
return keyName;
}
/**
* After calling GetLastWin32Error(), it clears the last error field,
* so you must save the HResult and pass it to this method. This method
* will determine the appropriate exception to throw dependent on your
* error, and depending on the error, insert a string into the message
* gotten from the ResourceManager.
*/
internal void Win32Error(int errorCode, String str)
{
switch (errorCode)
{
case Win32Native.ERROR_ACCESS_DENIED:
if (str != null)
throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str));
else
throw new UnauthorizedAccessException();
case Win32Native.ERROR_INVALID_HANDLE:
/**
* For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException.
* However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the
* SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues
* in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception
* on reentrant calls because of this error code path in RegistryKey
*
* Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this,
* however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on
* this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of
* having serialized access).
*/
if (!IsPerfDataKey())
{
hkey.SetHandleAsInvalid();
hkey = null;
}
goto default;
case Win32Native.ERROR_FILE_NOT_FOUND:
throw new IOException(SR.Arg_RegKeyNotFound, errorCode);
default:
throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode);
}
}
internal static String FixupName(String name)
{
Debug.Assert(name != null, "[FixupName]name!=null");
if (name.IndexOf('\\') == -1)
return name;
StringBuilder sb = new StringBuilder(name);
FixupPath(sb);
int temp = sb.Length - 1;
if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash
sb.Length = temp;
return sb.ToString();
}
private static void FixupPath(StringBuilder path)
{
Debug.Assert(path != null);
int length = path.Length;
bool fixup = false;
char markerChar = (char)0xFFFF;
int i = 1;
while (i < length - 1)
{
if (path[i] == '\\')
{
i++;
while (i < length)
{
if (path[i] == '\\')
{
path[i] = markerChar;
i++;
fixup = true;
}
else
break;
}
}
i++;
}
if (fixup)
{
i = 0;
int j = 0;
while (i < length)
{
if (path[i] == markerChar)
{
i++;
continue;
}
path[j] = path[i];
i++;
j++;
}
path.Length += j - i;
}
}
private void EnsureNotDisposed()
{
if (hkey == null)
{
ThrowHelper.ThrowObjectDisposedException(keyName, ExceptionResource.ObjectDisposed_RegKeyClosed);
}
}
private void EnsureWriteable()
{
EnsureNotDisposed();
if (!IsWritable())
{
ThrowHelper.ThrowUnauthorizedAccessException(ExceptionResource.UnauthorizedAccess_RegistryNoWrite);
}
}
private static int GetRegistryKeyAccess(bool isWritable)
{
int winAccess;
if (!isWritable)
{
winAccess = Win32Native.KEY_READ;
}
else
{
winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE;
}
return winAccess;
}
private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable)
{
if (checkMode == RegistryKeyPermissionCheck.Default)
{
return checkMode;
}
if (subkeyWritable)
{
return RegistryKeyPermissionCheck.ReadWriteSubTree;
}
else
{
return RegistryKeyPermissionCheck.ReadSubTree;
}
}
static private void ValidateKeyName(string name)
{
if (name == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name);
}
int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase);
int current = 0;
while (nextSlash != -1)
{
if ((nextSlash - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug);
current = nextSlash + 1;
nextSlash = name.IndexOf("\\", current, StringComparison.OrdinalIgnoreCase);
}
if ((name.Length - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug);
}
static private void ValidateKeyView(RegistryView view)
{
if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryViewCheck, ExceptionArgument.view);
}
}
// Win32 constants for error handling
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
}
[Flags]
internal enum RegistryValueOptions
{
None = 0,
DoNotExpandEnvironmentNames = 1
}
// the name for this API is meant to mimic FileMode, which has similar values
internal enum RegistryKeyPermissionCheck
{
Default = 0,
ReadSubTree = 1,
ReadWriteSubTree = 2
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security;
using Newtonsoft.Json.Utilities;
using Windows.Data.Json;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="IJsonValue"/> to and from JSON.
/// </summary>
public class JsonValueConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
WriteJsonValue(writer, (IJsonValue)value);
}
private void WriteJsonValue(JsonWriter writer, IJsonValue value)
{
switch (value.ValueType)
{
case JsonValueType.Array:
{
JsonArray a = value.GetArray();
writer.WriteStartArray();
for (int i = 0; i < a.Count; i++)
{
WriteJsonValue(writer, a[i]);
}
writer.WriteEndArray();
}
break;
case JsonValueType.Boolean:
{
writer.WriteValue(value.GetBoolean());
}
break;
case JsonValueType.Null:
{
writer.WriteNull();
}
break;
case JsonValueType.Number:
{
// JsonValue doesn't support integers
// serialize whole numbers without a decimal point
double d = value.GetNumber();
bool isInteger = (d % 1 == 0);
if (isInteger && d <= long.MaxValue && d >= long.MinValue)
writer.WriteValue(Convert.ToInt64(d));
else
writer.WriteValue(d);
}
break;
case JsonValueType.Object:
{
JsonObject o = value.GetObject();
writer.WriteStartObject();
foreach (KeyValuePair<string, IJsonValue> v in o)
{
writer.WritePropertyName(v.Key);
WriteJsonValue(writer, v.Value);
}
writer.WriteEndObject();
}
break;
case JsonValueType.String:
{
writer.WriteValue(value.GetString());
}
break;
default:
throw new ArgumentOutOfRangeException("ValueType");
}
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.None)
reader.Read();
IJsonValue value = CreateJsonValue(reader);
if (!objectType.IsAssignableFrom(value.GetType()))
throw JsonSerializationException.Create(reader, "Could not convert '{0}' to '{1}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), objectType));
return value;
}
private IJsonValue CreateJsonValue(JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment)
{
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
{
return CreateJsonObject(reader);
}
case JsonToken.StartArray:
{
JsonArray a = new JsonArray();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.EndArray:
return a;
default:
IJsonValue value = CreateJsonValue(reader);
a.Add(value);
break;
}
}
}
break;
case JsonToken.Integer:
case JsonToken.Float:
return JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
case JsonToken.String:
return JsonValue.CreateStringValue(reader.Value.ToString());
case JsonToken.Boolean:
return JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
case JsonToken.Null:
// surely there is a better way to create a null value than this?
return JsonValue.Parse("null");
case JsonToken.Date:
return JsonValue.CreateStringValue(reader.Value.ToString());
case JsonToken.Bytes:
return JsonValue.CreateStringValue(reader.Value.ToString());
default:
throw JsonSerializationException.Create(reader, "Unexpected or unsupported token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
private JsonObject CreateJsonObject(JsonReader reader)
{
JsonObject o = new JsonObject();
string propertyName = null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
propertyName = (string)reader.Value;
break;
case JsonToken.EndObject:
return o;
case JsonToken.Comment:
break;
default:
IJsonValue propertyValue = CreateJsonValue(reader);
o.Add(propertyName, propertyValue);
break;
}
}
throw JsonSerializationException.Create(reader, "Unexpected end.");
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return typeof(IJsonValue).IsAssignableFrom(objectType);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace Geocoding.MapQuest
{
/// <remarks>
/// <see cref="http://open.mapquestapi.com/geocoding/"/>
/// <seealso cref="http://developer.mapquest.com/"/>
/// </remarks>
public class MapQuestGeocoder : IGeocoder, IBatchGeocoder
{
readonly string key;
volatile bool useOSM;
/// <summary>
/// When true, will use the Open Street Map API
/// </summary>
public virtual bool UseOSM
{
get { return useOSM; }
set { useOSM = value; }
}
public IWebProxy Proxy { get; set; }
public MapQuestGeocoder(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("key can not be null or blank");
this.key = key;
}
IEnumerable<Address> HandleSingleResponse(MapQuestResponse res)
{
if (res != null && !res.Results.IsNullOrEmpty())
{
return HandleSingleResponse(from r in res.Results
where r != null && !r.Locations.IsNullOrEmpty()
from l in r.Locations
select l);
}
else
return new Address[0];
}
IEnumerable<Address> HandleSingleResponse(IEnumerable<MapQuestLocation> locs)
{
if (locs == null)
return new Address[0];
else
{
return from l in locs
where l != null && l.Quality < Quality.COUNTRY
let q = (int)l.Quality
let c = string.IsNullOrWhiteSpace(l.Confidence) ? "ZZZZZZ" : l.Confidence
orderby q ascending, c ascending
select l;
}
}
public IEnumerable<Address> Geocode(string address)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentException("address can not be null or empty!");
var f = new GeocodeRequest(key, address) { UseOSM = this.UseOSM };
MapQuestResponse res = Execute(f);
return HandleSingleResponse(res);
}
public IEnumerable<Address> Geocode(string street, string city, string state, string postalCode, string country)
{
var sb = new StringBuilder ();
if (!string.IsNullOrWhiteSpace (street))
sb.AppendFormat ("{0}, ", street);
if (!string.IsNullOrWhiteSpace (city))
sb.AppendFormat ("{0}, ", city);
if (!string.IsNullOrWhiteSpace (state))
sb.AppendFormat ("{0} ", state);
if (!string.IsNullOrWhiteSpace (postalCode))
sb.AppendFormat ("{0} ", postalCode);
if (!string.IsNullOrWhiteSpace (country))
sb.AppendFormat ("{0} ", country);
if (sb.Length > 1)
sb.Length--;
string s = sb.ToString ().Trim ();
if (string.IsNullOrWhiteSpace (s))
throw new ArgumentException ("Concatenated input values can not be null or blank");
if (s.Last () == ',')
s = s.Remove (s.Length - 1);
return Geocode (s);
}
public IEnumerable<Address> ReverseGeocode(Location location)
{
if (location == null)
throw new ArgumentNullException ("location");
var f = new ReverseGeocodeRequest(key, location) { UseOSM = this.UseOSM };
MapQuestResponse res = Execute(f);
return HandleSingleResponse(res);
}
public IEnumerable<Address> ReverseGeocode(double latitude, double longitude)
{
return ReverseGeocode(new Location(latitude, longitude));
}
public MapQuestResponse Execute(BaseRequest f)
{
HttpWebRequest request = Send(f);
MapQuestResponse r = Parse(request);
if (r != null && !r.Results.IsNullOrEmpty())
{
foreach (MapQuestResult o in r.Results)
{
if (o == null)
continue;
foreach (MapQuestLocation l in o.Locations)
{
if (!string.IsNullOrWhiteSpace(l.FormattedAddress) || o.ProvidedLocation == null)
continue;
if (string.Compare(o.ProvidedLocation.FormattedAddress, "unknown", true) != 0)
l.FormattedAddress = o.ProvidedLocation.FormattedAddress;
else
l.FormattedAddress = o.ProvidedLocation.ToString();
}
}
}
return r;
}
HttpWebRequest Send(BaseRequest f)
{
if (f == null)
throw new ArgumentNullException("f");
HttpWebRequest request;
bool hasBody = false;
switch (f.RequestVerb)
{
case "GET":
case "DELETE":
case "HEAD":
{
var u = string.Format("{0}json={1}&", f.RequestUri, HttpUtility.UrlEncode(f.RequestBody));
request = WebRequest.Create(u) as HttpWebRequest;
}
break;
case "POST":
case "PUT":
default:
{
request = WebRequest.Create(f.RequestUri) as HttpWebRequest;
hasBody = !string.IsNullOrWhiteSpace(f.RequestBody);
}
break;
}
request.Method = f.RequestVerb;
request.ContentType = "application/" + f.InputFormat;
request.Expect = "application/" + f.OutputFormat;
if (Proxy != null)
request.Proxy = Proxy;
if (hasBody)
{
byte[] buffer = Encoding.UTF8.GetBytes(f.RequestBody);
request.ContentLength = buffer.Length;
using (Stream rs = request.GetRequestStream())
{
rs.Write(buffer, 0, buffer.Length);
rs.Flush();
rs.Close();
}
}
return request;
}
MapQuestResponse Parse(HttpWebRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
string requestInfo = string.Format("[{0}] {1}", request.Method, request.RequestUri);
try
{
string json;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if ((int)response.StatusCode >= 300) //error
throw new HttpException((int)response.StatusCode, response.StatusDescription);
using (var sr = new StreamReader(response.GetResponseStream()))
json = sr.ReadToEnd();
}
if (string.IsNullOrWhiteSpace(json))
throw new ApplicationException("Remote system response with blank: " + requestInfo);
MapQuestResponse o = json.FromJSON<MapQuestResponse>();
if (o == null)
throw new ApplicationException("Unable to deserialize remote response: " + requestInfo + " => " + json);
return o;
}
catch (WebException wex) //convert to simple exception & close the response stream
{
using (HttpWebResponse response = wex.Response as HttpWebResponse)
{
var sb = new StringBuilder(requestInfo);
sb.Append(" | ");
sb.Append(response.StatusDescription);
sb.Append(" | ");
using (var sr = new StreamReader(response.GetResponseStream()))
{
sb.Append(sr.ReadToEnd());
}
throw new HttpException((int)response.StatusCode, sb.ToString());
}
}
}
public IEnumerable<ResultItem> Geocode(IEnumerable<string> addresses)
{
if (addresses == null)
throw new ArgumentNullException("addresses");
string[] adr = (from a in addresses
where !string.IsNullOrWhiteSpace(a)
group a by a into ag
select ag.Key).ToArray();
if (adr.IsNullOrEmpty())
throw new ArgumentException("Atleast one none blank item is required in addresses");
var f = new BatchGeocodeRequest(key, adr) { UseOSM = this.UseOSM };
MapQuestResponse res = Execute(f);
return HandleBatchResponse(res);
}
ICollection<ResultItem> HandleBatchResponse(MapQuestResponse res)
{
if (res != null && !res.Results.IsNullOrEmpty())
{
return (from r in res.Results
where r != null && !r.Locations.IsNullOrEmpty()
let resp = HandleSingleResponse(r.Locations)
where resp != null
select new ResultItem(r.ProvidedLocation, resp)).ToArray();
}
else
return new ResultItem[0];
}
public IEnumerable<ResultItem> ReverseGeocode(IEnumerable<Location> locations)
{
throw new NotSupportedException("ReverseGeocode(...) is not available for MapQuestGeocoder.");
}
}
}
| |
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
using umbraco.editorControls.tinymce;
using umbraco.editorControls.tinyMCE3.webcontrol;
using umbraco.editorControls.wysiwyg;
using umbraco.interfaces;
using Umbraco.Core.IO;
using umbraco.presentation;
using umbraco.uicontrols;
namespace umbraco.editorControls.tinyMCE3
{
[Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")]
public class TinyMCE : TinyMCEWebControl, IDataEditor, IMenuElement
{
private readonly string _activateButtons = "";
private readonly string _advancedUsers = "";
private readonly SortedList _buttons = new SortedList();
private readonly IData _data;
private readonly string _disableButtons = "help,visualaid,";
private readonly string _editorButtons = "";
private readonly bool _enableContextMenu;
private readonly bool _fullWidth;
private readonly int _height;
private readonly SortedList _mceButtons = new SortedList();
private readonly ArrayList _menuIcons = new ArrayList();
private readonly bool _showLabel;
private readonly ArrayList _stylesheets = new ArrayList();
private readonly int _width;
private readonly int m_maxImageWidth = 500;
private bool _isInitialized;
private string _plugins = "";
public TinyMCE(IData Data, string Configuration)
{
_data = Data;
try
{
string[] configSettings = Configuration.Split("|".ToCharArray());
if (configSettings.Length > 0)
{
_editorButtons = configSettings[0];
if (configSettings.Length > 1)
if (configSettings[1] == "1")
_enableContextMenu = true;
if (configSettings.Length > 2)
_advancedUsers = configSettings[2];
if (configSettings.Length > 3)
{
if (configSettings[3] == "1")
_fullWidth = true;
else if (configSettings[4].Split(',').Length > 1)
{
_width = int.Parse(configSettings[4].Split(',')[0]);
_height = int.Parse(configSettings[4].Split(',')[1]);
}
}
// default width/height
if (_width < 1)
_width = 500;
if (_height < 1)
_height = 400;
// add stylesheets
if (configSettings.Length > 4)
{
foreach (string s in configSettings[5].Split(",".ToCharArray()))
_stylesheets.Add(s);
}
if (configSettings.Length > 6 && configSettings[6] != "")
_showLabel = bool.Parse(configSettings[6]);
if (configSettings.Length > 7 && configSettings[7] != "")
m_maxImageWidth = int.Parse(configSettings[7]);
// sizing
if (!_fullWidth)
{
config.Add("width", _width.ToString());
config.Add("height", _height.ToString());
}
if (_enableContextMenu)
_plugins += ",contextmenu";
// If the editor is used in umbraco, use umbraco's own toolbar
bool onFront = false;
if (GlobalSettings.RequestIsInUmbracoApplication(HttpContext.Current))
{
config.Add("theme_umbraco_toolbar_location", "external");
config.Add("skin", "umbraco");
config.Add("inlinepopups_skin ", "umbraco");
}
else
{
onFront = true;
config.Add("theme_umbraco_toolbar_location", "top");
}
// load plugins
IDictionaryEnumerator pluginEnum = tinyMCEConfiguration.Plugins.GetEnumerator();
while (pluginEnum.MoveNext())
{
var plugin = (tinyMCEPlugin)pluginEnum.Value;
if (plugin.UseOnFrontend || (!onFront && !plugin.UseOnFrontend))
_plugins += "," + plugin.Name;
}
// add the umbraco overrides to the end
// NB: It is !!REALLY IMPORTANT!! that these plugins are added at the end
// as they make runtime modifications to default plugins, so require
// those plugins to be loaded first.
_plugins += ",umbracopaste,umbracolink,umbracocontextmenu";
if (_plugins.StartsWith(","))
_plugins = _plugins.Substring(1, _plugins.Length - 1);
if (_plugins.EndsWith(","))
_plugins = _plugins.Substring(0, _plugins.Length - 1);
config.Add("plugins", _plugins);
// Check advanced settings
if (UmbracoEnsuredPage.CurrentUser != null && ("," + _advancedUsers + ",").IndexOf("," + UmbracoEnsuredPage.CurrentUser.UserType.Id + ",") >
-1)
config.Add("umbraco_advancedMode", "true");
else
config.Add("umbraco_advancedMode", "false");
// Check maximum image width
config.Add("umbraco_maximumDefaultImageWidth", m_maxImageWidth.ToString());
// Styles
string cssFiles = String.Empty;
string styles = string.Empty;
foreach (string styleSheetId in _stylesheets)
{
if (styleSheetId.Trim() != "")
try
{
//TODO: Fix this, it will no longer work!
var s = StyleSheet.GetStyleSheet(int.Parse(styleSheetId), false, false);
if (s.nodeObjectType == StyleSheet.ModuleObjectType)
{
cssFiles += IOHelper.ResolveUrl(SystemDirectories.Css + "/" + s.Text + ".css");
foreach (StylesheetProperty p in s.Properties)
{
if (styles != string.Empty)
styles += ";";
styles += p.Text + "=" + p.Alias;
}
cssFiles += ",";
}
}
catch (Exception ee)
{
LogHelper.Error<TinyMCE>("Error adding stylesheet to tinymce Id:" + styleSheetId, ee);
}
}
// remove any ending comma (,)
if (!string.IsNullOrEmpty(cssFiles))
{
cssFiles = cssFiles.TrimEnd(',');
}
// language
string userLang = (UmbracoEnsuredPage.CurrentUser != null) ?
(User.GetCurrent().Language.Contains("-") ?
User.GetCurrent().Language.Substring(0, User.GetCurrent().Language.IndexOf("-")) : User.GetCurrent().Language)
: "en";
config.Add("language", userLang);
config.Add("content_css", cssFiles);
config.Add("theme_umbraco_styles", styles);
// Add buttons
IDictionaryEnumerator ide = tinyMCEConfiguration.Commands.GetEnumerator();
while (ide.MoveNext())
{
var cmd = (tinyMCECommand)ide.Value;
if (_editorButtons.IndexOf("," + cmd.Alias + ",") > -1)
_activateButtons += cmd.Alias + ",";
else
_disableButtons += cmd.Alias + ",";
}
if (_activateButtons.Length > 0)
_activateButtons = _activateButtons.Substring(0, _activateButtons.Length - 1);
if (_disableButtons.Length > 0)
_disableButtons = _disableButtons.Substring(0, _disableButtons.Length - 1);
// Add buttons
initButtons();
_activateButtons = "";
int separatorPriority = 0;
ide = _mceButtons.GetEnumerator();
while (ide.MoveNext())
{
string mceCommand = ide.Value.ToString();
var curPriority = (int)ide.Key;
// Check priority
if (separatorPriority > 0 &&
Math.Floor(decimal.Parse(curPriority.ToString()) / 10) >
Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10))
_activateButtons += "separator,";
_activateButtons += mceCommand + ",";
separatorPriority = curPriority;
}
config.Add("theme_umbraco_buttons1", _activateButtons);
config.Add("theme_umbraco_buttons2", "");
config.Add("theme_umbraco_buttons3", "");
config.Add("theme_umbraco_toolbar_align", "left");
config.Add("theme_umbraco_disable", _disableButtons);
config.Add("theme_umbraco_path ", "true");
config.Add("extended_valid_elements", "div[*]");
config.Add("document_base_url", "/");
config.Add("relative_urls", "false");
config.Add("remove_script_host", "true");
config.Add("event_elements", "div");
config.Add("paste_auto_cleanup_on_paste", "true");
config.Add("valid_elements",
tinyMCEConfiguration.ValidElements.Substring(1,
tinyMCEConfiguration.ValidElements.Length -
2));
config.Add("invalid_elements", tinyMCEConfiguration.InvalidElements);
// custom commands
if (tinyMCEConfiguration.ConfigOptions.Count > 0)
{
ide = tinyMCEConfiguration.ConfigOptions.GetEnumerator();
while (ide.MoveNext())
{
config.Add(ide.Key.ToString(), ide.Value.ToString());
}
}
//if (HttpContext.Current.Request.Path.IndexOf(Umbraco.Core.IO.SystemDirectories.Umbraco) > -1)
// config.Add("language", User.GetUser(BasePage.GetUserId(BasePage.umbracoUserContextID)).Language);
//else
// config.Add("language", System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName);
if (_fullWidth)
{
config.Add("auto_resize", "true");
base.Columns = 30;
base.Rows = 30;
}
else
{
base.Columns = 0;
base.Rows = 0;
}
EnableViewState = false;
}
}
catch (Exception ex)
{
throw new ArgumentException("Incorrect TinyMCE configuration.", "Configuration", ex);
}
}
#region TreatAsRichTextEditor
public virtual bool TreatAsRichTextEditor
{
get { return false; }
}
#endregion
#region ShowLabel
public virtual bool ShowLabel
{
get { return _showLabel; }
}
#endregion
#region Editor
public Control Editor
{
get { return this; }
}
#endregion
#region Save()
public virtual void Save()
{
string parsedString = base.Text.Trim();
string parsedStringForTinyMce = parsedString;
if (parsedString != string.Empty)
{
parsedString = replaceMacroTags(parsedString).Trim();
// tidy html - refactored, see #30534
if (UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent)
{
// always wrap in a <div> - using <p> was a bad idea
parsedString = "<div>" + parsedString + "</div>";
string tidyTxt = library.Tidy(parsedString, false);
if (tidyTxt != "[error]")
{
parsedString = tidyTxt;
// remove pesky \r\n, and other empty chars
parsedString = parsedString.Trim(new char[] { '\r', '\n', '\t', ' ' });
// compensate for breaking macro tags by tidy (?)
parsedString = parsedString.Replace("/?>", "/>");
// remove the wrapping <div> - safer to check that it is still here
if (parsedString.StartsWith("<div>") && parsedString.EndsWith("</div>"))
parsedString = parsedString.Substring("<div>".Length, parsedString.Length - "<div></div>".Length);
}
}
// rescue umbraco tags
parsedString = parsedString.Replace("|||?", "<?").Replace("/|||", "/>").Replace("|*|", "\"");
// fix images
parsedString = tinyMCEImageHelper.cleanImages(parsedString);
// parse current domain and instances of slash before anchor (to fix anchor bug)
// NH 31-08-2007
if (HttpContext.Current.Request.ServerVariables != null)
{
parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current) + "/#", "#");
parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current), "");
}
// if a paragraph is empty, remove it
if (parsedString.ToLower() == "<p></p>")
parsedString = "";
// save string after all parsing is done, but before CDATA replacement - to put back into TinyMCE
parsedStringForTinyMce = parsedString;
//Allow CDATA nested into RTE without exceptions
// GE 2012-01-18
parsedString = parsedString.Replace("<![CDATA[", "<!--CDATAOPENTAG-->").Replace("]]>", "<!--CDATACLOSETAG-->");
}
_data.Value = parsedString;
// update internal webcontrol value with parsed result
base.Text = parsedStringForTinyMce;
}
#endregion
public virtual string Plugins
{
get { return _plugins; }
set { _plugins = value; }
}
public object[] MenuIcons
{
get
{
initButtons();
var tempIcons = new object[_menuIcons.Count];
for (int i = 0; i < _menuIcons.Count; i++)
tempIcons[i] = _menuIcons[i];
return tempIcons;
}
}
#region IMenuElement Members
public string ElementName
{
get { return "div"; }
}
public string ElementIdPreFix
{
get { return "umbTinymceMenu"; }
}
public string ElementClass
{
get { return "tinymceMenuBar"; }
}
public int ExtraMenuWidth
{
get
{
initButtons();
return _buttons.Count * 40 + 300;
}
}
#endregion
protected override void OnLoad(EventArgs e)
{
try
{
// add current page info
base.NodeId = ((cms.businesslogic.datatype.DefaultData)_data).NodeId;
if (NodeId != 0)
{
base.VersionId = ((cms.businesslogic.datatype.DefaultData)_data).Version;
config.Add("theme_umbraco_pageId", base.NodeId.ToString());
config.Add("theme_umbraco_versionId", base.VersionId.ToString());
// we'll need to make an extra check for the liveediting as that value is set after the constructor have initialized
config.Add("umbraco_toolbar_id",
ElementIdPreFix +
((cms.businesslogic.datatype.DefaultData)_data).PropertyId);
}
else
{
// this is for use when tinymce is used for non default Umbraco pages
config.Add("umbraco_toolbar_id",
ElementIdPreFix + "_" + this.ClientID);
}
}
catch
{
// Empty catch as this is caused by the document doesn't exists yet,
// like when using this on an autoform, partly replaced by the if/else check on nodeId above though
}
base.OnLoad(e);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Allow CDATA nested into RTE without exceptions
// GE 2012-01-18
if (_data != null && _data.Value != null)
base.Text = _data.Value.ToString().Replace("<!--CDATAOPENTAG-->", "<![CDATA[").Replace("<!--CDATACLOSETAG-->", "]]>");
}
private string replaceMacroTags(string text)
{
while (findStartTag(text) > -1)
{
string result = text.Substring(findStartTag(text), findEndTag(text) - findStartTag(text));
text = text.Replace(result, generateMacroTag(result));
}
return text;
}
private string generateMacroTag(string macroContent)
{
string macroAttr = macroContent.Substring(5, macroContent.IndexOf(">") - 5);
string macroTag = "|||?UMBRACO_MACRO ";
Hashtable attributes = ReturnAttributes(macroAttr);
IDictionaryEnumerator ide = attributes.GetEnumerator();
while (ide.MoveNext())
{
if (ide.Key.ToString().IndexOf("umb_") != -1)
{
// Hack to compensate for Firefox adding all attributes as lowercase
string orgKey = ide.Key.ToString();
if (orgKey == "umb_macroalias")
orgKey = "umb_macroAlias";
macroTag += orgKey.Substring(4, orgKey.Length - 4) + "=|*|" +
ide.Value.ToString().Replace("\\r\\n", Environment.NewLine) + "|*| ";
}
}
macroTag += "/|||";
return macroTag;
}
[Obsolete("Has been superceded by Umbraco.Core.XmlHelper.GetAttributesFromElement")]
public static Hashtable ReturnAttributes(String tag)
{
var h = new Hashtable();
foreach (var i in Umbraco.Core.XmlHelper.GetAttributesFromElement(tag))
{
h.Add(i.Key, i.Value);
}
return h;
}
private int findStartTag(string text)
{
string temp = "";
text = text.ToLower();
if (text.IndexOf("ismacro=\"true\"") > -1)
{
temp = text.Substring(0, text.IndexOf("ismacro=\"true\""));
return temp.LastIndexOf("<");
}
return -1;
}
private int findEndTag(string text)
{
string find = "<!-- endumbmacro -->";
int endMacroIndex = text.ToLower().IndexOf(find);
string tempText = text.ToLower().Substring(endMacroIndex + find.Length,
text.Length - endMacroIndex - find.Length);
int finalEndPos = 0;
while (tempText.Length > 5)
if (tempText.Substring(finalEndPos, 6) == "</div>")
break;
else
finalEndPos++;
return endMacroIndex + find.Length + finalEndPos + 6;
}
private void initButtons()
{
if (!_isInitialized)
{
_isInitialized = true;
// Add icons for the editor control:
// Html
// Preview
// Style picker, showstyles
// Bold, italic, Text Gen
// Align: left, center, right
// Lists: Bullet, Ordered, indent, undo indent
// Link, Anchor
// Insert: Image, macro, table, formular
foreach (string button in _activateButtons.Split(','))
{
if (button.Trim() != "")
{
try
{
var cmd = (tinyMCECommand)tinyMCEConfiguration.Commands[button];
string appendValue = "";
if (cmd.Value != "")
appendValue = ", '" + cmd.Value + "'";
_mceButtons.Add(cmd.Priority, cmd.Command);
_buttons.Add(cmd.Priority,
new editorButton(cmd.Alias, ui.Text("buttons", cmd.Alias), cmd.Icon,
"tinyMCE.execInstanceCommand('" + ClientID + "', '" +
cmd.Command + "', " + cmd.UserInterface + appendValue + ")"));
}
catch (Exception ee)
{
LogHelper.Error<TinyMCE>(string.Format("TinyMCE: Error initializing button '{0}'", button), ee);
}
}
}
// add save icon
int separatorPriority = 0;
IDictionaryEnumerator ide = _buttons.GetEnumerator();
while (ide.MoveNext())
{
object buttonObj = ide.Value;
var curPriority = (int)ide.Key;
// Check priority
if (separatorPriority > 0 &&
Math.Floor(decimal.Parse(curPriority.ToString()) / 10) >
Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10))
_menuIcons.Add("|");
try
{
var e = (editorButton)buttonObj;
MenuIconI menuItem = new MenuIconClass();
menuItem.OnClickCommand = e.onClickCommand;
menuItem.ImageURL = e.imageUrl;
menuItem.AltText = e.alttag;
menuItem.ID = e.id;
_menuIcons.Add(menuItem);
}
catch
{
}
separatorPriority = curPriority;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
/// <summary>
/// Cache FileCodeModel instances for a given project (we are using WeakReference for now,
/// so that we can more or less match the semantics of the former native implementation, which
/// offered reference equality until all instances were collected by the GC)
/// </summary>
internal sealed partial class CodeModelProjectCache
{
private readonly CodeModelState _state;
private readonly AbstractProject _project;
private readonly Dictionary<string, CacheEntry> _cache = new Dictionary<string, CacheEntry>(StringComparer.OrdinalIgnoreCase);
private readonly object _cacheGate = new object();
private EnvDTE.CodeModel _rootCodeModel;
private bool _zombied;
internal CodeModelProjectCache(AbstractProject project, IServiceProvider serviceProvider, HostLanguageServices languageServices, VisualStudioWorkspace workspace)
{
_project = project;
_state = new CodeModelState(serviceProvider, languageServices, workspace);
}
private bool IsZombied
{
get { return _zombied; }
}
/// <summary>
/// Look for an existing instance of FileCodeModel in our cache.
/// Return null if there is no active FCM for "fileName".
/// </summary>
private CacheEntry? GetCacheEntry(string fileName)
{
lock (_cacheGate)
{
CacheEntry cacheEntry;
if (_cache.TryGetValue(fileName, out cacheEntry))
{
return cacheEntry;
}
}
return null;
}
public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath)
{
// First try
{
var cacheEntry = GetCacheEntry(filePath);
if (cacheEntry != null)
{
var comHandle = cacheEntry.Value.ComHandle;
if (comHandle != null)
{
return comHandle.Value;
}
}
}
// This ultimately ends up calling GetOrCreateFileCodeModel(fileName, parent) with the correct "parent" object
// through the project system.
var provider = (IProjectCodeModelProvider)_project;
var newFileCodeModel = (EnvDTE80.FileCodeModel2)provider.ProjectCodeModel.CreateFileCodeModelThroughProject(filePath);
return new ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(newFileCodeModel);
}
public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? GetComHandleForFileCodeModel(string filePath)
{
var cacheEntry = GetCacheEntry(filePath);
return cacheEntry != null
? cacheEntry.Value.ComHandle
: null;
}
public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath, object parent)
{
// First try
{
var cacheEntry = GetCacheEntry(filePath);
if (cacheEntry != null)
{
var comHandle = cacheEntry.Value.ComHandle;
if (comHandle != null)
{
return comHandle.Value;
}
}
}
// Check that we know about this file!
var hostDocument = _project.GetCurrentDocumentFromPath(filePath);
if (hostDocument == null)
{
// Matches behavior of native (C#) implementation
throw Exceptions.ThrowENotImpl();
}
// Create object (outside of lock)
var newFileCodeModel = FileCodeModel.Create(_state, parent, hostDocument.Id, new TextManagerAdapter());
var newCacheEntry = new CacheEntry(newFileCodeModel);
// Second try (object might have been added by another thread at this point!)
lock (_cacheGate)
{
var cacheEntry = GetCacheEntry(filePath);
if (cacheEntry != null)
{
var comHandle = cacheEntry.Value.ComHandle;
if (comHandle != null)
{
return comHandle.Value;
}
}
// Note: Using the indexer here (instead of "Add") is relevant since the old
// WeakReference entry is likely still in the cache (with a Null target, of course)
_cache[filePath] = newCacheEntry;
return newFileCodeModel;
}
}
public EnvDTE.CodeModel GetOrCreateRootCodeModel(EnvDTE.Project parent)
{
if (this.IsZombied)
{
Debug.Fail("Cannot access root code model after code model was shutdown!");
throw Exceptions.ThrowEUnexpected();
}
if (_rootCodeModel == null)
{
_rootCodeModel = RootCodeModel.Create(_state, parent, _project.Id);
}
return _rootCodeModel;
}
public IEnumerable<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>> GetFileCodeModelInstances()
{
var result = new List<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>>();
lock (_cacheGate)
{
foreach (var cacheEntry in _cache.Values)
{
var comHandle = cacheEntry.ComHandle;
if (comHandle != null)
{
result.Add(comHandle.Value);
}
}
}
return result;
}
public void OnProjectClosed()
{
var instances = GetFileCodeModelInstances();
lock (_cacheGate)
{
_cache.Clear();
}
foreach (var instance in instances)
{
instance.Object.Shutdown();
}
_zombied = false;
}
public void OnSourceFileRemoved(string fileName)
{
ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandle = null;
lock (_cacheGate)
{
CacheEntry cacheEntry;
if (_cache.TryGetValue(fileName, out cacheEntry))
{
comHandle = cacheEntry.ComHandle;
_cache.Remove(fileName);
}
}
if (comHandle != null)
{
comHandle.Value.Object.Shutdown();
}
}
public void OnSourceFileRenaming(string oldFileName, string newFileName)
{
ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToRename = null;
ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToShutDown = null;
lock (_cacheGate)
{
CacheEntry cacheEntry;
if (_cache.TryGetValue(oldFileName, out cacheEntry))
{
comHandleToRename = cacheEntry.ComHandle;
_cache.Remove(oldFileName);
if (comHandleToRename != null)
{
// We might already have a code model for this new filename. This can happen if
// we were to rename Foo.cs to Foocs, which will call this method, and then rename
// it back, which does not call this method. This results in both Foo.cs and Foocs
// being in the cache. We could fix that "correctly", but the zombied Foocs code model
// is pretty broken, so there's no point in trying to reuse it.
if (_cache.TryGetValue(newFileName, out cacheEntry))
{
comHandleToShutDown = cacheEntry.ComHandle;
}
_cache.Add(newFileName, cacheEntry);
}
}
}
comHandleToShutDown?.Object.Shutdown();
comHandleToRename?.Object.OnRename(newFileName);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Security.Policy;
namespace System.Runtime.InteropServices
{
[GuidAttribute("BEBB2505-8B54-3443-AEAD-142A16DD9CC7")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.AssemblyBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _AssemblyBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("ED3E4384-D7E2-3FA7-8FFD-8940D330519A")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ConstructorBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ConstructorBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("BE9ACCE8-AAFF-3B91-81AE-8211663F5CAD")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.CustomAttributeBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _CustomAttributeBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("C7BD73DE-9F85-3290-88EE-090B8BDFE2DF")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EnumBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _EnumBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("AADABA99-895D-3D65-9760-B1F12621FAE8")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EventBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _EventBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("CE1A3BF5-975E-30CC-97C9-1EF70F8F3993")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.FieldBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _FieldBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("A4924B27-6E3B-37F7-9B83-A4501955E6A7")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ILGenerator))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ILGenerator
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("4E6350D1-A08B-3DEC-9A3E-C465F9AEEC0C")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.LocalBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _LocalBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("007D8A14-FDF3-363E-9A0B-FEC0618260A2")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
#if FEATURE_METHOD_RENTAL
[GuidAttribute("C2323C25-F57F-3880-8A4D-12EBEA7A5852")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodRental))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodRental
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
#endif
[GuidAttribute("D05FFA9A-04AF-3519-8EE1-8D93AD73430B")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ModuleBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ModuleBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("36329EBA-F97A-3565-BC07-0ED5C6EF19FC")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ParameterBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ParameterBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("15F9A479-9397-3A63-ACBD-F51977FB0F02")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.PropertyBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _PropertyBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("7D13DD37-5A04-393C-BBCA-A5FEA802893D")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.SignatureHelper))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _SignatureHelper
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
[GuidAttribute("7E5678EE-48B3-3F83-B076-C58543498A58")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.TypeBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _TypeBuilder
{
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="LegacyAvailabilityTimeZone.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the LegacyAvailabilityTimeZone class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents a time zone as used by GetUserAvailabilityRequest.
/// </summary>
internal sealed class LegacyAvailabilityTimeZone : ComplexProperty
{
private TimeSpan bias;
private LegacyAvailabilityTimeZoneTime standardTime;
private LegacyAvailabilityTimeZoneTime daylightTime;
/// <summary>
/// Initializes a new instance of the <see cref="LegacyAvailabilityTimeZone"/> class.
/// </summary>
internal LegacyAvailabilityTimeZone()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LegacyAvailabilityTimeZone"/> class.
/// </summary>
/// <param name="timeZoneInfo">The time zone used to initialize this instance.</param>
internal LegacyAvailabilityTimeZone(TimeZoneInfo timeZoneInfo)
: this()
{
// Availability uses the opposite sign for the bias, e.g. if TimeZoneInfo.BaseUtcOffset = 480 than
// SerializedTimeZone.Bias must be -480.
this.bias = -timeZoneInfo.BaseUtcOffset;
// To convert TimeZoneInfo into SerializableTimeZone, we need two time changes: one to Standard
// time, the other to Daylight time. TimeZoneInfo holds a list of adjustment rules that represent
// the different rules that govern time changes over the years. We need to grab one of those rules
// to initialize this instance.
TimeZoneInfo.AdjustmentRule[] adjustmentRules = timeZoneInfo.GetAdjustmentRules();
if (adjustmentRules.Length == 0)
{
// If there are no adjustment rules (which is the case for UTC), we have to come up with two
// dummy time changes which both have a delta of zero and happen at two hard coded dates. This
// simulates a time zone in which there are no time changes.
this.daylightTime = new LegacyAvailabilityTimeZoneTime();
this.daylightTime.Delta = TimeSpan.Zero;
this.daylightTime.DayOrder = 1;
this.daylightTime.DayOfTheWeek = DayOfTheWeek.Sunday;
this.daylightTime.Month = 10;
this.daylightTime.TimeOfDay = TimeSpan.FromHours(2);
this.daylightTime.Year = 0;
this.standardTime = new LegacyAvailabilityTimeZoneTime();
this.standardTime.Delta = TimeSpan.Zero;
this.standardTime.DayOrder = 1;
this.standardTime.DayOfTheWeek = DayOfTheWeek.Sunday;
this.standardTime.Month = 3;
this.standardTime.TimeOfDay = TimeSpan.FromHours(2);
this.daylightTime.Year = 0;
}
else
{
// When there is at least one adjustment rule, we need to grab the last one which is the
// one that currently applies (TimeZoneInfo stores adjustment rules sorted from oldest to
// most recent).
TimeZoneInfo.AdjustmentRule currentRule = adjustmentRules[adjustmentRules.Length - 1];
this.standardTime = new LegacyAvailabilityTimeZoneTime(currentRule.DaylightTransitionEnd, TimeSpan.Zero);
// Again, TimeZoneInfo and SerializableTime use opposite signs for bias.
this.daylightTime = new LegacyAvailabilityTimeZoneTime(currentRule.DaylightTransitionStart, -currentRule.DaylightDelta);
}
}
internal TimeZoneInfo ToTimeZoneInfo()
{
if (this.daylightTime.HasTransitionTime &&
this.standardTime.HasTransitionTime)
{
TimeZoneInfo.AdjustmentRule adjustmentRule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(
DateTime.MinValue.Date,
DateTime.MaxValue.Date,
-this.daylightTime.Delta,
this.daylightTime.ToTransitionTime(),
this.standardTime.ToTransitionTime());
return TimeZoneInfo.CreateCustomTimeZone(
Guid.NewGuid().ToString(),
-this.bias,
"Custom time zone",
"Standard time",
"Daylight time",
new TimeZoneInfo.AdjustmentRule[] { adjustmentRule });
}
else
{
// Create no DST time zone
return TimeZoneInfo.CreateCustomTimeZone(
Guid.NewGuid().ToString(),
-this.bias,
"Custom time zone",
"Standard time");
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.Bias:
this.bias = TimeSpan.FromMinutes(reader.ReadElementValue<int>());
return true;
case XmlElementNames.StandardTime:
this.standardTime = new LegacyAvailabilityTimeZoneTime();
this.standardTime.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.DaylightTime:
this.daylightTime = new LegacyAvailabilityTimeZoneTime();
this.daylightTime.LoadFromXml(reader, reader.LocalName);
return true;
default:
return false;
}
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonProperty">The json property.</param>
/// <param name="service"></param>
internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service)
{
foreach (string key in jsonProperty.Keys)
{
switch (key)
{
case XmlElementNames.Bias:
this.bias = TimeSpan.FromMinutes(jsonProperty.ReadAsInt(key));
break;
case XmlElementNames.StandardTime:
this.standardTime = new LegacyAvailabilityTimeZoneTime();
this.standardTime.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service);
break;
case XmlElementNames.DaylightTime:
this.daylightTime = new LegacyAvailabilityTimeZoneTime();
this.daylightTime.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service);
break;
default:
break;
}
}
}
/// <summary>
/// Writes the elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.Bias,
(int)this.bias.TotalMinutes);
this.standardTime.WriteToXml(writer, XmlElementNames.StandardTime);
this.daylightTime.WriteToXml(writer, XmlElementNames.DaylightTime);
}
/// <summary>
/// Serializes the property to a Json value.
/// </summary>
/// <param name="service"></param>
/// <returns>
/// A Json value (either a JsonObject, an array of Json values, or a Json primitive)
/// </returns>
internal override object InternalToJson(ExchangeService service)
{
JsonObject jsonProperty = new JsonObject();
jsonProperty.Add(XmlElementNames.Bias, (int)this.bias.TotalMinutes);
jsonProperty.Add(XmlElementNames.StandardTime, this.standardTime.InternalToJson(service));
jsonProperty.Add(XmlElementNames.DaylightTime, this.daylightTime.InternalToJson(service));
return jsonProperty;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering.UI;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering
{
using UnityObject = UnityEngine.Object;
public interface IDebugData
{
Action GetReset();
//Action GetLoad();
//Action GetSave();
}
public sealed partial class DebugManager
{
static readonly Lazy<DebugManager> s_Instance = new Lazy<DebugManager>(() => new DebugManager());
public static DebugManager instance => s_Instance.Value;
ReadOnlyCollection<DebugUI.Panel> m_ReadOnlyPanels;
readonly List<DebugUI.Panel> m_Panels = new List<DebugUI.Panel>();
void UpdateReadOnlyCollection()
{
m_Panels.Sort();
m_ReadOnlyPanels = m_Panels.AsReadOnly();
}
public ReadOnlyCollection<DebugUI.Panel> panels
{
get
{
if (m_ReadOnlyPanels == null)
UpdateReadOnlyCollection();
return m_ReadOnlyPanels;
}
}
public event Action<bool> onDisplayRuntimeUIChanged = delegate {};
public event Action onSetDirty = delegate {};
event Action resetData;
public bool refreshEditorRequested;
GameObject m_Root;
DebugUIHandlerCanvas m_RootUICanvas;
GameObject m_PersistentRoot;
DebugUIHandlerPersistentCanvas m_RootUIPersistentCanvas;
// Knowing if the DebugWindows is open, is done by event as it is in another assembly.
// The DebugWindows is responsible to link its event to ToggleEditorUI.
bool m_EditorOpen = false;
public bool displayEditorUI => m_EditorOpen;
public void ToggleEditorUI(bool open) => m_EditorOpen = open;
public bool displayRuntimeUI
{
get => m_Root != null && m_Root.activeInHierarchy;
set
{
if (value)
{
m_Root = UnityObject.Instantiate(Resources.Load<Transform>("DebugUI Canvas")).gameObject;
m_Root.name = "[Debug Canvas]";
m_Root.transform.localPosition = Vector3.zero;
m_RootUICanvas = m_Root.GetComponent<DebugUIHandlerCanvas>();
m_Root.SetActive(true);
}
else
{
CoreUtils.Destroy(m_Root);
m_Root = null;
m_RootUICanvas = null;
}
onDisplayRuntimeUIChanged(value);
}
}
public bool displayPersistentRuntimeUI
{
get => m_RootUIPersistentCanvas != null && m_PersistentRoot.activeInHierarchy;
set
{
CheckPersistentCanvas();
m_PersistentRoot.SetActive(value);
}
}
DebugManager()
{
RegisterInputs();
RegisterActions();
}
public void RefreshEditor()
{
refreshEditorRequested = true;
}
public void Reset()
{
resetData?.Invoke();
ReDrawOnScreenDebug();
}
public void ReDrawOnScreenDebug()
{
if (displayRuntimeUI)
m_RootUICanvas?.ResetAllHierarchy();
}
public void RegisterData(IDebugData data) => resetData += data.GetReset();
public void UnregisterData(IDebugData data) => resetData -= data.GetReset();
public int GetState()
{
int hash = 17;
foreach (var panel in m_Panels)
hash = hash * 23 + panel.GetHashCode();
return hash;
}
internal void RegisterRootCanvas(DebugUIHandlerCanvas root)
{
Assert.IsNotNull(root);
m_Root = root.gameObject;
m_RootUICanvas = root;
}
internal void ChangeSelection(DebugUIHandlerWidget widget, bool fromNext)
{
m_RootUICanvas.ChangeSelection(widget, fromNext);
}
void CheckPersistentCanvas()
{
if (m_RootUIPersistentCanvas == null)
{
var uiManager = UnityObject.FindObjectOfType<DebugUIHandlerPersistentCanvas>();
if (uiManager == null)
{
m_PersistentRoot = UnityObject.Instantiate(Resources.Load<Transform>("DebugUI Persistent Canvas")).gameObject;
m_PersistentRoot.name = "[Debug Canvas - Persistent]";
m_PersistentRoot.transform.localPosition = Vector3.zero;
}
else
{
m_PersistentRoot = uiManager.gameObject;
}
m_RootUIPersistentCanvas = m_PersistentRoot.GetComponent<DebugUIHandlerPersistentCanvas>();
}
}
public void TogglePersistent(DebugUI.Widget widget)
{
if (widget == null)
return;
var valueWidget = widget as DebugUI.Value;
if (valueWidget == null)
{
Debug.Log("Only DebugUI.Value items can be made persistent.");
return;
}
CheckPersistentCanvas();
m_RootUIPersistentCanvas.Toggle(valueWidget);
}
void OnPanelDirty(DebugUI.Panel panel)
{
onSetDirty();
}
// TODO: Optimally we should use a query path here instead of a display name
public DebugUI.Panel GetPanel(string displayName, bool createIfNull = false, int groupIndex = 0)
{
foreach (var panel in m_Panels)
{
if (panel.displayName == displayName)
return panel;
}
DebugUI.Panel p = null;
if (createIfNull)
{
p = new DebugUI.Panel { displayName = displayName, groupIndex = groupIndex };
p.onSetDirty += OnPanelDirty;
m_Panels.Add(p);
UpdateReadOnlyCollection();
}
return p;
}
// TODO: Use a query path here as well instead of a display name
public void RemovePanel(string displayName)
{
DebugUI.Panel panel = null;
foreach (var p in m_Panels)
{
if (p.displayName == displayName)
{
p.onSetDirty -= OnPanelDirty;
panel = p;
break;
}
}
RemovePanel(panel);
}
public void RemovePanel(DebugUI.Panel panel)
{
if (panel == null)
return;
m_Panels.Remove(panel);
UpdateReadOnlyCollection();
}
public DebugUI.Widget GetItem(string queryPath)
{
foreach (var panel in m_Panels)
{
var w = GetItem(queryPath, panel);
if (w != null)
return w;
}
return null;
}
DebugUI.Widget GetItem(string queryPath, DebugUI.IContainer container)
{
foreach (var child in container.children)
{
if (child.queryPath == queryPath)
return child;
var containerChild = child as DebugUI.IContainer;
if (containerChild != null)
{
var w = GetItem(queryPath, containerChild);
if (w != null)
return w;
}
}
return null;
}
}
}
| |
using System;
using System.Linq;
using System.Threading;
using Amazon;
using Amazon.Runtime;
using Amazon.Runtime.Internal.Util;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2;
using System.Collections.Generic;
using Amazon.DynamoDBv2.DocumentModel;
using System.Text;
using System.IO;
using NUnit.Framework;
using CommonTests.Framework;
using CommonTests.IntegrationTests.DynamoDB;
namespace CommonTests.IntegrationTests
{
[TestFixture]
public class CacheTests
{
private const string tableName = "cache-test-table";
private AmazonDynamoDBClient client = null;
private bool lastUseSdkCacheValue;
[SetUp]
public void Init()
{
lastUseSdkCacheValue = AWSConfigs.UseSdkCache;
AWSConfigs.UseSdkCache = true;
SdkCache.Clear();
client = TestBase.CreateClient<AmazonDynamoDBClient>();
}
[TearDown]
public void Cleanup()
{
var tableExists = true;
//var status = AWSSDK_DotNet.IntegrationTests.Tests.DynamoDB.DynamoDBTests.GetStatus(tableName);
//tableExists = (status != null);
var allTables = client.ListTablesAsync().Result.TableNames;
tableExists = allTables.Contains(tableName);
if (tableExists)
DeleteTable();
AWSConfigs.UseSdkCache = lastUseSdkCacheValue;
SdkCache.Clear();
}
[Test]
public void TestCache()
{
Func<string, TableDescription> creator = tn => client.DescribeTableAsync(tn).Result.Table;
var tableName = GetTableName();
var tableCache = SdkCache.GetCache<string, TableDescription>(client, DynamoDBTests.TableCacheIdentifier, StringComparer.Ordinal);
Assert.AreEqual(0, tableCache.ItemCount);
using (var counter = new ServiceResponseCounter(client))
{
var table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(1, counter.ResponseCount);
Assert.AreEqual(1, tableCache.ItemCount);
// verify the item is still there
table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(1, counter.ResponseCount);
// verify item was reloaded
tableCache.Clear(tableName);
table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(2, counter.ResponseCount);
Assert.AreEqual(1, tableCache.ItemCount);
// test item expiration
tableCache.MaximumItemLifespan = TimeSpan.FromSeconds(1);
UtilityMethods.Sleep(tableCache.MaximumItemLifespan);
table = tableCache.GetValue(tableName, creator);
Assert.AreEqual(3, counter.ResponseCount);
Assert.AreEqual(1, tableCache.ItemCount);
}
}
[Test]
public void MultipleClientsTest()
{
Table.ClearTableCache();
var tableName = GetTableName();
Table table;
using (var nc = TestBase.CreateClient<AmazonDynamoDBClient>())
{
table = Table.LoadTable(nc, tableName);
}
Table.ClearTableCache();
table = Table.LoadTable(client, tableName);
}
[Test]
public void ChangingTableTest()
{
var item = new Document(new Dictionary<string, DynamoDBEntry>
{
{ "Id", 42 },
{ "Name", "Floyd" },
{ "Coffee", "Yes" }
});
var tableCache = SdkCache.GetCache<string, TableDescription>(client, DynamoDBTests.TableCacheIdentifier, StringComparer.Ordinal);
CreateTable(defaultKeys: true);
var table = Table.LoadTable(client, tableName);
table.PutItemAsync(item).Wait();
using (var counter = new ServiceResponseCounter(client))
{
var doc = table.GetItemAsync(42, "Floyd").Result;
Assert.IsNotNull(doc);
Assert.AreNotEqual(0, doc.Count);
Assert.AreEqual(1, counter.ResponseCount);
AssertExtensions.ExpectExceptionAsync(table.GetItemAsync("Floyd", 42)).Wait();
var oldTableDescription = tableCache.GetValue(tableName, null);
DeleteTable();
CreateTable(defaultKeys: false);
table.PutItemAsync(item).Wait();
AssertExtensions.ExpectExceptionAsync(table.GetItemAsync(42, "Yes")).Wait();
counter.Reset();
Table.ClearTableCache();
table = Table.LoadTable(client, tableName);
doc = table.GetItemAsync(42, "Yes").Result;
Assert.IsNotNull(doc);
Assert.AreNotEqual(0, doc.Count);
Assert.AreEqual(2, counter.ResponseCount);
counter.Reset();
Table.ClearTableCache();
PutItem(tableCache, tableName, oldTableDescription);
table = Table.LoadTable(client, tableName);
doc = tableCache.UseCache(tableName,
() => table.GetItemAsync(42, "Yes").Result,
() => table = Table.LoadTable(client, tableName),
shouldRetryForException: null);
Assert.IsNotNull(doc);
Assert.AreNotEqual(0, doc.Count);
Assert.AreEqual(2, counter.ResponseCount);
}
}
private void CreateTable(bool defaultKeys)
{
var keySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "Id",
KeyType = KeyType.HASH
},
new KeySchemaElement
{
AttributeName = defaultKeys ? "Name" : "Coffee",
KeyType = KeyType.RANGE
}
};
var attributes = new List<AttributeDefinition>
{
new AttributeDefinition
{
AttributeName = "Id",
AttributeType = ScalarAttributeType.N
},
new AttributeDefinition
{
AttributeName = defaultKeys ? "Name" : "Coffee",
AttributeType = ScalarAttributeType.S
}
};
client.CreateTableAsync(new CreateTableRequest
{
TableName = tableName,
KeySchema = keySchema,
AttributeDefinitions = attributes,
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 5
}
}).Wait();
DynamoDBTests.WaitForTableStatus(client, tableName, TableStatus.ACTIVE);
}
private void DeleteTable()
{
client.DeleteTableAsync(tableName).Wait();
DynamoDBTests.WaitForTableStatus(client, tableName, null);
}
private string GetTableName()
{
var tables = client.ListTablesAsync().Result.TableNames;
Assert.AreNotEqual(0, tables.Count);
var tableName = tables.First();
return tableName;
}
private void PutItem<TKey,TValue>(ICache<TKey,TValue> cache, TKey key, TValue value)
{
cache.Clear(key);
cache.GetValue(key, k => value);
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Quad Tree for input touch listeners. Considers on screen positions and axis alligned screen bounds.
/// Accepted screen bound: ----
/// | |
/// | |
/// ----
/// Not porperly handled screen bound: /\
/// / \
/// \ /
/// \/
/// (because is not axis alligned)
///
/// </summary>
public class QuadTreeTouchEvent {
public const int FIRST_LEVEL = 0;
public const int DEEP_LEVEL_THRESHOLD = 1;
private QuadNode root;
private ListenerLists[] tempArr = new ListenerLists[4];
// this temporal list is created once per quad tree root instance
private int tempIndex = 0;
/// <summary>
/// Initializes a new instance of the <see cref="QuadTreeTouchEvent"/> class.
/// </summary>
public QuadTreeTouchEvent () {
root = new QuadNode(FIRST_LEVEL);
}
/// <summary>
/// Tests the Rect screenBounds and returns the list of listeners that it affects.
/// There is a max of four lists.
/// </summary>
/// <param name='screenBounds'>
/// Screen bounds.
/// </param>
public ListenerLists[] add (Rect screenBounds) {
clear(tempArr);
addRecursive(root, screenBounds, tempArr, 0,0, Screen.width,Screen.height);
return tempArr;
}
private void addRecursive (QuadNode n, Rect screenBounds, ListenerLists[] arr, float x0, float y0, float x1, float y1) {
// reached max level?
if (n.level == DEEP_LEVEL_THRESHOLD) {
if (n.leafContent == null)
n.leafContent = new ListenerLists();
arr[tempIndex++] = n.leafContent;
// the caller object is responsible to allocate the listener instance in the many listeners list
return;
}
/// Test four points of rect screenBounds to get the destiny quad/s.
/// It can falls in as much as four quads.
/// y1
/// ------------- x1
/// | 001 | 010 |
/// -------------
/// | 1000 | 100 |
/// y0 -------------
/// x0
///
// use actual limits to calculate destiny quadrant/s
int test = quadrantTest(screenBounds, x0,y0,x1,y1);
/// depending on which quadrant/s it falls we need to allocate space for the
/// quad/s node and continue testing recursively
if (((test >> 0) & 1) == 1) {
if (n.topLeft == null)
n.topLeft = new QuadNode(n.level + 1);
addRecursive(n.topLeft, screenBounds, arr, x0,y1/2f, x1/2f,y1);
}
if (((test >> 1) & 1) == 1) {
if (n.topRight == null)
n.topRight = new QuadNode(n.level + 1);
addRecursive(n.topRight, screenBounds, arr, x1/2f,y1/2f, x1,y1);
}
if (((test >> 2) & 1) == 1) {
if (n.botRight == null)
n.botRight = new QuadNode(n.level + 1);
addRecursive(n.botRight, screenBounds, arr, x1/2f,y0, x1,y1/2f);
}
if (((test >> 3) & 1) == 1) {
if (n.botLeft == null)
n.botLeft = new QuadNode(n.level + 1);
addRecursive(n.botLeft, screenBounds, arr, x0,y0, x1/2f,y1/2f);
}
}
private static int quadrantTest (Rect bounds, float x0, float y0, float x1, float y1) {
int t = 0;
/// Executes the test for each 4 points of screen bound element.
/// This way we ensure the bound lement falls in as many quadrants it can
float halfY = y1/2f;
float halfX = x1/2f;
// minX is on left side?
if (bounds.xMin < halfX) {
if (bounds.yMin > halfY)
t |= 1; // quad topLeft
else t |= 8; // quad botLeft
if (bounds.yMax > halfY)
t |= 1; // quad topLeft
// other case processed above because it means minY also was <= y1/2f
// whenever maxX is on left, means minX is on side too
if (bounds.xMax < halfX)
return t;
// the other case is processed outside
}
// minX is on right
else {
if (bounds.yMin > halfY)
t |= 2; // quad topRight
else t |= 4; // quad botRight
if (bounds.yMax > halfY)
t |= 2; // quad topRight
// other case processed above because it means minY also was <= y1/2f
// whenever minX lies on right side, then maxX is also on right side
return t;
}
// last case: maxX is on right
if (bounds.yMin > halfY)
t |= 2; // quad topRight
else t |= 4; // quad botRight
if (bounds.yMax > halfY)
t |= 2; // quad topRight
// other case processed above because it means minY also was <= y1/2f
return t;
}
public ListenerLists traverse (Vector2 screenPos) {
return traverseRecursive(root, screenPos, 0,0, Screen.width,Screen.height);
}
public ListenerLists[] traverse (Rect bounds) {
clear(tempArr);
// if is leaf then return the list of listeners
if (root.level == DEEP_LEVEL_THRESHOLD) {
tempArr[tempIndex++] = root.leafContent;
return tempArr;
}
ListenerLists ll;
Vector2 v2aux;
// do some check if we can save some traverse work, for example when the entire bound is in one quadrant
v2aux.x = bounds.xMin;
v2aux.y = bounds.yMax;
ll = traverse(v2aux);
if (ll != null) tempArr[tempIndex++] = ll;
v2aux.x = bounds.xMax;
v2aux.y = bounds.yMax;
ll = traverse(v2aux);
if (ll != null) tempArr[tempIndex++] = ll;
v2aux.x = bounds.xMax;
v2aux.y = bounds.yMin;
ll = traverse(v2aux);
if (ll != null) tempArr[tempIndex++] = ll;
v2aux.x = bounds.xMin;
v2aux.y = bounds.yMin;
ll = traverse(v2aux);
if (ll != null) tempArr[tempIndex++] = ll;
return tempArr;
}
private ListenerLists traverseRecursive (QuadNode n, Vector2 p, float x0, float y0, float x1, float y1) {
// if is leaf then return the list of listeners
if (n.level == DEEP_LEVEL_THRESHOLD)
return n.leafContent;
// search in quad tree a leaf containing the screen position
float halfY = y1/2f;
float halfX = x1/2f;
if (p.x < halfX) {
if (p.y > halfY)
return n.topLeft==null? null : traverseRecursive(n.topLeft, p, x0, halfY, halfX, y1);
else
return n.botLeft==null? null : traverseRecursive(n.botLeft, p, x0, y0, halfX, halfY);
}
else {
if (p.y > halfY)
return n.topRight==null? null : traverseRecursive(n.topRight, p, halfX, halfY, x1, y1);
else
return n.botRight==null? null : traverseRecursive(n.botRight, p, halfX, y0, x1, halfY);
}
}
private void clear (ListenerLists[] arr) {
tempIndex = 0;
arr[0]= arr[1]= arr[2]= arr[3]= null;
}
public void clear () {
root.clear();
}
}
| |
namespace gView.Framework.GPS.UI
{
partial class FormGPS
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.gbPortSettings = new System.Windows.Forms.GroupBox();
this.lblComPort = new System.Windows.Forms.Label();
this.cmbPortName = new System.Windows.Forms.ComboBox();
this.lblStopBits = new System.Windows.Forms.Label();
this.cmbBaudRate = new System.Windows.Forms.ComboBox();
this.cmbStopBits = new System.Windows.Forms.ComboBox();
this.lblBaudRate = new System.Windows.Forms.Label();
this.lblDataBits = new System.Windows.Forms.Label();
this.cmbParity = new System.Windows.Forms.ComboBox();
this.cmbDataBits = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.btnStart = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtLon = new System.Windows.Forms.TextBox();
this.txtLat = new System.Windows.Forms.TextBox();
this.txtDLat = new System.Windows.Forms.TextBox();
this.txtDLon = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtPDOP = new System.Windows.Forms.TextBox();
this.txtVDOP = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtHDOP = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.panelSatellites = new System.Windows.Forms.Panel();
this.btnOK = new System.Windows.Forms.Button();
this.label7 = new System.Windows.Forms.Label();
this.txtTime = new System.Windows.Forms.TextBox();
this.gbPortSettings.SuspendLayout();
this.SuspendLayout();
//
// gbPortSettings
//
this.gbPortSettings.Controls.Add(this.lblComPort);
this.gbPortSettings.Controls.Add(this.cmbPortName);
this.gbPortSettings.Controls.Add(this.lblStopBits);
this.gbPortSettings.Controls.Add(this.cmbBaudRate);
this.gbPortSettings.Controls.Add(this.cmbStopBits);
this.gbPortSettings.Controls.Add(this.lblBaudRate);
this.gbPortSettings.Controls.Add(this.lblDataBits);
this.gbPortSettings.Controls.Add(this.cmbParity);
this.gbPortSettings.Controls.Add(this.cmbDataBits);
this.gbPortSettings.Controls.Add(this.label1);
this.gbPortSettings.Location = new System.Drawing.Point(101, 12);
this.gbPortSettings.Name = "gbPortSettings";
this.gbPortSettings.Size = new System.Drawing.Size(370, 67);
this.gbPortSettings.TabIndex = 24;
this.gbPortSettings.TabStop = false;
this.gbPortSettings.Text = "Serial Port &Settings";
//
// lblComPort
//
this.lblComPort.AutoSize = true;
this.lblComPort.Location = new System.Drawing.Point(12, 19);
this.lblComPort.Name = "lblComPort";
this.lblComPort.Size = new System.Drawing.Size(56, 13);
this.lblComPort.TabIndex = 0;
this.lblComPort.Text = "COM Port:";
//
// cmbPortName
//
this.cmbPortName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbPortName.FormattingEnabled = true;
this.cmbPortName.Items.AddRange(new object[] {
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6"});
this.cmbPortName.Location = new System.Drawing.Point(13, 35);
this.cmbPortName.Name = "cmbPortName";
this.cmbPortName.Size = new System.Drawing.Size(67, 21);
this.cmbPortName.TabIndex = 1;
//
// lblStopBits
//
this.lblStopBits.AutoSize = true;
this.lblStopBits.Location = new System.Drawing.Point(295, 19);
this.lblStopBits.Name = "lblStopBits";
this.lblStopBits.Size = new System.Drawing.Size(52, 13);
this.lblStopBits.TabIndex = 8;
this.lblStopBits.Text = "Stop Bits:";
//
// cmbBaudRate
//
this.cmbBaudRate.FormattingEnabled = true;
this.cmbBaudRate.Items.AddRange(new object[] {
"300",
"600",
"1200",
"2400",
"4800",
"9600",
"14400",
"28800",
"36000",
"115000"});
this.cmbBaudRate.Location = new System.Drawing.Point(86, 35);
this.cmbBaudRate.Name = "cmbBaudRate";
this.cmbBaudRate.Size = new System.Drawing.Size(69, 21);
this.cmbBaudRate.TabIndex = 3;
//
// cmbStopBits
//
this.cmbStopBits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbStopBits.FormattingEnabled = true;
this.cmbStopBits.Items.AddRange(new object[] {
"1",
"2",
"3"});
this.cmbStopBits.Location = new System.Drawing.Point(293, 35);
this.cmbStopBits.Name = "cmbStopBits";
this.cmbStopBits.Size = new System.Drawing.Size(65, 21);
this.cmbStopBits.TabIndex = 9;
//
// lblBaudRate
//
this.lblBaudRate.AutoSize = true;
this.lblBaudRate.Location = new System.Drawing.Point(85, 19);
this.lblBaudRate.Name = "lblBaudRate";
this.lblBaudRate.Size = new System.Drawing.Size(61, 13);
this.lblBaudRate.TabIndex = 2;
this.lblBaudRate.Text = "Baud Rate:";
//
// lblDataBits
//
this.lblDataBits.AutoSize = true;
this.lblDataBits.Location = new System.Drawing.Point(229, 19);
this.lblDataBits.Name = "lblDataBits";
this.lblDataBits.Size = new System.Drawing.Size(53, 13);
this.lblDataBits.TabIndex = 6;
this.lblDataBits.Text = "Data Bits:";
//
// cmbParity
//
this.cmbParity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbParity.FormattingEnabled = true;
this.cmbParity.Items.AddRange(new object[] {
"None",
"Even",
"Odd"});
this.cmbParity.Location = new System.Drawing.Point(161, 35);
this.cmbParity.Name = "cmbParity";
this.cmbParity.Size = new System.Drawing.Size(60, 21);
this.cmbParity.TabIndex = 5;
//
// cmbDataBits
//
this.cmbDataBits.FormattingEnabled = true;
this.cmbDataBits.Items.AddRange(new object[] {
"7",
"8",
"9"});
this.cmbDataBits.Location = new System.Drawing.Point(227, 35);
this.cmbDataBits.Name = "cmbDataBits";
this.cmbDataBits.Size = new System.Drawing.Size(60, 21);
this.cmbDataBits.TabIndex = 7;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(163, 19);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(36, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Parity:";
//
// btnStart
//
this.btnStart.BackColor = System.Drawing.Color.Red;
this.btnStart.Location = new System.Drawing.Point(12, 13);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(83, 68);
this.btnStart.TabIndex = 25;
this.btnStart.Text = "Start";
this.btnStart.UseVisualStyleBackColor = false;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(101, 88);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(57, 13);
this.label2.TabIndex = 26;
this.label2.Text = "Longitude:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(286, 88);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(48, 13);
this.label3.TabIndex = 27;
this.label3.Text = "Latitude:";
//
// txtLon
//
this.txtLon.Location = new System.Drawing.Point(156, 85);
this.txtLon.Name = "txtLon";
this.txtLon.ReadOnly = true;
this.txtLon.Size = new System.Drawing.Size(124, 20);
this.txtLon.TabIndex = 28;
//
// txtLat
//
this.txtLat.Location = new System.Drawing.Point(335, 85);
this.txtLat.Name = "txtLat";
this.txtLat.ReadOnly = true;
this.txtLat.Size = new System.Drawing.Size(124, 20);
this.txtLat.TabIndex = 29;
//
// txtDLat
//
this.txtDLat.Location = new System.Drawing.Point(335, 111);
this.txtDLat.Name = "txtDLat";
this.txtDLat.ReadOnly = true;
this.txtDLat.Size = new System.Drawing.Size(124, 20);
this.txtDLat.TabIndex = 31;
//
// txtDLon
//
this.txtDLon.Location = new System.Drawing.Point(156, 111);
this.txtDLon.Name = "txtDLon";
this.txtDLon.ReadOnly = true;
this.txtDLon.Size = new System.Drawing.Size(124, 20);
this.txtDLon.TabIndex = 30;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(9, 88);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(40, 13);
this.label4.TabIndex = 32;
this.label4.Text = "PDOP:";
//
// txtPDOP
//
this.txtPDOP.Location = new System.Drawing.Point(48, 85);
this.txtPDOP.Name = "txtPDOP";
this.txtPDOP.ReadOnly = true;
this.txtPDOP.Size = new System.Drawing.Size(47, 20);
this.txtPDOP.TabIndex = 33;
//
// txtVDOP
//
this.txtVDOP.Location = new System.Drawing.Point(48, 111);
this.txtVDOP.Name = "txtVDOP";
this.txtVDOP.ReadOnly = true;
this.txtVDOP.Size = new System.Drawing.Size(47, 20);
this.txtVDOP.TabIndex = 35;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(9, 114);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(40, 13);
this.label5.TabIndex = 34;
this.label5.Text = "VDOP:";
//
// txtHDOP
//
this.txtHDOP.Location = new System.Drawing.Point(48, 137);
this.txtHDOP.Name = "txtHDOP";
this.txtHDOP.ReadOnly = true;
this.txtHDOP.Size = new System.Drawing.Size(47, 20);
this.txtHDOP.TabIndex = 37;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(9, 140);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(41, 13);
this.label6.TabIndex = 36;
this.label6.Text = "HDOP:";
//
// panelSatellites
//
this.panelSatellites.BackColor = System.Drawing.SystemColors.ControlDark;
this.panelSatellites.Location = new System.Drawing.Point(156, 137);
this.panelSatellites.Name = "panelSatellites";
this.panelSatellites.Size = new System.Drawing.Size(303, 234);
this.panelSatellites.TabIndex = 38;
this.panelSatellites.Paint += new System.Windows.Forms.PaintEventHandler(this.panelSatellites_Paint);
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(12, 347);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(128, 23);
this.btnOK.TabIndex = 39;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(12, 187);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(58, 13);
this.label7.TabIndex = 40;
this.label7.Text = "GPS Time:";
//
// txtTime
//
this.txtTime.Location = new System.Drawing.Point(15, 203);
this.txtTime.Name = "txtTime";
this.txtTime.ReadOnly = true;
this.txtTime.Size = new System.Drawing.Size(125, 20);
this.txtTime.TabIndex = 43;
//
// FormGPS
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(484, 383);
this.Controls.Add(this.txtTime);
this.Controls.Add(this.label7);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.panelSatellites);
this.Controls.Add(this.txtHDOP);
this.Controls.Add(this.label6);
this.Controls.Add(this.txtVDOP);
this.Controls.Add(this.label5);
this.Controls.Add(this.txtPDOP);
this.Controls.Add(this.label4);
this.Controls.Add(this.txtDLat);
this.Controls.Add(this.txtDLon);
this.Controls.Add(this.txtLat);
this.Controls.Add(this.txtLon);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.gbPortSettings);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "FormGPS";
this.Text = "GPS";
this.gbPortSettings.ResumeLayout(false);
this.gbPortSettings.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox gbPortSettings;
private System.Windows.Forms.Label lblComPort;
private System.Windows.Forms.ComboBox cmbPortName;
private System.Windows.Forms.Label lblStopBits;
private System.Windows.Forms.ComboBox cmbBaudRate;
private System.Windows.Forms.ComboBox cmbStopBits;
private System.Windows.Forms.Label lblBaudRate;
private System.Windows.Forms.Label lblDataBits;
private System.Windows.Forms.ComboBox cmbParity;
private System.Windows.Forms.ComboBox cmbDataBits;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtLon;
private System.Windows.Forms.TextBox txtLat;
private System.Windows.Forms.TextBox txtDLat;
private System.Windows.Forms.TextBox txtDLon;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtPDOP;
private System.Windows.Forms.TextBox txtVDOP;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtHDOP;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Panel panelSatellites;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtTime;
}
}
| |
// 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.
#nullable enable
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace System.Resources.Extensions
{
public partial class DeserializingResourceReader
{
private bool _assumeBinaryFormatter = false;
private BinaryFormatter? _formatter = null;
private bool ValidateReaderType(string readerType)
{
// our format?
if (TypeNameComparer.Instance.Equals(readerType, PreserializedResourceWriter.DeserializingResourceReaderFullyQualifiedName))
{
return true;
}
// default format?
if (TypeNameComparer.Instance.Equals(readerType, PreserializedResourceWriter.ResourceReaderFullyQualifiedName))
{
// we can read the default format, we just assume BinaryFormatter and don't
// read the SerializationFormat
_assumeBinaryFormatter = true;
return true;
}
return false;
}
private object ReadBinaryFormattedObject()
{
if (_formatter == null)
{
_formatter = new BinaryFormatter()
{
Binder = new UndoTruncatedTypeNameSerializationBinder()
};
}
return _formatter.Deserialize(_store.BaseStream);
}
internal class UndoTruncatedTypeNameSerializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type type = null;
// determine if we have a mangled generic type name
if (typeName != null && assemblyName != null && !AreBracketsBalanced(typeName))
{
// undo the mangling that may have happened with .NETFramework's
// incorrect ResXSerialization binder.
typeName = typeName + ", " + assemblyName;
type = Type.GetType(typeName, throwOnError: false, ignoreCase:false);
}
// if type is null we'll fall back to the default type binder which is preferable
// since it is backed by a cache
return type;
}
private static bool AreBracketsBalanced(string typeName)
{
// make sure brackets are balanced
int firstBracket = typeName.IndexOf('[');
if (firstBracket == -1)
{
return true;
}
int brackets = 1;
for (int i = firstBracket + 1; i < typeName.Length; i++)
{
if (typeName[i] == '[')
{
brackets++;
}
else if (typeName[i] == ']')
{
brackets--;
if (brackets < 0)
{
// unbalanced, closing bracket without opening
break;
}
}
}
return brackets == 0;
}
}
private object DeserializeObject(int typeIndex)
{
Type type = FindType(typeIndex);
if (_assumeBinaryFormatter)
{
return ReadBinaryFormattedObject();
}
// read type
SerializationFormat format = (SerializationFormat)_store.Read7BitEncodedInt();
object value;
// read data
switch (format)
{
case SerializationFormat.BinaryFormatter:
{
// read length
int length = _store.Read7BitEncodedInt();
if (length < 0)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
}
long originalPosition = _store.BaseStream.Position;
value = ReadBinaryFormattedObject();
if (type == typeof(UnknownType))
{
// type information was omitted at the time of writing
// allow the payload to define the type
type = value.GetType();
}
long bytesRead = _store.BaseStream.Position - originalPosition;
// Ensure BF read what we expected.
if (bytesRead != length)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
}
break;
}
case SerializationFormat.TypeConverterByteArray:
{
// read length
int length = _store.Read7BitEncodedInt();
if (length < 0)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
}
byte[] data = _store.ReadBytes(length);
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter == null)
{
throw new TypeLoadException(SR.Format(SR.TypeLoadException_CannotLoadConverter, type));
}
value = converter.ConvertFrom(data);
break;
}
case SerializationFormat.TypeConverterString:
{
string stringData = _store.ReadString();
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter == null)
{
throw new TypeLoadException(SR.Format(SR.TypeLoadException_CannotLoadConverter, type));
}
value = converter.ConvertFromInvariantString(stringData);
break;
}
case SerializationFormat.ActivatorStream:
{
// read length
int length = _store.Read7BitEncodedInt();
if (length < 0)
{
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, length));
}
Stream stream;
if (_store.BaseStream is UnmanagedMemoryStream ums)
{
// For the case that we've memory mapped in the .resources
// file, just return a Stream pointing to that block of memory.
unsafe
{
stream = new UnmanagedMemoryStream(ums.PositionPointer, length, length, FileAccess.Read);
}
}
else
{
byte[] bytes = _store.ReadBytes(length);
// Lifetime of memory == lifetime of this stream.
stream = new MemoryStream(bytes, false);
}
value = Activator.CreateInstance(type, new object[] { stream });
break;
}
default:
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch);
}
// Make sure we deserialized the type that we expected.
// This protects against bad typeconverters or bad binaryformatter payloads.
if (value.GetType() != type)
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResType_SerBlobMismatch, type.FullName, value.GetType().FullName));
return value;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
//
// vp_Timer.cs
// ?VisionPunk, Minea Softworks. All Rights Reserved.
//
// description: vp_Timer is a script extension for delaying (scheduling) methods
// in Unity. it supports arguments, delegates, repetition with
// intervals, infinite repetition, pausing and canceling, and uses
// an object pool in order to feed the garbage collector with an
// absolute minimum amount of data
//
/////////////////////////////////////////////////////////////////////////////////
//#define DEBUG // uncomment to display timers in the Unity Editor Hierarchy
using UnityEngine;
using System;
using System.Collections.Generic;
#if (UNITY_EDITOR && DEBUG)
using System.Diagnostics;
#endif
public class vp_Timer : MonoBehaviour
{
private static GameObject m_MainObject = null;
private static List<Event> m_Active = new List<Event>();
private static List<Event> m_Pool = new List<Event>();
private static Event m_NewEvent = null;
private static int m_EventCount = 0;
// variables for the Update method
private static int m_EventBatch = 0;
private static int m_EventIterator = 0;
/// <summary>
/// the maximum amount of callbacks that the timer system will be
/// allowed to execute in one frame. reducing this may improve
/// performance with extreme amounts (hundreds) of active timers
/// but may also lead to some events getting delayed for a few
/// frames
/// </summary>
public static int MaxEventsPerFrame = 500;
/// <summary>
/// timer event callback for methods with no parameters
/// </summary>
public delegate void Callback();
/// <summary>
/// timer event callback for methods with parameters
/// </summary>
public delegate void ArgCallback(object args);
/// <summary>
/// data struct for use by the editor class
/// </summary>
public struct Stats
{
public int Created;
public int Inactive;
public int Active;
}
/// <summary>
/// returns false if this script was not added via the 'vp_Timer.In'
/// method - e.g. you may have dragged it to a gameobject in
/// the Inspector which won't work
/// </summary>
public bool WasAddedCorrectly
{
get
{
if (!Application.isPlaying)
return false;
if (gameObject != m_MainObject)
return false;
return true;
}
}
/// <summary>
/// in Awake a check is made to see if the vp_Timer component
/// was added correctly. if not it will be destroyed
/// </summary>
private void Awake()
{
if (!WasAddedCorrectly)
{
Destroy(this);
return;
}
}
/// <summary>
/// in Update the active list is looped every frame, executing
/// any timer events for which time is up. Update also detects
/// paused and canceled events
/// </summary>
private void Update()
{
// NOTE: this method never processes more than 'MaxEventsPerFrame',
// in order to avoid performance problems with excessive amounts of
// timers. this may lead to events being delayed a few frames.
// if experiencing delayed events 1) try to cut back on the amount
// of timers created simultaneously, and 2) increase 'MaxEventsPerFrame'
// execute any active events that are due, but only check
// up to max events per frame for performance
m_EventBatch = 0;
while ((vp_Timer.m_Active.Count > 0) && m_EventBatch < MaxEventsPerFrame)
{
// if we reached beginning of list, halt until next frame
if (m_EventIterator < 0)
{
// this has two purposes: 1) preventing multiple iterations
// per frame if our event count is below the maximum, and
// 2) preventing reaching index -1
m_EventIterator = vp_Timer.m_Active.Count - 1;
break;
}
// prevent index out of bounds
if (m_EventIterator > vp_Timer.m_Active.Count - 1)
m_EventIterator = vp_Timer.m_Active.Count - 1;
// execute all due events
if (Time.time >= vp_Timer.m_Active[m_EventIterator].DueTime || // time is up
vp_Timer.m_Active[m_EventIterator].Id == 0) // event has been canceled ('Execute' will kill it)
vp_Timer.m_Active[m_EventIterator].Execute();
else
{
// handle pausing
if (vp_Timer.m_Active[m_EventIterator].Paused)
vp_Timer.m_Active[m_EventIterator].DueTime += Time.deltaTime;
else
// log lifetime
vp_Timer.m_Active[m_EventIterator].LifeTime += Time.deltaTime;
}
// going backwards since 'Execute' will remove items from the list
m_EventIterator--;
m_EventBatch++;
}
}
/// <summary>
/// the "In" method is used for scheduling events. it always takes a
/// delay along with a callback (method or delegate) to be triggered
/// at the end of the delay. the overloads support arguments, iterations
/// and intervals. an optional "Event.Handle" object can also be passed
/// as the last parameter. this will be associated to the scheduled
/// event and will enable interaction with the event post-initiation,
/// along with extraction of a number of useful parameters
/// </summary>
// time + callback + [timer handle]
public static void In(float delay, Callback callback, Handle timerHandle = null)
{ Schedule(delay, callback, null, null, timerHandle, 1, -1.0f); }
// time + callback + iterations + [timer handle]
public static void In(float delay, Callback callback, int iterations, Handle timerHandle = null)
{ Schedule(delay, callback, null, null, timerHandle, iterations, -1.0f); }
// time + callback + iterations + interval + [timer handle]
public static void In(float delay, Callback callback, int iterations, float interval, Handle timerHandle = null)
{ Schedule(delay, callback, null, null, timerHandle, iterations, interval); }
// time + callback + arguments + [timer handle]
public static void In(float delay, ArgCallback callback, object arguments, Handle timerHandle = null)
{ Schedule(delay, null, callback, arguments, timerHandle, 1, -1.0f); }
// time + callback + arguments + iterations + [timer handle]
public static void In(float delay, ArgCallback callback, object arguments, int iterations, Handle timerHandle = null)
{ Schedule(delay, null, callback, arguments, timerHandle, iterations, -1.0f); }
// time + callback + arguments + iterations + interval + [timer handle]
public static void In(float delay, ArgCallback callback, object arguments, int iterations, float interval, Handle timerHandle = null)
{ Schedule(delay, null, callback, arguments, timerHandle, iterations, interval); }
/// <summary>
/// the "Start" method is used to run a timer for the sole
/// purpose of measuring time (useful for e.g. stopwatches).
/// it takes a mandatory timer handle as only input argument,
/// has no callback method and will run practically forever.
/// the timer handle can then be used to pause, resume and
/// poll all sorts of info from the timer event
/// </summary>
public static void Start(Handle timerHandle)
{
Schedule(315360000.0f, /* ten years, yo ;) */ delegate() { }, null, null, timerHandle, 1, -1.0f);
}
/// <summary>
/// the 'Schedule' method sets everything in order for the
/// timer event to be fired. it also creates a hidden
/// gameobject upon the first time called (for purposes of
/// running the Update loop and drawing editor debug info)
/// </summary>
private static void Schedule(float time, Callback func, ArgCallback argFunc, object args, Handle timerHandle, int iterations, float interval)
{
if (func == null && argFunc == null)
{
UnityEngine.Debug.LogError("Error: (vp_Timer) Aborted event because function is null.");
return;
}
// setup main gameobject
if (m_MainObject == null)
{
m_MainObject = new GameObject("Timers");
m_MainObject.AddComponent<vp_Timer>();
UnityEngine.Object.DontDestroyOnLoad(m_MainObject);
#if (UNITY_EDITOR && !DEBUG)
m_MainObject.gameObject.hideFlags = HideFlags.HideInHierarchy;
#endif
}
// force healthy time values
time = Mathf.Max(0.0f, time);
iterations = Mathf.Max(0, iterations);
interval = (interval == -1.0f) ? time : Mathf.Max(0.0f, interval);
// recycle an event - or create a new one if the pool is empty
m_NewEvent = null;
if (m_Pool.Count > 0)
{
m_NewEvent = m_Pool[0];
m_Pool.Remove(m_NewEvent);
}
else
m_NewEvent = new Event();
// iterate the event counter and store the id for this event
vp_Timer.m_EventCount++;
m_NewEvent.Id = vp_Timer.m_EventCount;
// set up the event with its function, arguments and times
if (func != null)
m_NewEvent.Function = func;
else if (argFunc != null)
{
m_NewEvent.ArgFunction = argFunc;
m_NewEvent.Arguments = args;
}
m_NewEvent.StartTime = Time.time;
m_NewEvent.DueTime = Time.time + time;
m_NewEvent.Iterations = iterations;
m_NewEvent.Interval = interval;
m_NewEvent.LifeTime = 0.0f;
m_NewEvent.Paused = false;
// add event to the Active list
vp_Timer.m_Active.Add(m_NewEvent);
// if a timer handle was provided, associate it to this event,
// but first cancel any already active event using the same
// handle: there can be only one ...
if (timerHandle != null)
{
if (timerHandle.Active)
timerHandle.Cancel();
// setting the 'Id' property associates this handle with
// the currently active event with the corresponding id
timerHandle.Id = m_NewEvent.Id;
}
#if (UNITY_EDITOR && DEBUG)
m_NewEvent.StoreCallingMethod();
EditorRefresh();
#endif
}
/// <summary>
/// cancels a timer if the passed timer handle is still active
/// </summary>
private static void Cancel(vp_Timer.Handle handle)
{
if (handle == null)
return;
// NOTE: the below Active check is super-important for verifying timer
// handle integrity. recycling 'handle.Event' if 'handle.Active' is false
// will cancel the wrong event and lead to some other timer never firing
// (this is because timer events are recycled but not their timer handles).
if (handle.Active)
{
// setting the 'Id' property to zero will result in DueTime also
// becoming zero, sending the event to 'Execute' in the next frame
// where it will be recycled instead of executed
handle.Id = 0;
return;
}
}
/// <summary>
/// cancels every currently active timer
/// </summary>
public static void CancelAll()
{
for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)
{
vp_Timer.m_Active[t].Id = 0;
}
}
/// <summary>
/// cancels every currently active timer that points to a
/// certain method
/// </summary>
public static void CancelAll(string methodName)
{
for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)
{
if (vp_Timer.m_Active[t].MethodName == methodName)
vp_Timer.m_Active[t].Id = 0;
}
}
/// <summary>
/// clears all currently active timers along with the object
/// pool, that is: disposes of every timer event, releasing
/// memory to the garbage collector
/// </summary>
public static void DestroyAll()
{
vp_Timer.m_Active.Clear();
vp_Timer.m_Pool.Clear();
#if (UNITY_EDITOR && DEBUG)
EditorRefresh();
#endif
}
/// <summary>
/// provides the custom vp_Timer editor class with debug info
/// </summary>
public static Stats EditorGetStats()
{
Stats stats;
stats.Created = m_Active.Count + m_Pool.Count;
stats.Inactive = m_Pool.Count;
stats.Active = m_Active.Count;
return stats;
}
/// <summary>
/// provides the custom vp_Timer editor class with the name of a
/// specific method in the Active list along with any arguments,
/// plus a stack trace (if compiling with the DEBUG define)
/// </summary>
public static string EditorGetMethodInfo(int eventIndex)
{
if (eventIndex < 0 || eventIndex > m_Active.Count - 1)
return "Argument out of range.";
return m_Active[eventIndex].MethodInfo;
}
/// <summary>
/// provides the custom vp_Timer editor class with the id of a
/// specific event in the Active list
/// </summary>
public static int EditorGetMethodId(int eventIndex)
{
if (eventIndex < 0 || eventIndex > m_Active.Count - 1)
return 0;
return m_Active[eventIndex].Id;
}
#if (DEBUG && UNITY_EDITOR)
/// <summary>
/// updates the name of the main gamobject, visible in the
/// hierarchy view during runtime (if compiling with the
/// DEBUG define)
/// </summary>
private static void EditorRefresh()
{
m_MainObject.name = "Timers (" + m_Active.Count + " / " + (m_Pool.Count + m_Active.Count).ToString() + ")";
}
#endif
/////////////////////////////////////////////////////////////////////////////////
//
// vp_Timer.Event
//
// description: this class is the internal representation of an event object.
// it is not to be manipulated directly since events are recycled
// and references to them would be unreliable. to interact with
// an event post initiation, schedule it with a 'vp_Timer.Handle'
//
/////////////////////////////////////////////////////////////////////////////////
private class Event
{
public int Id;
public Callback Function = null;
public ArgCallback ArgFunction = null;
public object Arguments = null;
public int Iterations = 1;
public float Interval = -1.0f;
public float DueTime = 0.0f;
public float StartTime = 0.0f;
public float LifeTime = 0.0f;
public bool Paused = false;
#if (DEBUG && UNITY_EDITOR)
private string m_CallingMethod = "";
#endif
/// <summary>
/// runs an event function, taking care of iterations, intervals
/// canceling and recycling
/// </summary>
public void Execute()
{
// if either 'Id' or 'DueTime' is zero, this timer has been
// canceled: recycle it!
if (Id == 0 || DueTime == 0.0f)
{
Recycle();
return;
}
// attempt to execute the callback function
if (Function != null)
Function();
else if (ArgFunction != null)
ArgFunction(Arguments);
else
{
// function was null: nothing to do so abort
Error("Aborted event because function is null.");
Recycle();
return;
}
// count down to recycling
if (Iterations > 0)
{
Iterations--;
// usually a timer has one default iteration and will
// enter the below scope to get recycled right away ...
if (Iterations < 1)
{
Recycle();
return;
}
}
// ... but if we end up here the timer either has atleast one
// iteration left, or user set iterations to zero for infinite
// repetition. either way: update due time with the interval
DueTime = Time.time + Interval;
}
/// <summary>
/// performs internal recycling of the vp_Timer
/// </summary>
private void Recycle()
{
Id = 0;
DueTime = 0.0f;
StartTime = 0.0f;
Function = null;
ArgFunction = null;
Arguments = null;
if (vp_Timer.m_Active.Remove(this))
m_Pool.Add(this);
#if (UNITY_EDITOR && DEBUG)
EditorRefresh();
#endif
}
/// <summary>
/// destroys this timer event forever, releasing its memory
/// to the garbage collector
/// </summary>
private void Destroy()
{
vp_Timer.m_Active.Remove(this);
vp_Timer.m_Pool.Remove(this);
}
#if (UNITY_EDITOR && DEBUG)
/// <summary>
/// used by the debug mode to fetch the callstack
/// </summary>
public void StoreCallingMethod()
{
StackTrace stackTrace = new StackTrace();
string result = "";
string declaringType = "";
for (int v = 3; v < stackTrace.FrameCount; v++)
{
StackFrame stackFrame = stackTrace.GetFrame(v);
declaringType = stackFrame.GetMethod().DeclaringType.ToString();
result += " <- " + declaringType + ":" + stackFrame.GetMethod().Name.ToString();
}
m_CallingMethod = result;
}
#endif
/// <summary>
/// standard event error method
/// </summary>
private void Error(string message)
{
string msg = "Error: (vp_Timer.Event) " + message;
#if (UNITY_EDITOR && DEBUG)
msg += MethodInfo;
#endif
UnityEngine.Debug.LogError(msg);
}
/// <summary>
/// returns the name of the scheduled method, or 'delegate'
/// </summary>
public string MethodName
{
get
{
if (Function != null)
{
if (Function.Method != null)
{
if (Function.Method.Name[0] == '<')
return "delegate";
else return Function.Method.Name;
}
}
else if (ArgFunction != null)
{
if (ArgFunction.Method != null)
{
if (ArgFunction.Method.Name[0] == '<')
return "delegate";
else return ArgFunction.Method.Name;
}
}
return null;
}
}
/// <summary>
/// returns the name of the scheduled method along with any arguments,
/// plus a stack trace (if compiling with the DEBUG define)
/// </summary>
public string MethodInfo
{
get
{
string s = MethodName;
if (!string.IsNullOrEmpty(s))
{
s += "(";
if (Arguments != null)
{
if (Arguments.GetType().IsArray)
{
object[] array = (object[])Arguments;
foreach (object o in array)
{
s += o.ToString();
if (Array.IndexOf(array, o) < array.Length - 1)
s += ", ";
}
}
else
s += Arguments;
}
s += ")";
}
else
s = "(function = null)";
#if (DEBUG && UNITY_EDITOR)
s += m_CallingMethod;
#endif
return s;
}
}
}
/////////////////////////////////////////////////////////////////////////////////
//
// vp_Timer.Handle
//
// description: this class is used to keep track of a currently running event.
// it is most commonly used to cancel an event or to see if it's
// still active, but it also has many properties to analyze the
// state of an event. the editor uses it to display debug info
//
/////////////////////////////////////////////////////////////////////////////////
public class Handle
{
private vp_Timer.Event m_Event = null; // timer we're pointing at
private int m_Id = 0; // id associated with timer upon creation of this handle
private int m_StartIterations = 1; // the amount of iterations of the event when started
private float m_FirstDueTime = 0.0f; // the initial execution delay of the event
/// <summary>
/// pauses or unpauses this timer event
/// </summary>
public bool Paused
{
get
{
return Active && m_Event.Paused;
}
set
{
if (Active)
m_Event.Paused = value;
}
}
//////// fixed times ////////
/// <summary>
/// returns the time of initial scheduling
/// </summary>
public float TimeOfInitiation
{
get
{
if (Active)
return m_Event.StartTime;
else return 0.0f;
}
}
/// <summary>
/// returns the time of first execution
/// </summary>
public float TimeOfFirstIteration
{
get
{
if (Active)
return m_FirstDueTime;
return 0.0f;
}
}
/// <summary>
/// returns the expected due time of the next iteration of an event
/// </summary>
public float TimeOfNextIteration
{
get
{
if (Active)
return m_Event.DueTime;
return 0.0f;
}
}
/// <summary>
/// returns the expected due time of the last iteration of an event
/// </summary>
public float TimeOfLastIteration
{
get
{
if (Active)
return Time.time + DurationLeft;
return 0.0f;
}
}
//////// timespans ////////
/// <summary>
/// returns the delay before first execution
/// </summary>
public float Delay
{
get
{
return (Mathf.Round((m_FirstDueTime - TimeOfInitiation) * 1000.0f) / 1000.0f);
}
}
/// <summary>
/// returns the repeat interval of an event
/// </summary>
public float Interval
{
get
{
if (Active)
return m_Event.Interval;
return 0.0f;
}
}
/// <summary>
/// returns the time left until the next iteration of an event
/// </summary>
public float TimeUntilNextIteration
{
get
{
if (Active)
return m_Event.DueTime - Time.time;
return 0.0f;
}
}
/// <summary>
/// returns the current total time left (all iterations) of an event
/// </summary>
public float DurationLeft
{
get
{
if (Active)
return TimeUntilNextIteration + ((m_Event.Iterations - 1) * m_Event.Interval);
return 0.0f;
}
}
/// <summary>
/// returns the total expected duration (due time + all iterations) of an event.
/// NOTE: this does not take pausing into account.
/// </summary>
public float DurationTotal
{
get
{
if (Active)
{
return Delay +
((m_StartIterations) * ((m_StartIterations > 1) ? Interval : 0.0f));
}
return 0.0f;
}
}
/// <summary>
/// returns the current age of an event (lifetime since initiation)
/// </summary>
public float Duration
{
get
{
if (Active)
return m_Event.LifeTime;
return 0.0f;
}
}
//////// iterations ////////
/// <summary>
/// returns the total expected amount of iterations of an event upon initiation
/// </summary>
public int IterationsTotal
{
get
{
return m_StartIterations;
}
}
/// <summary>
/// returns the number of iterations left of an event
/// </summary>
public int IterationsLeft
{
get
{
if (Active)
return m_Event.Iterations;
return 0;
}
}
//////// main data ////////
/// <summary>
/// returns the id of this event handle, which is also the id of
/// the associated event (if not, the handle is considered inactive).
/// Setting this property directly is not recommended
/// </summary>
public int Id
{
get
{
return m_Id;
}
set
{
// setting the property associates this handle with a
// currently active event with the same id, or null.
m_Id = value;
// if 'Id' is being set to zero, cancel the event immediately
// by setting due time to zero and return
if (m_Id == 0)
{
m_Event.DueTime = 0.0f;
return;
}
// find the associated event. most likely it is the last created one in
// the active list, which is instantly found by looping backwards.
// if not, it might be some other event that a brave user wishes to
// find and hook up manually (this is OK, though not recommended)
m_Event = null;
for (int t = vp_Timer.m_Active.Count - 1; t > -1; t--)
{
if (vp_Timer.m_Active[t].Id == m_Id)
{
m_Event = vp_Timer.m_Active[t];
break;
}
}
if (m_Event == null)
UnityEngine.Debug.LogError("Error: (vp_Timer.Handle) Failed to assign event with Id '" + m_Id + "'.");
// store some initial event info
m_StartIterations = m_Event.Iterations;
m_FirstDueTime = m_Event.DueTime;
}
}
/// <summary>
/// returns true if the timer event of this handle is active
/// (running or paused). rReturns false if not, or if this
/// timer handle is no longer valid
/// </summary>
public bool Active
{
// NOTE: this property verifies timer handle integrity.
// if 'Event.Id' and 'Id' differ, the timer handle is no
// longer valid and using its event may cause bugs
get
{
if (m_Event == null || Id == 0 || m_Event.Id == 0)
return false;
return m_Event.Id == Id;
}
}
/// <summary>
/// returns the name of the scheduled method, or 'delegate'
/// </summary>
public string MethodName { get { return m_Event.MethodName; } }
/// <summary>
/// returns the name of the scheduled method along with any arguments,
/// plus a stack trace (if compiling with the DEBUG define)
/// </summary>
public string MethodInfo { get { return m_Event.MethodInfo; } }
/// <summary>
/// cancels the event associated with this handle, if active
/// </summary>
public void Cancel()
{
vp_Timer.Cancel(this);
}
/// <summary>
/// executes the event associated with this handle early, if active
/// </summary>
public void Execute()
{
m_Event.DueTime = Time.time;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Xml;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Management.Automation.Language;
using Microsoft.Management.Infrastructure;
namespace System.Management.Automation
{
/// <summary>
/// Defines generic utilities and helper methods for PowerShell
/// </summary>
internal static class PsUtils
{
internal static string ArmArchitecture = "ARM";
/// <summary>
/// Safely retrieves the MainModule property of a
/// process. Version 2.0 and below of the .NET Framework are
/// impacted by a Win32 API usability knot that throws an
/// exception if API tries to enumerate the process' modules
/// while it is still loading them. This generates the error
/// message: Only part of a ReadProcessMemory or
/// WriteProcessMemory request was completed.
/// The BCL fix in V3 was to just try more, so we do the same
/// thing.
///
/// Note: If you attempt to retrieve the MainModule of a 64-bit
/// process from a WOW64 (32-bit) process, the Win32 API has a fatal
/// flaw that causes this to return the same error.
///
/// If you need the MainModule of a 64-bit process from a WOW64
/// process, you will need to write the P/Invoke yourself.
/// </summary>
///
/// <param name="targetProcess">The process from which to
/// retrieve the MainModule</param>
/// <exception cref="NotSupportedException">
/// You are trying to access the MainModule property for a process that is running
/// on a remote computer. This property is available only for processes that are
/// running on the local computer.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The process Id is not available (or) The process has exited.
/// </exception>
/// <exception cref="System.ComponentModel.Win32Exception">
///
/// </exception>
internal static ProcessModule GetMainModule(Process targetProcess)
{
int caughtCount = 0;
ProcessModule mainModule = null;
while (mainModule == null)
{
try
{
mainModule = targetProcess.MainModule;
}
catch (System.ComponentModel.Win32Exception e)
{
// If this is an Access Denied error (which can happen with thread impersonation)
// then re-throw immediately.
if (e.NativeErrorCode == 5)
throw;
// Otherwise retry to ensure module is loaded.
caughtCount++;
System.Threading.Thread.Sleep(100);
if (caughtCount == 5)
throw;
}
}
return mainModule;
}
/// <summary>
/// Retrieve the parent process of a process.
///
/// This is an extremely expensive operation, as WMI
/// needs to work with an ugly Win32 API. The Win32 API
/// creates a snapshot of every process in the system, which
/// you then need to iterate through to find your process and
/// its parent PID.
///
/// Also, since this is PID based, this API is only reliable
/// when the process has not yet exited.
/// </summary>
///
/// <param name="current">The process we want to find the
/// parent of</param>
internal static Process GetParentProcess(Process current)
{
string wmiQuery = String.Format(CultureInfo.CurrentCulture,
"Select * From Win32_Process Where Handle='{0}'",
current.Id);
using (CimSession cimSession = CimSession.Create(null))
{
IEnumerable<CimInstance> processCollection =
cimSession.QueryInstances("root/cimv2", "WQL", wmiQuery);
int parentPid =
processCollection.Select(
cimProcess =>
Convert.ToInt32(cimProcess.CimInstanceProperties["ParentProcessId"].Value,
CultureInfo.CurrentCulture)).FirstOrDefault();
if (parentPid == 0)
return null;
try
{
Process returnProcess = Process.GetProcessById(parentPid);
// Ensure the process started before the current
// process, as it could have gone away and had the
// PID recycled.
if (returnProcess.StartTime <= current.StartTime)
return returnProcess;
else
return null;
}
catch (ArgumentException)
{
// GetProcessById throws an ArgumentException when
// you reach the top of the chain -- Explorer.exe
// has a parent process, but you cannot retrieve it.
return null;
}
}
}
#if !CORECLR // .NET Framework Version is not applicable to CoreCLR
/// <summary>
/// Detects the installation of Framework Versions 1.1, 2.0, 3.0 and 3.5 and 4.0 through
/// the official registry installation keys.
/// </summary>
internal static class FrameworkRegistryInstallation
{
/// <summary>
/// Gets the three registry names allowing for framework installation and service pack checks based on the
/// majorVersion and minorVersion version numbers.
/// </summary>
/// <param name="majorVersion">Major version of .NET required, for .NET 3.5 this is 3.</param>
/// <param name="minorVersion">Minor version of .NET required, for .NET 3.5 this is 5.</param>
/// <param name="installKeyName">name of the key containing installValueName</param>
/// <param name="installValueName">name of the registry key indicating the SP has been installed</param>
/// <param name="spKeyName">name of the key containing the SP value with SP version</param>
/// <param name="spValueName">name of the value containing the SP value with SP version</param>
/// <returns>true if the majorVersion and minorVersion correspond the versions we can check for, false otherwise.</returns>
private static bool GetRegistryNames(int majorVersion, int minorVersion, out string installKeyName, out string installValueName, out string spKeyName, out string spValueName)
{
installKeyName = null;
spKeyName = null;
installValueName = null;
spValueName = "SP";
const string v1_1KeyName = "v1.1.4322";
const string v2KeyName = "v2.0.50727";
const string v3KeyName = "v3.0";
const string v3_5KeyName = "v3.5";
// There are two registry keys "Client" and "Full" corresponding to the Client and Full .NET 4 Profiles.
// Client is a subset of the assemblies in Full (identical assemblies, smaller set), having most of the
// .NET 4's features.
// Here is some information on the client profile: http://msdn.microsoft.com/en-us/library/cc656912.aspx
// For now, we are picking Client, because it has most of .NET features and is the only version available
// in Server Core. If, in the future, PowerShell needs to depend on Full, we might have to revisit this
// decision.
const string v4KeyName = @"v4\Client";
const string install = "Install";
const string oneToThreePointFivePrefix = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\";
// In .NET 4.5, there is no concept of Client and Full. There is only the full redistributable package available
// http://msdn.microsoft.com/en-us/library/cc656912(VS.110).aspx
const string v45KeyName = @"v4\Full";
const string v45ReleaseKeyName = "Release";
if (majorVersion == 1 && minorVersion == 1)
{
// http://msdn.microsoft.com/en-us/library/ms994402.aspx
installKeyName = oneToThreePointFivePrefix + v1_1KeyName;
spKeyName = installKeyName;
installValueName = install;
return true;
}
if (majorVersion == 2 && minorVersion == 0)
{
// http://msdn.microsoft.com/en-us/library/aa480243.aspx
installKeyName = oneToThreePointFivePrefix + v2KeyName;
spKeyName = installKeyName;
installValueName = install;
return true;
}
if (majorVersion == 3 && minorVersion == 0)
{
// http://msdn.microsoft.com/en-us/library/aa480173.aspx
installKeyName = oneToThreePointFivePrefix + v3KeyName + @"\Setup";
spKeyName = oneToThreePointFivePrefix + v3KeyName;
installValueName = "InstallSuccess";
return true;
}
if (majorVersion == 3 && minorVersion == 5)
{
// http://msdn.microsoft.com/en-us/library/cc160716.aspx
installKeyName = oneToThreePointFivePrefix + v3_5KeyName;
spKeyName = installKeyName;
installValueName = install;
return true;
}
if (majorVersion == 4 && minorVersion == 0)
{
// http://msdn.microsoft.com/library/ee942965(v=VS.100).aspx
installKeyName = oneToThreePointFivePrefix + v4KeyName;
spKeyName = installKeyName;
installValueName = install;
spValueName = "Servicing";
return true;
}
if (majorVersion == 4 && minorVersion == 5)
{
// http://msdn.microsoft.com/en-us/library/ee942965(VS.110).aspx
installKeyName = oneToThreePointFivePrefix + v45KeyName;
installValueName = v45ReleaseKeyName;
return true;
}
// To add v1.0 in the future note that
// http://msdn.microsoft.com/en-us/library/ms994395.aspx does not mention
// NDP keys since they were not introduced until later.
// There were no official setup keys, but this blog suggests an alternative for finding out
// about the service pack information:
// http://blogs.msdn.com/astebner/archive/2004/09/14/229802.aspx
return false;
}
/// <summary>
/// Tries to read the valueName from the registry key returning null if
/// the it was not found, if it is not an integer or if or an exception was thrown.
/// </summary>
/// <param name="key">Key containing valueName</param>
/// <param name="valueName">Name of value to be returned</param>
/// <returns>The value or null if it could not be retrieved</returns>
private static int? GetRegistryKeyValueInt(RegistryKey key, string valueName)
{
try
{
object keyValue = key.GetValue(valueName);
if (keyValue is int)
{
return (int)keyValue;
}
return null;
}
catch (ObjectDisposedException)
{
return null;
}
catch (SecurityException)
{
return null;
}
catch (IOException)
{
return null;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
/// <summary>
/// Tries to read the keyName from the registry key returning null if
/// the key was not found or an exception was thrown.
/// </summary>
/// <param name="key">Key containing subKeyName</param>
/// <param name="subKeyName">NAme of sub key to be returned</param>
/// <returns>The subkey or null if it could not be retrieved</returns>
private static RegistryKey GetRegistryKeySubKey(RegistryKey key, string subKeyName)
{
try
{
return key.OpenSubKey(subKeyName);
}
catch (ObjectDisposedException)
{
return null;
}
catch (SecurityException)
{
return null;
}
catch (ArgumentException)
{
return null;
}
}
// based on Table in http://support.microsoft.com/kb/318785
private static Version V4_0 = new Version(4, 0, 30319, 0);
private static Version V3_5 = new Version(3, 5, 21022, 8);
private static Version V3_5sp1 = new Version(3, 5, 30729, 1);
private static Version V3_0 = new Version(3, 0, 4506, 30);
private static Version V3_0sp1 = new Version(3, 0, 4506, 648);
private static Version V3_0sp2 = new Version(3, 0, 4506, 2152);
private static Version V2_0 = new Version(2, 0, 50727, 42);
private static Version V2_0sp1 = new Version(2, 0, 50727, 1433);
private static Version V2_0sp2 = new Version(2, 0, 50727, 3053);
private static Version V1_1 = new Version(1, 1, 4322, 573);
private static Version V1_1sp1 = new Version(1, 1, 4322, 2032);
private static Version V1_1sp1Server = new Version(1, 1, 4322, 2300);
// Original versions without build or revision numbers
private static Version V4_5_00 = new Version(4, 5, 0, 0);
private static Version V4_0_00 = new Version(4, 0, 0, 0);
private static Version V3_5_00 = new Version(3, 5, 0, 0);
private static Version V3_0_00 = new Version(3, 0, 0, 0);
private static Version V2_0_00 = new Version(2, 0, 0, 0);
private static Version V1_1_00 = new Version(1, 1, 0, 0);
// Dictionary holding compatible .NET framework versions
// This is used in verifying the .NET framework version for loading module manifest
internal static Dictionary<Version, HashSet<Version>> CompatibleNetFrameworkVersions = new Dictionary<Version, HashSet<Version>>() {
{V1_1_00, new HashSet<Version> {V4_5_00, V4_0_00, V3_5_00, V3_0_00, V2_0_00}},
{V2_0_00, new HashSet<Version> {V4_5_00, V4_0_00, V3_5_00, V3_0_00}},
{V3_0_00, new HashSet<Version> {V4_5_00, V4_0_00, V3_5_00 }},
{V3_5_00, new HashSet<Version> {V4_5_00, V4_0_00 }},
{V4_0_00, new HashSet<Version> {V4_5_00}},
{V4_5_00, new HashSet<Version> ()},
};
// .NET 4.5 is the highest known .NET version for PowerShell 3.0
internal static Version KnownHighestNetFrameworkVersion = new Version(4, 5);
/// <summary>
/// Returns true if IsFrameworkInstalled will be able to check for this framework version.
/// </summary>
/// <param name="version">version to be checked</param>
/// <param name="majorVersion">Major version of .NET required, for .NET 3.5 this is 3.</param>
/// <param name="minorVersion">Minor version of .NET required, for .NET 3.5 this is 5.</param>
/// <param name="minimumSpVersion">Minimum SP version number corresponding to <paramref name="version"/>.</param>
/// <returns>true if IsFrameworkInstalled will be able to check for this framework version</returns>
internal static bool CanCheckFrameworkInstallation(Version version, out int majorVersion, out int minorVersion, out int minimumSpVersion)
{
// based on Table in http://support.microsoft.com/kb/318785
majorVersion = -1;
minorVersion = -1;
minimumSpVersion = -1;
if (version == V4_5_00)
{
majorVersion = 4;
minorVersion = 5;
minimumSpVersion = 0;
return true;
}
if (version == V4_0 || version == V4_0_00)
{
majorVersion = 4;
minorVersion = 0;
minimumSpVersion = 0;
return true;
}
if (version == V3_5 || version == V3_5_00)
{
majorVersion = 3;
minorVersion = 5;
minimumSpVersion = 0;
return true;
}
if (version == V3_5sp1)
{
majorVersion = 3;
minorVersion = 5;
minimumSpVersion = 1;
return true;
}
else if (version == V3_0 || version == V3_0_00)
{
majorVersion = 3;
minorVersion = 0;
minimumSpVersion = 0;
return true;
}
else if (version == V3_0sp1)
{
majorVersion = 3;
minorVersion = 0;
minimumSpVersion = 1;
return true;
}
else if (version == V3_0sp2)
{
majorVersion = 3;
minorVersion = 0;
minimumSpVersion = 2;
return true;
}
else if (version == V2_0 || version == V2_0_00)
{
majorVersion = 2;
minorVersion = 0;
minimumSpVersion = 0;
return true;
}
else if (version == V2_0sp1)
{
majorVersion = 2;
minorVersion = 0;
minimumSpVersion = 1;
return true;
}
else if (version == V2_0sp2)
{
majorVersion = 2;
minorVersion = 0;
minimumSpVersion = 2;
return true;
}
else if (version == V1_1 || version == V1_1_00)
{
majorVersion = 1;
minorVersion = 1;
minimumSpVersion = 0;
return true;
}
else if (version == V1_1sp1 || version == V1_1sp1Server)
{
majorVersion = 1;
minorVersion = 1;
minimumSpVersion = 1;
return true;
}
return false;
}
/// <summary>
/// Check if the given version if the framework is installed
/// </summary>
/// <param name="version">version to check.
/// for .NET Framework 3.5 and any service pack this can be new Version(3,5) or new Version(3, 5, 21022, 8).
/// for .NET 3.5 with SP1 this should be new Version(3, 5, 30729, 1).
/// For other versions please check the table at http://support.microsoft.com/kb/318785.
/// </param>
/// <returns></returns>
internal static bool IsFrameworkInstalled(Version version)
{
int minorVersion, majorVersion, minimumSPVersion;
if (!FrameworkRegistryInstallation.CanCheckFrameworkInstallation(
version,
out majorVersion,
out minorVersion,
out minimumSPVersion))
{
return false;
}
return IsFrameworkInstalled(majorVersion, minorVersion, minimumSPVersion);
}
/// <summary>
/// Check if the given version if the framework is installed
/// </summary>
/// <param name="majorVersion">Major version of .NET required, for .NET 3.5 this is 3.</param>
/// <param name="minorVersion">Minor version of .NET required, for .NET 3.5 this is 5.</param>
/// <param name="minimumSPVersion">Minimum SP version required. 0 (Zero) or less means no SP requirement.</param>
/// <returns>true if the framework is available. False if it is not available or that could not be determined.</returns>
internal static bool IsFrameworkInstalled(int majorVersion, int minorVersion, int minimumSPVersion)
{
string installKeyName, installValueName, spKeyName, spValueName;
if (!FrameworkRegistryInstallation.GetRegistryNames(majorVersion, minorVersion, out installKeyName, out installValueName, out spKeyName, out spValueName))
{
return false;
}
RegistryKey installKey = FrameworkRegistryInstallation.GetRegistryKeySubKey(Registry.LocalMachine, installKeyName);
if (installKey == null)
{
return false;
}
int? installValue = FrameworkRegistryInstallation.GetRegistryKeyValueInt(installKey, installValueName);
if (installValue == null)
{
return false;
}
// The detection logic for .NET 4.5 is to check for the existence of a DWORD key named Release under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full folder in the registry.
// For .NET 4.5, the value of this key is the release number and not 1 (Install = 1 for .NET 3.5, .NET 4.0) . So, we need to bypasss the check below
if ((majorVersion != 4 && minorVersion != 5) && (installValue != 1))
{
Debug.Assert(PSVersionInfo.CLRVersion.Major == 4, "This check is valid only for CLR Version 4.0 and .NET Version 4.5");
return false;
}
if (minimumSPVersion > 0)
{
RegistryKey spKey = FrameworkRegistryInstallation.GetRegistryKeySubKey(Registry.LocalMachine, spKeyName);
if (spKey == null)
{
return false;
}
int? spValue = FrameworkRegistryInstallation.GetRegistryKeyValueInt(spKey, spValueName);
if (spValue == null)
{
return false;
}
if (spValue < minimumSPVersion)
{
return false;
}
}
return true;
}
}
#endif
/// <summary>
/// Returns processor architecture for the current process.
/// If powershell is running inside Wow64, then <see cref="ProcessorArchitecture.X86"/> is returned.
/// </summary>
/// <returns>processor architecture for the current process</returns>
internal static ProcessorArchitecture GetProcessorArchitecture(out bool isRunningOnArm)
{
var sysInfo = new NativeMethods.SYSTEM_INFO();
NativeMethods.GetSystemInfo(ref sysInfo);
ProcessorArchitecture result;
isRunningOnArm = false;
switch (sysInfo.wProcessorArchitecture)
{
case NativeMethods.PROCESSOR_ARCHITECTURE_IA64:
result = ProcessorArchitecture.IA64;
break;
case NativeMethods.PROCESSOR_ARCHITECTURE_AMD64:
result = ProcessorArchitecture.Amd64;
break;
case NativeMethods.PROCESSOR_ARCHITECTURE_INTEL:
result = ProcessorArchitecture.X86;
break;
case NativeMethods.PROCESSOR_ARCHITECTURE_ARM:
result = ProcessorArchitecture.None;
isRunningOnArm = true;
break;
default:
result = ProcessorArchitecture.None;
break;
}
return result;
}
/// <summary>
/// Return true/false to indicate whether the processor architecture is ARM
/// </summary>
/// <returns></returns>
internal static bool IsRunningOnProcessorArchitectureARM()
{
#if CORECLR
Architecture arch = RuntimeInformation.OSArchitecture;
if (arch == Architecture.Arm || arch == Architecture.Arm64)
{
return true;
}
else
{
return false;
}
#else
// Important:
// this function has a clone in Workflow.ServiceCore in admin\monad\src\m3p\product\ServiceCore\WorkflowCore\WorkflowRuntimeCompilation.cs
// if you are making any changes specific to this function then update the clone as well.
var sysInfo = new NativeMethods.SYSTEM_INFO();
NativeMethods.GetSystemInfo(ref sysInfo);
return sysInfo.wProcessorArchitecture == NativeMethods.PROCESSOR_ARCHITECTURE_ARM;
#endif
}
internal static string GetHostName()
{
// Note: non-windows CoreCLR does not support System.Net yet
if (Platform.IsWindows)
{
return WinGetHostName();
}
else
{
return Platform.NonWindowsGetHostName();
}
}
internal static string WinGetHostName()
{
System.Net.NetworkInformation.IPGlobalProperties ipProperties =
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
string hostname = ipProperties.HostName;
if (!String.IsNullOrEmpty(ipProperties.DomainName))
{
hostname = hostname + "." + ipProperties.DomainName;
}
return hostname;
}
internal static uint GetNativeThreadId()
{
if (Platform.IsWindows)
{
return WinGetNativeThreadId();
}
else
{
return Platform.NonWindowsGetThreadId();
}
}
internal static uint WinGetNativeThreadId()
{
return NativeMethods.GetCurrentThreadId();
}
private static class NativeMethods
{
// Important:
// this clone has a clone in SMA in admin\monad\src\m3p\product\ServiceCore\WorkflowCore\WorkflowRuntimeCompilation.cs
// if you are making any changes specific to this class then update the clone as well.
internal const ushort PROCESSOR_ARCHITECTURE_INTEL = 0;
internal const ushort PROCESSOR_ARCHITECTURE_ARM = 5;
internal const ushort PROCESSOR_ARCHITECTURE_IA64 = 6;
internal const ushort PROCESSOR_ARCHITECTURE_AMD64 = 9;
internal const ushort PROCESSOR_ARCHITECTURE_UNKNOWN = 0xFFFF;
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEM_INFO
{
public ushort wProcessorArchitecture;
public ushort wReserved;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public UIntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort wProcessorLevel;
public ushort wProcessorRevision;
};
[DllImport(PinvokeDllNames.GetSystemInfoDllName)]
internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
[DllImport(PinvokeDllNames.GetCurrentThreadIdDllName)]
internal static extern uint GetCurrentThreadId();
}
#region ASTUtils
/// <summary>
/// This method is to get the unique key for a UsingExpressionAst. The key is a base64
/// encoded string based on the text of the UsingExpressionAst.
///
/// This method is used when handling a script block that contains $using for Invoke-Command.
///
/// When run Invoke-Command targeting a machine that runs PSv3 or above, we pass a dictionary
/// to the remote end that contains the key of each UsingExpressionAst and its value. This method
/// is used to generate the key.
/// </summary>
/// <param name="usingAst">A using expression</param>
/// <returns>Base64 encoded string as the key of the UsingExpressionAst</returns>
internal static string GetUsingExpressionKey(Language.UsingExpressionAst usingAst)
{
Diagnostics.Assert(usingAst != null, "Caller makes sure the parameter is not null");
// We cannot call ToLowerInvariant unconditionally, because usingAst might
// contain IndexExpressionAst in its SubExpression, such as
// $using:bar["AAAA"]
// and the index "AAAA" might not get us the same value as "aaaa".
//
// But we do want a unique key to represent the same UsingExpressionAst's as much
// as possible, so as to avoid sending redundant key-value's to remote machine.
// As a workaround, we call ToLowerInvariant when the SubExpression of usingAst
// is a VariableExpressionAst, because:
// (1) Variable name is case insensitive;
// (2) People use $using to refer to a variable most of the time.
string usingAstText = usingAst.ToString();
if (usingAst.SubExpression is Language.VariableExpressionAst)
{
usingAstText = usingAstText.ToLowerInvariant();
}
return StringToBase64Converter.StringToBase64String(usingAstText);
}
#endregion ASTUtils
#region EvaluatePowerShellDataFile
/// <summary>
/// Evaluate a powershell data file as if it's a module manifest
/// </summary>
/// <param name="parameterName"></param>
/// <param name="psDataFilePath"></param>
/// <param name="context"></param>
/// <param name="skipPathValidation"></param>
/// <returns></returns>
internal static Hashtable EvaluatePowerShellDataFileAsModuleManifest(
string parameterName,
string psDataFilePath,
ExecutionContext context,
bool skipPathValidation)
{
// Use the same capabilities as the module manifest
// e.g. allow 'PSScriptRoot' variable
return EvaluatePowerShellDataFile(
parameterName,
psDataFilePath,
context,
Microsoft.PowerShell.Commands.ModuleCmdletBase.PermittedCmdlets,
new[] { "PSScriptRoot" },
allowEnvironmentVariables: true,
skipPathValidation: skipPathValidation);
}
/// <summary>
/// Get a Hashtable object out of a PowerShell data file (.psd1)
/// </summary>
/// <param name="parameterName">
/// Name of the parameter that takes the specified .psd1 file as a value
/// </param>
/// <param name="psDataFilePath">
/// Path to the powershell data file
/// </param>
/// <param name="context">
/// ExecutionContext to use
/// </param>
/// <param name="allowedCommands">
/// Set of command names that are allowed to use in the .psd1 file
/// </param>
/// <param name="allowedVariables">
/// Set of variable names that are allowed to use in the .psd1 file
/// </param>
/// <param name="allowEnvironmentVariables">
/// If true, allow to use environment variables in the .psd1 file
/// </param>
/// <param name="skipPathValidation">
/// If true, caller guarantees the path is valid
/// </param>
/// <returns></returns>
internal static Hashtable EvaluatePowerShellDataFile(
string parameterName,
string psDataFilePath,
ExecutionContext context,
IEnumerable<string> allowedCommands,
IEnumerable<string> allowedVariables,
bool allowEnvironmentVariables,
bool skipPathValidation)
{
if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); }
if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); }
if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); }
string resolvedPath;
if (skipPathValidation)
{
resolvedPath = psDataFilePath;
}
else
{
#region "ValidatePowerShellDataFilePath"
bool isPathValid = true;
// File extension needs to be .psd1
string pathExt = Path.GetExtension(psDataFilePath);
if (string.IsNullOrEmpty(pathExt) ||
!StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase))
{
isPathValid = false;
}
ProviderInfo provider;
var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider);
// ConfigPath should be resolved as FileSystem provider
if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase))
{
isPathValid = false;
}
// ConfigPath should be resolved to a single path
if (resolvedPaths.Count != 1)
{
isPathValid = false;
}
if (!isPathValid)
{
throw PSTraceSource.NewArgumentException(
parameterName,
ParserStrings.CannotResolvePowerShellDataFilePath,
psDataFilePath);
}
resolvedPath = resolvedPaths[0];
#endregion "ValidatePowerShellDataFilePath"
}
#region "LoadAndEvaluatePowerShellDataFile"
object evaluationResult;
try
{
// Create the scriptInfo for the .psd1 file
string dataFileName = Path.GetFileName(resolvedPath);
var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context);
ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock;
// Validate the scriptblock
scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables);
// Evaluate the scriptblock
object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
try
{
// Set the $PSScriptRoot before the evaluation
context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath));
evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs());
}
finally
{
context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot);
}
}
catch (RuntimeException ex)
{
throw PSTraceSource.NewInvalidOperationException(
ex,
ParserStrings.CannotLoadPowerShellDataFile,
psDataFilePath,
ex.Message);
}
var retResult = evaluationResult as Hashtable;
if (retResult == null)
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
#endregion "LoadAndEvaluatePowerShellDataFile"
return retResult;
}
#endregion EvaluatePowerShellDataFile
internal static readonly string[] ManifestModuleVersionPropertyName = new[] { "ModuleVersion" };
internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" };
internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] { "AliasesToExport", "CmdletsToExport", "FunctionsToExport", "NestedModules", "RootModule", "ModuleToProcess", "ModuleVersion" };
internal static Hashtable GetModuleManifestProperties(string psDataFilePath, string[] keys)
{
string dataFileContents = ScriptAnalysis.ReadScript(psDataFilePath);
ParseError[] parseErrors;
var ast = (new Parser()).Parse(psDataFilePath, dataFileContents, null, out parseErrors, ParseMode.ModuleAnalysis);
if (parseErrors.Length > 0)
{
var pe = new ParseException(parseErrors);
throw PSTraceSource.NewInvalidOperationException(
pe,
ParserStrings.CannotLoadPowerShellDataFile,
psDataFilePath,
pe.Message);
}
string unused1;
string unused2;
var pipeline = ast.GetSimplePipeline(false, out unused1, out unused2);
if (pipeline != null)
{
var hashtableAst = pipeline.GetPureExpression() as HashtableAst;
if (hashtableAst != null)
{
var result = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (var pair in hashtableAst.KeyValuePairs)
{
var key = pair.Item1 as StringConstantExpressionAst;
if (key != null && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase))
{
try
{
var val = pair.Item2.SafeGetValue();
result[key.Value] = val;
}
catch
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
}
}
return result;
}
}
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
}
/// <summary>
/// This class provides helper methods for converting to/fro from
/// string to base64string
/// </summary>
internal static class StringToBase64Converter
{
/// <summary>
/// Converts string to base64 encoded string
/// </summary>
/// <param name="input">string to encode</param>
/// <returns>base64 encoded string</returns>
internal static string StringToBase64String(string input)
{
// NTRAID#Windows Out Of Band Releases-926471-2005/12/27-JonN
// shell crashes if you pass an empty script block to a native command
if (null == input)
{
throw PSTraceSource.NewArgumentNullException("input");
}
string base64 = Convert.ToBase64String
(
Encoding.Unicode.GetBytes(input.ToCharArray())
);
return base64;
}
/// <summary>
/// Decodes base64 encoded string
/// </summary>
/// <param name="base64">base64 string to decode</param>
/// <returns>decoded string</returns>
internal static string Base64ToString(string base64)
{
if (string.IsNullOrEmpty(base64))
{
throw PSTraceSource.NewArgumentNullException("base64");
}
string output = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64)));
return output;
}
/// <summary>
/// Decodes base64 encoded string in to args array
/// </summary>
/// <param name="base64"></param>
/// <returns></returns>
internal static object[] Base64ToArgsConverter(string base64)
{
if (string.IsNullOrEmpty(base64))
{
throw PSTraceSource.NewArgumentNullException("base64");
}
string decoded = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64)));
//Deserialize string
XmlReader reader = XmlReader.Create(new StringReader(decoded), InternalDeserializer.XmlReaderSettingsForCliXml);
object dso;
Deserializer deserializer = new Deserializer(reader);
dso = deserializer.Deserialize();
if (deserializer.Done() == false)
{
//This helper function should move to host and it should provide appropriate
//error message there.
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
PSObject mo = dso as PSObject;
if (mo == null)
{
//This helper function should move the host. Provide appropriate error message.
//Format of args parameter is not correct.
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
var argsList = mo.BaseObject as ArrayList;
if (argsList == null)
{
//This helper function should move the host. Provide appropriate error message.
//Format of args parameter is not correct.
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
return argsList.ToArray();
}
}
#region ReferenceEqualityComparer
/// <summary>
/// Equality comparer based on Object Identity
/// </summary>
internal class ReferenceEqualityComparer : IEqualityComparer
{
bool IEqualityComparer.Equals(object x, object y)
{
return Object.ReferenceEquals(x, y);
}
int IEqualityComparer.GetHashCode(object obj)
{
// The Object.GetHashCode and RuntimeHelpers.GetHashCode methods are used in the following scenarios:
//
// Object.GetHashCode is useful in scenarios where you care about object value. Two strings with identical
// contents will return the same value for Object.GetHashCode.
//
// RuntimeHelpers.GetHashCode is useful in scenarios where you care about object identity. Two strings with
// identical contents will return different values for RuntimeHelpers.GetHashCode, because they are different
// string objects, although their contents are the same.
return RuntimeHelpers.GetHashCode(obj);
}
}
#endregion
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using TouchScript.Hit;
using TouchScript.Utils;
using UnityEngine;
namespace TouchScript.Layers
{
/// <summary>
/// Base class for all touch layers. Used to check if some object is hit by a touch point.
/// <seealso cref="ITouchManager"/>
/// <seealso cref="TouchHit"/>
/// <seealso cref="TouchPoint"/>
/// </summary>
/// <remarks>
/// <para>In <b>TouchScript</b> it's a layer's job to determine if a touch on the screen hits anything in Unity's 3d/2d world.</para>
/// <para><see cref="ITouchManager"/> keeps a sorted list of all layers in <see cref="ITouchManager.Layers"/> which it queries when a new touch appears. It's a layer's job to return <see cref="LayerHitResult.Hit"/> if this touch hits an object. Layers can even be used to "hit" objects outside of Unity's 3d world, for example <b>Scaleform</b> integration is implemented this way.</para>
/// <para>Layers can be configured in a scene using <see cref="TouchManager"/> or from code using <see cref="ITouchManager"/> API.</para>
/// <para>If you want to route touches and manually control which objects they should "touch" it's better to create a new layer extending <see cref="TouchLayer"/>.</para>
/// </remarks>
[ExecuteInEditMode]
public abstract class TouchLayer : MonoBehaviour
{
#region Constants
/// <summary>
/// Result of a touch's hit test with a layer.
/// </summary>
public enum LayerHitResult
{
/// <summary>
/// Something wrong happened.
/// </summary>
Error = 0,
/// <summary>
/// Touch hit an object.
/// </summary>
Hit = 1,
/// <summary>
/// Touch didn't hit any object.
/// </summary>
Miss = 2
}
#endregion
#region Events
/// <summary>
/// Occurs when layer determines that a touch has hit something.
/// </summary>
public event EventHandler<TouchLayerEventArgs> TouchBegan
{
add { touchBeganInvoker += value; }
remove { touchBeganInvoker -= value; }
}
// Needed to overcome iOS AOT limitations
private EventHandler<TouchLayerEventArgs> touchBeganInvoker;
#endregion
#region Public properties
/// <summary>
/// Touch layer's name.
/// </summary>
public string Name;
/// <summary>
/// Layers screen to world projection normal.
/// </summary>
public virtual Vector3 WorldProjectionNormal
{
get { return transform.forward; }
}
/// <summary>
/// Gets or sets an object implementing <see cref="ILayerDelegate"/> to be asked for layer specific actions.
/// </summary>
/// <value> The delegate. </value>
public ILayerDelegate Delegate { get; set; }
#endregion
#region Public methods
/// <summary>
/// Gets the projection parameters of this layer which might depend on a specific touch data.
/// </summary>
/// <param name="touch"> Touch to retrieve projection parameters for. </param>
/// <returns></returns>
public virtual ProjectionParams GetProjectionParams(TouchPoint touch)
{
return layerProjectionParams;
}
/// <summary>
/// Checks if a point in screen coordinates hits something in this layer.
/// </summary>
/// <param name="position">Position in screen coordinates.</param>
/// <param name="hit">Hit result.</param>
/// <returns><see cref="LayerHitResult.Hit"/>, if an object is hit, <see cref="LayerHitResult.Miss"/> or <see cref="LayerHitResult.Error"/> otherwise.</returns>
public virtual LayerHitResult Hit(Vector2 position, out TouchHit hit)
{
hit = default(TouchHit);
if (enabled == false || gameObject.activeInHierarchy == false) return LayerHitResult.Miss;
return LayerHitResult.Error;
}
#endregion
#region Private variables
/// <summary>
/// The layer projection parameters.
/// </summary>
protected ProjectionParams layerProjectionParams;
#endregion
#region Unity methods
/// <summary>
/// Unity Awake callback.
/// </summary>
protected virtual void Awake()
{
setName();
if (!Application.isPlaying) return;
layerProjectionParams = createProjectionParams();
TouchManager.Instance.AddLayer(this, 0, false);
}
/// <summary>
/// Unity OnDestroy callback.
/// </summary>
protected virtual void OnDestroy()
{
if (Application.isPlaying && TouchManager.Instance != null) TouchManager.Instance.RemoveLayer(this);
}
#endregion
#region Internal methods
internal bool INTERNAL_BeginTouch(TouchPoint touch)
{
TouchHit hit;
if (Delegate != null && Delegate.ShouldReceiveTouch(this, touch) == false) return false;
var result = beginTouch(touch, out hit);
if (result == LayerHitResult.Hit)
{
touch.Layer = this;
touch.Hit = hit;
if (hit.Transform != null) touch.Target = hit.Transform;
if (touchBeganInvoker != null)
touchBeganInvoker.InvokeHandleExceptions(this, new TouchLayerEventArgs(touch));
return true;
}
return false;
}
internal void INTERNAL_UpdateTouch(TouchPoint touch)
{
updateTouch(touch);
}
internal void INTERNAL_EndTouch(TouchPoint touch)
{
endTouch(touch);
}
internal void INTERNAL_CancelTouch(TouchPoint touch)
{
cancelTouch(touch);
}
#endregion
#region Protected functions
/// <summary>
/// Updates touch layers's name.
/// </summary>
protected virtual void setName()
{
if (string.IsNullOrEmpty(Name)) Name = "Layer";
}
/// <summary>
/// Called when a layer is touched to query the layer if this touch hits something.
/// </summary>
/// <param name="touch">Touch.</param>
/// <param name="hit">Hit result.</param>
/// <returns><see cref="LayerHitResult.Hit"/>, if an object is hit, <see cref="LayerHitResult.Miss"/> or <see cref="LayerHitResult.Error"/> otherwise.</returns>
/// <remarks>This method may also be used to update some internal state or resend this event somewhere.</remarks>
protected virtual LayerHitResult beginTouch(TouchPoint touch, out TouchHit hit)
{
var result = Hit(touch.Position, out hit);
return result;
}
/// <summary>
/// Called when a touch is moved.
/// </summary>
/// <param name="touch">Touch.</param>
/// <remarks>This method may also be used to update some internal state or resend this event somewhere.</remarks>
protected virtual void updateTouch(TouchPoint touch) {}
/// <summary>
/// Called when a touch ends.
/// </summary>
/// <param name="touch">Touch.</param>
/// <remarks>This method may also be used to update some internal state or resend this event somewhere.</remarks>
protected virtual void endTouch(TouchPoint touch) {}
/// <summary>
/// Called when a touch is cancelled.
/// </summary>
/// <param name="touch">Touch.</param>
/// <remarks>This method may also be used to update some internal state or resend this event somewhere.</remarks>
protected virtual void cancelTouch(TouchPoint touch) {}
/// <summary>
/// Creates projection parameters.
/// </summary>
/// <returns> Created <see cref="ProjectionParams"/> instance.</returns>
protected virtual ProjectionParams createProjectionParams()
{
return new ProjectionParams();
}
#endregion
}
/// <summary>
/// Arguments used with <see cref="TouchLayer"/> events.
/// </summary>
public class TouchLayerEventArgs : EventArgs
{
/// <summary>
/// Gets the touch associated with the event.
/// </summary>
public TouchPoint Touch { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="TouchLayerEventArgs"/> class.
/// </summary>
/// <param name="touch">The touch associated with the event.</param>
public TouchLayerEventArgs(TouchPoint touch)
: base()
{
Touch = touch;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.CertLDAPConfigurationBinding", Namespace="urn:iControl")]
public partial class ManagementCertLDAPConfiguration : iControlInterface {
public ManagementCertLDAPConfiguration() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void add_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("add_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginadd_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endadd_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void create(
string [] config_names,
string [] search_base_dns,
string [] [] servers
) {
this.Invoke("create", new object [] {
config_names,
search_base_dns,
servers});
}
public System.IAsyncResult Begincreate(string [] config_names,string [] search_base_dns,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
config_names,
search_base_dns,
servers}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create_default_authentication_ad_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void create_default_authentication_ad_configuration(
string search_base_dn,
string [] servers
) {
this.Invoke("create_default_authentication_ad_configuration", new object [] {
search_base_dn,
servers});
}
public System.IAsyncResult Begincreate_default_authentication_ad_configuration(string search_base_dn,string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create_default_authentication_ad_configuration", new object[] {
search_base_dn,
servers}, callback, asyncState);
}
public void Endcreate_default_authentication_ad_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create_default_authentication_ldap_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void create_default_authentication_ldap_configuration(
string search_base_dn,
string [] servers
) {
this.Invoke("create_default_authentication_ldap_configuration", new object [] {
search_base_dn,
servers});
}
public System.IAsyncResult Begincreate_default_authentication_ldap_configuration(string search_base_dn,string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create_default_authentication_ldap_configuration", new object[] {
search_base_dn,
servers}, callback, asyncState);
}
public void Endcreate_default_authentication_ldap_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_configurations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void delete_all_configurations(
) {
this.Invoke("delete_all_configurations", new object [0]);
}
public System.IAsyncResult Begindelete_all_configurations(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_configurations", new object[0], callback, asyncState);
}
public void Enddelete_all_configurations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void delete_configuration(
string [] config_names
) {
this.Invoke("delete_configuration", new object [] {
config_names});
}
public System.IAsyncResult Begindelete_configuration(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_configuration", new object[] {
config_names}, callback, asyncState);
}
public void Enddelete_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_bind_distinguished_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_bind_distinguished_name(
string [] config_names
) {
object [] results = this.Invoke("get_bind_distinguished_name", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_bind_distinguished_name(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_bind_distinguished_name", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_bind_distinguished_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_bind_password
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_bind_password(
string [] config_names
) {
object [] results = this.Invoke("get_bind_password", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_bind_password(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_bind_password", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_bind_password(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_bind_time_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_bind_time_limit(
string [] config_names
) {
object [] results = this.Invoke("get_bind_time_limit", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_bind_time_limit(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_bind_time_limit", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_bind_time_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_check_host_attribute_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_check_host_attribute_state(
string [] config_names
) {
object [] results = this.Invoke("get_check_host_attribute_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_check_host_attribute_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_check_host_attribute_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_check_host_attribute_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_check_roles_group_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_check_roles_group_state(
string [] config_names
) {
object [] results = this.Invoke("get_check_roles_group_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_check_roles_group_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_check_roles_group_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_check_roles_group_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_debug_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_debug_state(
string [] config_names
) {
object [] results = this.Invoke("get_debug_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_debug_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_debug_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_debug_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] config_names
) {
object [] results = this.Invoke("get_description", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_filter
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_filter(
string [] config_names
) {
object [] results = this.Invoke("get_filter", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_filter(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_filter", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_filter(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_idle_time_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_idle_time_limit(
string [] config_names
) {
object [] results = this.Invoke("get_idle_time_limit", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_idle_time_limit(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_idle_time_limit", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_idle_time_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ignore_unavailable_authentication_information_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_ignore_unavailable_authentication_information_state(
string [] config_names
) {
object [] results = this.Invoke("get_ignore_unavailable_authentication_information_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_ignore_unavailable_authentication_information_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ignore_unavailable_authentication_information_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_ignore_unavailable_authentication_information_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ldap_ssl_option
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementLDAPSSLOption [] get_ldap_ssl_option(
string [] config_names
) {
object [] results = this.Invoke("get_ldap_ssl_option", new object [] {
config_names});
return ((ManagementLDAPSSLOption [])(results[0]));
}
public System.IAsyncResult Beginget_ldap_ssl_option(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ldap_ssl_option", new object[] {
config_names}, callback, asyncState);
}
public ManagementLDAPSSLOption [] Endget_ldap_ssl_option(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementLDAPSSLOption [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ldap_sso_option
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementLDAPSSOOption [] get_ldap_sso_option(
string [] config_names
) {
object [] results = this.Invoke("get_ldap_sso_option", new object [] {
config_names});
return ((ManagementLDAPSSOOption [])(results[0]));
}
public System.IAsyncResult Beginget_ldap_sso_option(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ldap_sso_option", new object[] {
config_names}, callback, asyncState);
}
public ManagementLDAPSSOOption [] Endget_ldap_sso_option(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementLDAPSSOOption [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ldap_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_ldap_version(
string [] config_names
) {
object [] results = this.Invoke("get_ldap_version", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_ldap_version(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ldap_version", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_ldap_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_login_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_login_attribute(
string [] config_names
) {
object [] results = this.Invoke("get_login_attribute", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_login_attribute(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_login_attribute", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_login_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_login_filter
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_login_filter(
string [] config_names
) {
object [] results = this.Invoke("get_login_filter", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_login_filter(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_login_filter", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_login_filter(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_login_name_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_login_name_attribute(
string [] config_names
) {
object [] results = this.Invoke("get_login_name_attribute", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_login_name_attribute(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_login_name_attribute", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_login_name_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_port(
string [] config_names
) {
object [] results = this.Invoke("get_port", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_port(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_port", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_search_base_distinguished_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_search_base_distinguished_name(
string [] config_names
) {
object [] results = this.Invoke("get_search_base_distinguished_name", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_search_base_distinguished_name(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_search_base_distinguished_name", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_search_base_distinguished_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_search_scope
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementLDAPSearchScope [] get_search_scope(
string [] config_names
) {
object [] results = this.Invoke("get_search_scope", new object [] {
config_names});
return ((ManagementLDAPSearchScope [])(results[0]));
}
public System.IAsyncResult Beginget_search_scope(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_search_scope", new object[] {
config_names}, callback, asyncState);
}
public ManagementLDAPSearchScope [] Endget_search_scope(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementLDAPSearchScope [])(results[0]));
}
//-----------------------------------------------------------------------
// get_search_time_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_search_time_limit(
string [] config_names
) {
object [] results = this.Invoke("get_search_time_limit", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_search_time_limit(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_search_time_limit", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_search_time_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_server(
string [] config_names
) {
object [] results = this.Invoke("get_server", new object [] {
config_names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_server(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_server", new object[] {
config_names}, callback, asyncState);
}
public string [] [] Endget_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ssl_ca_certificate_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_ssl_ca_certificate_file(
string [] config_names
) {
object [] results = this.Invoke("get_ssl_ca_certificate_file", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_ssl_ca_certificate_file(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ssl_ca_certificate_file", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_ssl_ca_certificate_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ssl_check_peer_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_ssl_check_peer_state(
string [] config_names
) {
object [] results = this.Invoke("get_ssl_check_peer_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_ssl_check_peer_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ssl_check_peer_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_ssl_check_peer_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ssl_cipher
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_ssl_cipher(
string [] config_names
) {
object [] results = this.Invoke("get_ssl_cipher", new object [] {
config_names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_ssl_cipher(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ssl_cipher", new object[] {
config_names}, callback, asyncState);
}
public string [] [] Endget_ssl_cipher(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ssl_client_certificate
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_ssl_client_certificate(
string [] config_names
) {
object [] results = this.Invoke("get_ssl_client_certificate", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_ssl_client_certificate(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ssl_client_certificate", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_ssl_client_certificate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ssl_client_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_ssl_client_key(
string [] config_names
) {
object [] results = this.Invoke("get_ssl_client_key", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_ssl_client_key(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ssl_client_key", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_ssl_client_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// get_warning_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_warning_state(
string [] config_names
) {
object [] results = this.Invoke("get_warning_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_warning_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_warning_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_warning_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// remove_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void remove_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("remove_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginremove_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endremove_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_bind_distinguished_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_bind_distinguished_name(
string [] config_names,
string [] bind_dns
) {
this.Invoke("set_bind_distinguished_name", new object [] {
config_names,
bind_dns});
}
public System.IAsyncResult Beginset_bind_distinguished_name(string [] config_names,string [] bind_dns, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_bind_distinguished_name", new object[] {
config_names,
bind_dns}, callback, asyncState);
}
public void Endset_bind_distinguished_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_bind_password
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_bind_password(
string [] config_names,
string [] bind_passwords
) {
this.Invoke("set_bind_password", new object [] {
config_names,
bind_passwords});
}
public System.IAsyncResult Beginset_bind_password(string [] config_names,string [] bind_passwords, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_bind_password", new object[] {
config_names,
bind_passwords}, callback, asyncState);
}
public void Endset_bind_password(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_bind_time_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_bind_time_limit(
string [] config_names,
long [] time_limits
) {
this.Invoke("set_bind_time_limit", new object [] {
config_names,
time_limits});
}
public System.IAsyncResult Beginset_bind_time_limit(string [] config_names,long [] time_limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_bind_time_limit", new object[] {
config_names,
time_limits}, callback, asyncState);
}
public void Endset_bind_time_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_check_host_attribute_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_check_host_attribute_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_check_host_attribute_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_check_host_attribute_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_check_host_attribute_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_check_host_attribute_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_check_roles_group_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_check_roles_group_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_check_roles_group_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_check_roles_group_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_check_roles_group_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_check_roles_group_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_debug_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_debug_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_debug_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_debug_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_debug_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_debug_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_description(
string [] config_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
config_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] config_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
config_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_filter
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_filter(
string [] config_names,
string [] filters
) {
this.Invoke("set_filter", new object [] {
config_names,
filters});
}
public System.IAsyncResult Beginset_filter(string [] config_names,string [] filters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_filter", new object[] {
config_names,
filters}, callback, asyncState);
}
public void Endset_filter(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_idle_time_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_idle_time_limit(
string [] config_names,
long [] time_limits
) {
this.Invoke("set_idle_time_limit", new object [] {
config_names,
time_limits});
}
public System.IAsyncResult Beginset_idle_time_limit(string [] config_names,long [] time_limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_idle_time_limit", new object[] {
config_names,
time_limits}, callback, asyncState);
}
public void Endset_idle_time_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ignore_unavailable_authentication_information_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ignore_unavailable_authentication_information_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_ignore_unavailable_authentication_information_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_ignore_unavailable_authentication_information_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ignore_unavailable_authentication_information_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_ignore_unavailable_authentication_information_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ldap_ssl_option
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ldap_ssl_option(
string [] config_names,
ManagementLDAPSSLOption [] options
) {
this.Invoke("set_ldap_ssl_option", new object [] {
config_names,
options});
}
public System.IAsyncResult Beginset_ldap_ssl_option(string [] config_names,ManagementLDAPSSLOption [] options, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ldap_ssl_option", new object[] {
config_names,
options}, callback, asyncState);
}
public void Endset_ldap_ssl_option(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ldap_sso_option
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ldap_sso_option(
string [] config_names,
ManagementLDAPSSOOption [] options
) {
this.Invoke("set_ldap_sso_option", new object [] {
config_names,
options});
}
public System.IAsyncResult Beginset_ldap_sso_option(string [] config_names,ManagementLDAPSSOOption [] options, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ldap_sso_option", new object[] {
config_names,
options}, callback, asyncState);
}
public void Endset_ldap_sso_option(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ldap_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ldap_version(
string [] config_names,
long [] versions
) {
this.Invoke("set_ldap_version", new object [] {
config_names,
versions});
}
public System.IAsyncResult Beginset_ldap_version(string [] config_names,long [] versions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ldap_version", new object[] {
config_names,
versions}, callback, asyncState);
}
public void Endset_ldap_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_login_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_login_attribute(
string [] config_names,
string [] login_attributes
) {
this.Invoke("set_login_attribute", new object [] {
config_names,
login_attributes});
}
public System.IAsyncResult Beginset_login_attribute(string [] config_names,string [] login_attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_login_attribute", new object[] {
config_names,
login_attributes}, callback, asyncState);
}
public void Endset_login_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_login_filter
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_login_filter(
string [] config_names,
string [] filters
) {
this.Invoke("set_login_filter", new object [] {
config_names,
filters});
}
public System.IAsyncResult Beginset_login_filter(string [] config_names,string [] filters, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_login_filter", new object[] {
config_names,
filters}, callback, asyncState);
}
public void Endset_login_filter(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_login_name_attribute
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_login_name_attribute(
string [] config_names,
string [] attributes
) {
this.Invoke("set_login_name_attribute", new object [] {
config_names,
attributes});
}
public System.IAsyncResult Beginset_login_name_attribute(string [] config_names,string [] attributes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_login_name_attribute", new object[] {
config_names,
attributes}, callback, asyncState);
}
public void Endset_login_name_attribute(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_port(
string [] config_names,
long [] ports
) {
this.Invoke("set_port", new object [] {
config_names,
ports});
}
public System.IAsyncResult Beginset_port(string [] config_names,long [] ports, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_port", new object[] {
config_names,
ports}, callback, asyncState);
}
public void Endset_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_search_base_distinguished_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_search_base_distinguished_name(
string [] config_names,
string [] search_base_dns
) {
this.Invoke("set_search_base_distinguished_name", new object [] {
config_names,
search_base_dns});
}
public System.IAsyncResult Beginset_search_base_distinguished_name(string [] config_names,string [] search_base_dns, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_search_base_distinguished_name", new object[] {
config_names,
search_base_dns}, callback, asyncState);
}
public void Endset_search_base_distinguished_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_search_scope
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_search_scope(
string [] config_names,
ManagementLDAPSearchScope [] search_scopes
) {
this.Invoke("set_search_scope", new object [] {
config_names,
search_scopes});
}
public System.IAsyncResult Beginset_search_scope(string [] config_names,ManagementLDAPSearchScope [] search_scopes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_search_scope", new object[] {
config_names,
search_scopes}, callback, asyncState);
}
public void Endset_search_scope(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_search_time_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_search_time_limit(
string [] config_names,
long [] time_limits
) {
this.Invoke("set_search_time_limit", new object [] {
config_names,
time_limits});
}
public System.IAsyncResult Beginset_search_time_limit(string [] config_names,long [] time_limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_search_time_limit", new object[] {
config_names,
time_limits}, callback, asyncState);
}
public void Endset_search_time_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ssl_ca_certificate_file
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ssl_ca_certificate_file(
string [] config_names,
string [] ca_cert_files
) {
this.Invoke("set_ssl_ca_certificate_file", new object [] {
config_names,
ca_cert_files});
}
public System.IAsyncResult Beginset_ssl_ca_certificate_file(string [] config_names,string [] ca_cert_files, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ssl_ca_certificate_file", new object[] {
config_names,
ca_cert_files}, callback, asyncState);
}
public void Endset_ssl_ca_certificate_file(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ssl_check_peer_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ssl_check_peer_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_ssl_check_peer_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_ssl_check_peer_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ssl_check_peer_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_ssl_check_peer_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ssl_cipher
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ssl_cipher(
string [] config_names,
string [] [] ciphers
) {
this.Invoke("set_ssl_cipher", new object [] {
config_names,
ciphers});
}
public System.IAsyncResult Beginset_ssl_cipher(string [] config_names,string [] [] ciphers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ssl_cipher", new object[] {
config_names,
ciphers}, callback, asyncState);
}
public void Endset_ssl_cipher(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ssl_client_certificate
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ssl_client_certificate(
string [] config_names,
string [] certificates
) {
this.Invoke("set_ssl_client_certificate", new object [] {
config_names,
certificates});
}
public System.IAsyncResult Beginset_ssl_client_certificate(string [] config_names,string [] certificates, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ssl_client_certificate", new object[] {
config_names,
certificates}, callback, asyncState);
}
public void Endset_ssl_client_certificate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ssl_client_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_ssl_client_key(
string [] config_names,
string [] keys
) {
this.Invoke("set_ssl_client_key", new object [] {
config_names,
keys});
}
public System.IAsyncResult Beginset_ssl_client_key(string [] config_names,string [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ssl_client_key", new object[] {
config_names,
keys}, callback, asyncState);
}
public void Endset_ssl_client_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_warning_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/CertLDAPConfiguration",
RequestNamespace="urn:iControl:Management/CertLDAPConfiguration", ResponseNamespace="urn:iControl:Management/CertLDAPConfiguration")]
public void set_warning_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_warning_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_warning_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_warning_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_warning_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Content.Server.Chat.Managers;
using Content.Server.Players;
using Content.Server.Roles;
using Content.Server.Suspicion;
using Content.Server.Suspicion.Roles;
using Content.Server.Traitor.Uplink;
using Content.Server.Traitor.Uplink.Account;
using Content.Shared.CCVar;
using Content.Shared.Doors.Systems;
using Content.Shared.GameTicking;
using Content.Shared.MobState.Components;
using Content.Shared.Roles;
using Content.Shared.Sound;
using Content.Shared.Suspicion;
using Content.Shared.Traitor.Uplink;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Audio;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Maths;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using Timer = Robust.Shared.Timing.Timer;
namespace Content.Server.GameTicking.Rules;
/// <summary>
/// Simple GameRule that will do a TTT-like gamemode with traitors.
/// </summary>
public sealed class SuspicionRuleSystem : GameRuleSystem
{
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IChatManager _chatManager = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly IEntityManager _entities = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly SharedDoorSystem _doorSystem = default!;
public override string Prototype => "Suspicion";
private static readonly TimeSpan DeadCheckDelay = TimeSpan.FromSeconds(1);
private readonly HashSet<SuspicionRoleComponent> _traitors = new();
public IReadOnlyCollection<SuspicionRoleComponent> Traitors => _traitors;
[DataField("addedSound")] private SoundSpecifier _addedSound = new SoundPathSpecifier("/Audio/Misc/tatoralert.ogg");
private CancellationTokenSource _checkTimerCancel = new();
private TimeSpan? _endTime;
public TimeSpan? EndTime
{
get => _endTime;
set
{
_endTime = value;
SendUpdateToAll();
}
}
public TimeSpan RoundMaxTime { get; set; } = TimeSpan.FromSeconds(CCVars.SuspicionMaxTimeSeconds.DefaultValue);
public TimeSpan RoundEndDelay { get; set; } = TimeSpan.FromSeconds(10);
private const string TraitorID = "SuspicionTraitor";
private const string InnocentID = "SuspicionInnocent";
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<RulePlayerJobsAssignedEvent>(OnPlayersAssigned);
SubscribeLocalEvent<RoundStartAttemptEvent>(OnRoundStartAttempt);
SubscribeLocalEvent<RefreshLateJoinAllowedEvent>(OnLateJoinRefresh);
SubscribeLocalEvent<RoundRestartCleanupEvent>(Reset);
SubscribeLocalEvent<SuspicionRoleComponent, PlayerAttachedEvent>(OnPlayerAttached);
SubscribeLocalEvent<SuspicionRoleComponent, PlayerDetachedEvent>(OnPlayerDetached);
SubscribeLocalEvent<SuspicionRoleComponent, RoleAddedEvent>(OnRoleAdded);
SubscribeLocalEvent<SuspicionRoleComponent, RoleRemovedEvent>(OnRoleRemoved);
}
private void OnRoundStartAttempt(RoundStartAttemptEvent ev)
{
if (!Enabled)
return;
var minPlayers = _cfg.GetCVar(CCVars.SuspicionMinPlayers);
if (!ev.Forced && ev.Players.Length < minPlayers)
{
_chatManager.DispatchServerAnnouncement($"Not enough players readied up for the game! There were {ev.Players.Length} players readied up out of {minPlayers} needed.");
ev.Cancel();
return;
}
if (ev.Players.Length == 0)
{
_chatManager.DispatchServerAnnouncement("No players readied up! Can't start Suspicion.");
ev.Cancel();
return;
}
}
private void OnPlayersAssigned(RulePlayerJobsAssignedEvent ev)
{
if (!Enabled)
return;
var minTraitors = _cfg.GetCVar(CCVars.SuspicionMinTraitors);
var playersPerTraitor = _cfg.GetCVar(CCVars.SuspicionPlayersPerTraitor);
var traitorStartingBalance = _cfg.GetCVar(CCVars.SuspicionStartingBalance);
var list = new List<IPlayerSession>(ev.Players);
var prefList = new List<IPlayerSession>();
foreach (var player in list)
{
if (!ev.Profiles.ContainsKey(player.UserId) || player.AttachedEntity is not {} attached)
{
continue;
}
prefList.Add(player);
attached.EnsureComponent<SuspicionRoleComponent>();
}
var numTraitors = MathHelper.Clamp(ev.Players.Length / playersPerTraitor,
minTraitors, ev.Players.Length);
var traitors = new List<SuspicionTraitorRole>();
for (var i = 0; i < numTraitors; i++)
{
IPlayerSession traitor;
if(prefList.Count == 0)
{
if (list.Count == 0)
{
Logger.InfoS("preset", "Insufficient ready players to fill up with traitors, stopping the selection.");
break;
}
traitor = _random.PickAndTake(list);
Logger.InfoS("preset", "Insufficient preferred traitors, picking at random.");
}
else
{
traitor = _random.PickAndTake(prefList);
list.Remove(traitor);
Logger.InfoS("preset", "Selected a preferred traitor.");
}
var mind = traitor.Data.ContentData()?.Mind;
var antagPrototype = _prototypeManager.Index<AntagPrototype>(TraitorID);
DebugTools.AssertNotNull(mind?.OwnedEntity);
var traitorRole = new SuspicionTraitorRole(mind!, antagPrototype);
mind!.AddRole(traitorRole);
traitors.Add(traitorRole);
// creadth: we need to create uplink for the antag.
// PDA should be in place already, so we just need to
// initiate uplink account.
var uplinkAccount = new UplinkAccount(traitorStartingBalance, mind.OwnedEntity!);
var accounts = EntityManager.EntitySysManager.GetEntitySystem<UplinkAccountsSystem>();
accounts.AddNewAccount(uplinkAccount);
// try to place uplink
if (!EntityManager.EntitySysManager.GetEntitySystem<UplinkSystem>()
.AddUplink(mind.OwnedEntity!.Value, uplinkAccount))
continue;
}
foreach (var player in list)
{
var mind = player.Data.ContentData()?.Mind;
var antagPrototype = _prototypeManager.Index<AntagPrototype>(InnocentID);
DebugTools.AssertNotNull(mind);
mind!.AddRole(new SuspicionInnocentRole(mind, antagPrototype));
}
foreach (var traitor in traitors)
{
traitor.GreetSuspicion(traitors, _chatManager);
}
}
public override void Started()
{
_playerManager.PlayerStatusChanged += PlayerManagerOnPlayerStatusChanged;
RoundMaxTime = TimeSpan.FromSeconds(_cfg.GetCVar(CCVars.SuspicionMaxTimeSeconds));
EndTime = _timing.CurTime + RoundMaxTime;
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-suspicion-added-announcement"));
var filter = Filter.Empty()
.AddWhere(session => ((IPlayerSession) session).ContentData()?.Mind?.HasRole<SuspicionTraitorRole>() ?? false);
SoundSystem.Play(filter, _addedSound.GetSound(), AudioParams.Default);
_doorSystem.AccessType = SharedDoorSystem.AccessTypes.AllowAllNoExternal;
_checkTimerCancel = new CancellationTokenSource();
Timer.SpawnRepeating(DeadCheckDelay, CheckWinConditions, _checkTimerCancel.Token);
}
public override void Ended()
{
_doorSystem.AccessType = SharedDoorSystem.AccessTypes.Id;
EndTime = null;
_traitors.Clear();
_playerManager.PlayerStatusChanged -= PlayerManagerOnPlayerStatusChanged;
_checkTimerCancel.Cancel();
}
private void CheckWinConditions()
{
if (!Enabled || !_cfg.GetCVar(CCVars.GameLobbyEnableWin))
return;
var traitorsAlive = 0;
var innocentsAlive = 0;
foreach (var playerSession in _playerManager.ServerSessions)
{
if (playerSession.AttachedEntity is not {Valid: true} playerEntity
|| !_entities.TryGetComponent(playerEntity, out MobStateComponent? mobState)
|| !_entities.HasComponent<SuspicionRoleComponent>(playerEntity))
{
continue;
}
if (!mobState.IsAlive())
{
continue;
}
var mind = playerSession.ContentData()?.Mind;
if (mind != null && mind.HasRole<SuspicionTraitorRole>())
traitorsAlive++;
else
innocentsAlive++;
}
if (innocentsAlive + traitorsAlive == 0)
{
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-suspicion-check-winner-stalemate"));
EndRound(Victory.Stalemate);
}
else if (traitorsAlive == 0)
{
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-suspicion-check-winner-station-win"));
EndRound(Victory.Innocents);
}
else if (innocentsAlive == 0)
{
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-suspicion-check-winner-traitor-win"));
EndRound(Victory.Traitors);
}
else if (_timing.CurTime > _endTime)
{
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-suspicion-traitor-time-has-run-out"));
EndRound(Victory.Innocents);
}
}
private enum Victory
{
Stalemate,
Innocents,
Traitors
}
private void EndRound(Victory victory)
{
string text;
switch (victory)
{
case Victory.Innocents:
text = Loc.GetString("rule-suspicion-end-round-innocents-victory");
break;
case Victory.Traitors:
text = Loc.GetString("rule-suspicion-end-round-traitors-victory");
break;
default:
text = Loc.GetString("rule-suspicion-end-round-nobody-victory");
break;
}
GameTicker.EndRound(text);
_chatManager.DispatchServerAnnouncement(Loc.GetString("rule-restarting-in-seconds", ("seconds", (int) RoundEndDelay.TotalSeconds)));
_checkTimerCancel.Cancel();
Timer.Spawn(RoundEndDelay, () => GameTicker.RestartRound());
}
private void PlayerManagerOnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus == SessionStatus.InGame)
{
SendUpdateTimerMessage(e.Session);
}
}
private void SendUpdateToAll()
{
foreach (var player in _playerManager.ServerSessions.Where(p => p.Status == SessionStatus.InGame))
{
SendUpdateTimerMessage(player);
}
}
private void SendUpdateTimerMessage(IPlayerSession player)
{
var msg = new SuspicionMessages.SetSuspicionEndTimerMessage
{
EndTime = EndTime
};
EntityManager.EntityNetManager?.SendSystemNetworkMessage(msg, player.ConnectedClient);
}
public void AddTraitor(SuspicionRoleComponent role)
{
if (!_traitors.Add(role))
{
return;
}
foreach (var traitor in _traitors)
{
traitor.AddAlly(role);
}
role.SetAllies(_traitors);
}
public void RemoveTraitor(SuspicionRoleComponent role)
{
if (!_traitors.Remove(role))
{
return;
}
foreach (var traitor in _traitors)
{
traitor.RemoveAlly(role);
}
role.ClearAllies();
}
private void Reset(RoundRestartCleanupEvent ev)
{
EndTime = null;
_traitors.Clear();
}
private void OnPlayerDetached(EntityUid uid, SuspicionRoleComponent component, PlayerDetachedEvent args)
{
component.SyncRoles();
}
private void OnPlayerAttached(EntityUid uid, SuspicionRoleComponent component, PlayerAttachedEvent args)
{
component.SyncRoles();
}
private void OnRoleAdded(EntityUid uid, SuspicionRoleComponent component, RoleAddedEvent args)
{
if (args.Role is not SuspicionRole role) return;
component.Role = role;
}
private void OnRoleRemoved(EntityUid uid, SuspicionRoleComponent component, RoleRemovedEvent args)
{
if (args.Role is not SuspicionRole) return;
component.Role = null;
}
private void OnLateJoinRefresh(RefreshLateJoinAllowedEvent ev)
{
if (!Enabled)
return;
ev.Disallow();
}
}
| |
using System;
namespace Semmle.Util
{
/// <summary>
/// An instance of this class is used to store the computed line count metrics (of
/// various different types) for a piece of text.
/// </summary>
public sealed class LineCounts
{
//#################### PROPERTIES ####################
#region
/// <summary>
/// The number of lines in the text that contain code.
/// </summary>
public int Code { get; set; }
/// <summary>
/// The number of lines in the text that contain comments.
/// </summary>
public int Comment { get; set; }
/// <summary>
/// The total number of lines in the text.
/// </summary>
public int Total { get; set; }
#endregion
//#################### PUBLIC METHODS ####################
#region
public override bool Equals(object? other)
{
return other is LineCounts rhs &&
Total == rhs.Total &&
Code == rhs.Code &&
Comment == rhs.Comment;
}
public override int GetHashCode()
{
return Total ^ Code ^ Comment;
}
public override string ToString()
{
return "Total: " + Total + " Code: " + Code + " Comment: " + Comment;
}
#endregion
}
/// <summary>
/// This class can be used to compute line count metrics of various different types
/// (code, comment and total) for a piece of text.
/// </summary>
public static class LineCounter
{
//#################### NESTED CLASSES ####################
#region
/// <summary>
/// An instance of this class keeps track of the contextual information required during line counting.
/// </summary>
private class Context
{
/// <summary>
/// The index of the current character under consideration.
/// </summary>
public int CurIndex { get; set; }
/// <summary>
/// Whether or not the current line under consideration contains any code.
/// </summary>
public bool HasCode { get; set; }
/// <summary>
/// Whether or not the current line under consideration contains a comment.
/// </summary>
public bool HasComment { get; set; }
}
#endregion
//#################### PUBLIC METHODS ####################
#region
/// <summary>
/// Computes line count metrics for the specified input text.
/// </summary>
/// <param name="input">The input text for which to compute line count metrics.</param>
/// <returns>The computed metrics.</returns>
public static LineCounts ComputeLineCounts(string input)
{
var counts = new LineCounts();
var context = new Context();
char? cur, prev = null;
while ((cur = GetNext(input, context)) is not null)
{
if (IsNewLine(cur))
{
RegisterNewLine(counts, context);
cur = null;
}
else if (cur == '*' && prev == '/')
{
ReadMultiLineComment(input, counts, context);
cur = null;
}
else if (cur == '/' && prev == '/')
{
ReadEOLComment(input, context);
context.HasComment = true;
cur = null;
}
else if (cur == '"')
{
ReadRestOfString(input, context);
context.HasCode = true;
cur = null;
}
else if (cur == '\'')
{
ReadRestOfChar(input, context);
context.HasCode = true;
cur = null;
}
else if (!IsWhitespace(cur) && cur != '/') // exclude '/' to avoid counting comments as code
{
context.HasCode = true;
}
prev = cur;
}
// The final line of text should always be counted, even if it's empty.
RegisterNewLine(counts, context);
return counts;
}
#endregion
//#################### PRIVATE METHODS ####################
#region
/// <summary>
/// Gets the next character to be considered from the input text and updates the current character index accordingly.
/// </summary>
/// <param name="input">The input text for which we are computing line count metrics.</param>
/// <param name="context">The contextual information required during line counting.</param>
/// <returns></returns>
private static char? GetNext(string input, Context context)
{
return input is null || context.CurIndex >= input.Length ?
(char?)null :
input[context.CurIndex++];
}
/// <summary>
/// Determines whether or not the specified character equals '\n'.
/// </summary>
/// <param name="c">The character to test.</param>
/// <returns>true, if the specified character equals '\n', or false otherwise.</returns>
private static bool IsNewLine(char? c)
{
return c == '\n';
}
/// <summary>
/// Determines whether or not the specified character should be considered to be whitespace.
/// </summary>
/// <param name="c">The character to test.</param>
/// <returns>true, if the specified character should be considered to be whitespace, or false otherwise.</returns>
private static bool IsWhitespace(char? c)
{
return c == ' ' || c == '\t' || c == '\r';
}
/// <summary>
/// Consumes the input text up to the end of the current line (not including any '\n').
/// This is used to consume an end-of-line comment (i.e. a //-style comment).
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadEOLComment(string input, Context context)
{
char? c;
do
{
c = GetNext(input, context);
} while (c is not null && !IsNewLine(c));
// If we reached the end of a line (as opposed to reaching the end of the text),
// put the '\n' back so that it can be handled by the normal newline processing
// code.
if (IsNewLine(c))
--context.CurIndex;
}
/// <summary>
/// Consumes the input text up to the end of a multi-line comment.
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="counts">The line count metrics for the input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadMultiLineComment(string input, LineCounts counts, Context context)
{
char? cur = '\0', prev = null;
context.HasComment = true;
while (cur is not null && ((cur = GetNext(input, context)) != '/' || prev != '*'))
{
if (IsNewLine(cur))
{
RegisterNewLine(counts, context);
context.HasComment = true;
}
prev = cur;
}
}
/// <summary>
/// Consumes the input text up to the end of a character literal, e.g. '\t'.
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadRestOfChar(string input, Context context)
{
if (GetNext(input, context) == '\\')
{
GetNext(input, context);
}
GetNext(input, context);
}
/// <summary>
/// Consumes the input text up to the end of a string literal, e.g. "Wibble".
/// </summary>
/// <param name="input">The input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void ReadRestOfString(string input, Context context)
{
char? cur = '\0';
var numSlashes = 0;
while (cur is not null && ((cur = GetNext(input, context)) != '"' || (numSlashes % 2 != 0)))
{
if (cur == '\\')
++numSlashes;
else
numSlashes = 0;
}
}
/// <summary>
/// Updates the line count metrics when a newline character is seen, and resets
/// the code and comment flags in the context ready to process the next line.
/// </summary>
/// <param name="counts">The line count metrics for the input text.</param>
/// <param name="context">The contextual information required during line counting.</param>
private static void RegisterNewLine(LineCounts counts, Context context)
{
++counts.Total;
if (context.HasCode)
{
++counts.Code;
context.HasCode = false;
}
if (context.HasComment)
{
++counts.Comment;
context.HasComment = false;
}
}
#endregion
}
}
| |
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Image (AMI) description.
/// </summary>
[XmlRootAttribute(IsNullable = false)]
public class Image
{
private string imageIdField;
private string imageLocationField;
private string imageStateField;
private string ownerIdField;
private string visibilityField;
// obsolete, to be removed
private List<string> productCodeField;
// replacement for string list of product codes
private List<ProductCode> productCodesField;
private string architectureField;
private string imageTypeField;
private string kernelIdField;
private string ramdiskIdField;
private string platformField;
private StateReason stateReasonField;
private string imageOwnerAliasField;
private string nameField;
private string descriptionField;
private string rootDeviceTypeField;
private string rootDeviceNameField;
private List<BlockDeviceMapping> blockDeviceMappingField;
private string virtualizationTypeField;
private List<Tag> tagField;
private string hypervisorField;
/// <summary>
/// The ID of the AMI.
/// </summary>
[XmlElementAttribute(ElementName = "ImageId")]
public string ImageId
{
get { return this.imageIdField; }
set { this.imageIdField = value; }
}
/// <summary>
/// Sets the ID of the AMI.
/// </summary>
/// <param name="imageId">The ID of the AMI.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithImageId(string imageId)
{
this.imageIdField = imageId;
return this;
}
/// <summary>
/// Checks if ImageId property is set
/// </summary>
/// <returns>true if ImageId property is set</returns>
public bool IsSetImageId()
{
return this.imageIdField != null;
}
/// <summary>
/// The location of the AMI.
/// </summary>
[XmlElementAttribute(ElementName = "ImageLocation")]
public string ImageLocation
{
get { return this.imageLocationField; }
set { this.imageLocationField = value; }
}
/// <summary>
/// Sets the location of the AMI.
/// </summary>
/// <param name="imageLocation">The location of the AMI.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithImageLocation(string imageLocation)
{
this.imageLocationField = imageLocation;
return this;
}
/// <summary>
/// Checks if ImageLocation property is set
/// </summary>
/// <returns>true if ImageLocation property is set</returns>
public bool IsSetImageLocation()
{
return this.imageLocationField != null;
}
/// <summary>
/// Current state of the AMI.
/// </summary>
[XmlElementAttribute(ElementName = "ImageState")]
public string ImageState
{
get { return this.imageStateField; }
set { this.imageStateField = value; }
}
/// <summary>
/// Sets current state of the AMI.
/// </summary>
/// <param name="imageState">Current state of the AMI.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithImageState(string imageState)
{
this.imageStateField = imageState;
return this;
}
/// <summary>
/// Checks if ImageState property is set
/// </summary>
/// <returns>true if ImageState property is set</returns>
public bool IsSetImageState()
{
return this.imageStateField != null;
}
/// <summary>
/// AWS Access Key ID of the image owner.
/// </summary>
[XmlElementAttribute(ElementName = "OwnerId")]
public string OwnerId
{
get { return this.ownerIdField; }
set { this.ownerIdField = value; }
}
/// <summary>
/// Sets the AWS Access Key ID of the image owner.
/// </summary>
/// <param name="ownerId">AWS Access Key ID of the image owner.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithOwnerId(string ownerId)
{
this.ownerIdField = ownerId;
return this;
}
/// <summary>
/// Checks if OwnerId property is set
/// </summary>
/// <returns>true if OwnerId property is set</returns>
public bool IsSetOwnerId()
{
return this.ownerIdField != null;
}
/// <summary>
/// Image visibility.
/// Valid values: public | private
/// </summary>
[XmlElementAttribute(ElementName = "Visibility")]
public string Visibility
{
get { return this.visibilityField; }
set { this.visibilityField = value; }
}
/// <summary>
/// Sets the image visibility.
/// </summary>
/// <param name="visibility">Visibility - public or private</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithVisibility(string visibility)
{
this.visibilityField = visibility;
return this;
}
/// <summary>
/// Checks if Visibility property is set
/// </summary>
/// <returns>true if Visibility property is set</returns>
public bool IsSetVisibility()
{
return this.visibilityField != null;
}
/// <summary>
/// Product codes of the AMI
/// </summary>
[XmlElementAttribute(ElementName = "ProductCodeId")]
[Obsolete("This member has been deprecated and will be removed in a future release. Please use the ProductCodes member instead.")]
public List<string> ProductCode
{
get
{
if (this.productCodeField == null)
{
this.productCodeField = new List<string>();
}
return this.productCodeField;
}
set { this.productCodeField = value; }
}
/// <summary>
/// Sets the product codes of the AMI
/// </summary>
/// <param name="list">Product codes of the AMI</param>
/// <returns>this instance</returns>
[Obsolete("This member has been deprecated and will be removed in a future release. Please use the WithProductCodes member instead.")]
public Image WithProductCode(params string[] list)
{
foreach (string item in list)
{
ProductCode.Add(item);
}
return this;
}
/// <summary>
/// Checks if ProductCode property is set
/// </summary>
/// <returns>true if ProductCode property is set</returns>
[Obsolete("This member has been deprecated and will be removed in a future release. Please use the IsSetProductCodes member instead.")]
public bool IsSetProductCode()
{
return (ProductCode.Count > 0);
}
/// <summary>
/// Product codes attached to this instance.
/// </summary>
[XmlElementAttribute(ElementName = "ProductCodes")]
public List<ProductCode> ProductCodes
{
get
{
if (this.productCodesField == null)
{
this.productCodesField = new List<ProductCode>();
}
return this.productCodesField;
}
set { this.productCodesField = value; }
}
/// <summary>
/// Sets the product codes attached to this instance.
/// </summary>
/// <param name="list">Product codes attached to this instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithProductCodes(params ProductCode[] list)
{
foreach (ProductCode item in list)
{
ProductCodes.Add(item);
}
return this;
}
/// <summary>
/// Checks if ProductCodes property is set
/// </summary>
/// <returns>true if ProductCodes property is set</returns>
public bool IsSetProductCodes()
{
return (ProductCodes.Count > 0);
}
/// <summary>
/// The architecture of the image.
/// </summary>
[XmlElementAttribute(ElementName = "Architecture")]
public string Architecture
{
get { return this.architectureField; }
set { this.architectureField = value; }
}
/// <summary>
/// Sets the architecture of the image.
/// </summary>
/// <param name="architecture">The architecture of the image.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithArchitecture(string architecture)
{
this.architectureField = architecture;
return this;
}
/// <summary>
/// Checks if Architecture property is set
/// </summary>
/// <returns>true if Architecture property is set</returns>
public bool IsSetArchitecture()
{
return this.architectureField != null;
}
/// <summary>
/// The image type.
/// </summary>
[XmlElementAttribute(ElementName = "ImageType")]
public string ImageType
{
get { return this.imageTypeField; }
set { this.imageTypeField = value; }
}
/// <summary>
/// Sets the image type.
/// </summary>
/// <param name="imageType">The type of image</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithImageType(string imageType)
{
this.imageTypeField = imageType;
return this;
}
/// <summary>
/// Checks if ImageType property is set
/// </summary>
/// <returns>true if ImageType property is set</returns>
public bool IsSetImageType()
{
return this.imageTypeField != null;
}
/// <summary>
/// The kernel associated with the image, if any.
/// Only applicable for machine images.
/// </summary>
[XmlElementAttribute(ElementName = "KernelId")]
public string KernelId
{
get { return this.kernelIdField; }
set { this.kernelIdField = value; }
}
/// <summary>
/// Sets the kernel associated with the image.
/// </summary>
/// <param name="kernelId">The kernel associated with the image, if any.
/// Only applicable for machine images.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithKernelId(string kernelId)
{
this.kernelIdField = kernelId;
return this;
}
/// <summary>
/// Checks if KernelId property is set
/// </summary>
/// <returns>true if KernelId property is set</returns>
public bool IsSetKernelId()
{
return this.kernelIdField != null;
}
/// <summary>
/// The RAM disk associated with the image, if any.
/// Only applicable for machine images.
/// </summary>
[XmlElementAttribute(ElementName = "RamdiskId")]
public string RamdiskId
{
get { return this.ramdiskIdField; }
set { this.ramdiskIdField = value; }
}
/// <summary>
/// Sets the RAM disk associated with the image.
/// </summary>
/// <param name="ramdiskId">The RAM disk associated with the image, if any.
/// Only applicable for machine images.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithRamdiskId(string ramdiskId)
{
this.ramdiskIdField = ramdiskId;
return this;
}
/// <summary>
/// Checks if RamdiskId property is set
/// </summary>
/// <returns>true if RamdiskId property is set</returns>
public bool IsSetRamdiskId()
{
return this.ramdiskIdField != null;
}
/// <summary>
/// The operating platform of the instance.
/// </summary>
[XmlElementAttribute(ElementName = "Platform")]
public string Platform
{
get { return this.platformField; }
set { this.platformField = value; }
}
/// <summary>
/// Sets the operating platform of the instance.
/// </summary>
/// <param name="platform">The operating platform of the instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithPlatform(string platform)
{
this.platformField = platform;
return this;
}
/// <summary>
/// Checks if Platform property is set
/// </summary>
/// <returns>true if Platform property is set</returns>
public bool IsSetPlatform()
{
return this.platformField != null;
}
/// <summary>
/// The reason for the state change.
/// </summary>
[XmlElementAttribute(ElementName = "StateReason")]
public StateReason StateReason
{
get { return this.stateReasonField; }
set { this.stateReasonField = value; }
}
/// <summary>
/// Ses the reason for the state change.
/// </summary>
/// <param name="stateReason">The reason for the state change.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithStateReason(StateReason stateReason)
{
this.stateReasonField = stateReason;
return this;
}
/// <summary>
/// Checks if StateReason property is set
/// </summary>
/// <returns>true if StateReason property is set</returns>
public bool IsSetStateReason()
{
return this.stateReasonField != null;
}
/// <summary>
/// The AWS account alias (e.g., "amazon") or AWS
/// account ID that owns the AMI.
/// </summary>
[XmlElementAttribute(ElementName = "ImageOwnerAlias")]
public string ImageOwnerAlias
{
get { return this.imageOwnerAliasField; }
set { this.imageOwnerAliasField = value; }
}
/// <summary>
/// Sets the AWS account alias (e.g., "amazon") or AWS
/// account ID that owns the AMI.
/// </summary>
/// <param name="imageOwnerAlias">The AWS account alias (e.g., "amazon") or AWS
/// account ID that owns the AMI.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithImageOwnerAlias(string imageOwnerAlias)
{
this.imageOwnerAliasField = imageOwnerAlias;
return this;
}
/// <summary>
/// Checks if ImageOwnerAlias property is set
/// </summary>
/// <returns>true if ImageOwnerAlias property is set</returns>
public bool IsSetImageOwnerAlias()
{
return this.imageOwnerAliasField != null;
}
/// <summary>
/// The name of the AMI.
/// </summary>
[XmlElementAttribute(ElementName = "Name")]
public string Name
{
get { return this.nameField; }
set { this.nameField = value; }
}
/// <summary>
/// Sets the name of the AMI.
/// </summary>
/// <param name="name">The name of the AMI.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithName(string name)
{
this.nameField = name;
return this;
}
/// <summary>
/// Checks if Name property is set
/// </summary>
/// <returns>true if Name property is set</returns>
public bool IsSetName()
{
return this.nameField != null;
}
/// <summary>
/// The description of the AMI.
/// </summary>
[XmlElementAttribute(ElementName = "Description")]
public string Description
{
get { return this.descriptionField; }
set { this.descriptionField = value; }
}
/// <summary>
/// Sets the description of the AMI.
/// </summary>
/// <param name="description">The description of the AMI.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithDescription(string description)
{
this.descriptionField = description;
return this;
}
/// <summary>
/// Checks if Description property is set
/// </summary>
/// <returns>true if Description property is set</returns>
public bool IsSetDescription()
{
return this.descriptionField != null;
}
/// <summary>
/// The root device type used by the AMI.
/// The AMI can use an Amazon EBS or instance store root device.
/// </summary>
[XmlElementAttribute(ElementName = "RootDeviceType")]
public string RootDeviceType
{
get { return this.rootDeviceTypeField; }
set { this.rootDeviceTypeField = value; }
}
/// <summary>
/// Sets the root device type used by the AMI.
/// </summary>
/// <param name="rootDeviceType">The root device type used by the AMI. The AMI
/// can use an Amazon EBS or instance store root device.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithRootDeviceType(string rootDeviceType)
{
this.rootDeviceTypeField = rootDeviceType;
return this;
}
/// <summary>
/// Checks if RootDeviceType property is set
/// </summary>
/// <returns>true if RootDeviceType property is set</returns>
public bool IsSetRootDeviceType()
{
return this.rootDeviceTypeField != null;
}
/// <summary>
/// The root device name (e.g., /dev/sda1).
/// </summary>
[XmlElementAttribute(ElementName = "RootDeviceName")]
public string RootDeviceName
{
get { return this.rootDeviceNameField; }
set { this.rootDeviceNameField = value; }
}
/// <summary>
/// Sets the root device name (e.g., /dev/sda1).
/// </summary>
/// <param name="rootDeviceName">The root device name (e.g., /dev/sda1).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithRootDeviceName(string rootDeviceName)
{
this.rootDeviceNameField = rootDeviceName;
return this;
}
/// <summary>
/// Checks if RootDeviceName property is set
/// </summary>
/// <returns>true if RootDeviceName property is set</returns>
public bool IsSetRootDeviceName()
{
return this.rootDeviceNameField != null;
}
/// <summary>
/// One or more specifications of how block devices are exposed to the instance.
/// </summary>
[XmlElementAttribute(ElementName = "BlockDeviceMapping")]
public List<BlockDeviceMapping> BlockDeviceMapping
{
get
{
if (this.blockDeviceMappingField == null)
{
this.blockDeviceMappingField = new List<BlockDeviceMapping>();
}
return this.blockDeviceMappingField;
}
set { this.blockDeviceMappingField = value; }
}
/// <summary>
/// Sets specifications of how block devices are exposed to the instance.
/// </summary>
/// <param name="list">Specifies how block devices are exposed to the
/// instance.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithBlockDeviceMapping(params BlockDeviceMapping[] list)
{
foreach (BlockDeviceMapping item in list)
{
BlockDeviceMapping.Add(item);
}
return this;
}
/// <summary>
/// Checks if BlockDeviceMapping property is set
/// </summary>
/// <returns>true if BlockDeviceMapping property is set</returns>
public bool IsSetBlockDeviceMapping()
{
return (BlockDeviceMapping.Count > 0);
}
/// <summary>
/// Specifies whether the Amazon EC2 instance is a hardware virtual
/// machine (HVM) or a para-virtual machine (PVM).
/// </summary>
[XmlElementAttribute(ElementName = "VirtualizationType")]
public string VirtualizationType
{
get { return this.virtualizationTypeField; }
set { this.virtualizationTypeField = value; }
}
/// <summary>
/// Sets whether the Amazon EC2 instance is a hardware virtual
/// machine (HVM) or a para-virtual machine (PVM).
/// </summary>
/// <param name="virtualizationType">Specifies whether the Amazon EC2 instance is a
/// hardware virtual machine
/// (HVM) or a para-virtual machine (PVM).</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithVirtualizationType(string virtualizationType)
{
this.virtualizationTypeField = virtualizationType;
return this;
}
/// <summary>
/// Checks if VirtualizationType property is set
/// </summary>
/// <returns>true if VirtualizationType property is set</returns>
public bool IsSetVirtualizationType()
{
return this.virtualizationTypeField != null;
}
/// <summary>
/// A list of tags for the Image.
/// </summary>
[XmlElementAttribute(ElementName = "Tag")]
public List<Tag> Tag
{
get
{
if (this.tagField == null)
{
this.tagField = new List<Tag>();
}
return this.tagField;
}
set { this.tagField = value; }
}
/// <summary>
/// Sets the list of tags for the Image.
/// </summary>
/// <param name="list">A list of tags for the Image.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithTag(params Tag[] list)
{
foreach (Tag item in list)
{
Tag.Add(item);
}
return this;
}
/// <summary>
/// Checks if Tag property is set
/// </summary>
/// <returns>true if Tag property is set</returns>
public bool IsSetTag()
{
return (Tag.Count > 0);
}
/// <summary>
/// The image hypervisor type.
/// </summary>
[XmlElementAttribute(ElementName = "Hypervisor")]
public string Hypervisor
{
get { return this.hypervisorField; }
set { this.hypervisorField = value; }
}
/// <summary>
/// Sets the image hypervisor type.
/// </summary>
/// <param name="hypervisor">Hypervisor property</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Image WithHypervisor(string hypervisor)
{
this.hypervisorField = hypervisor;
return this;
}
/// <summary>
/// Checks if Hypervisor property is set
/// </summary>
/// <returns>true if Hypervisor property is set</returns>
public bool IsSetHypervisor()
{
return this.hypervisorField != null;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2006 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;
using NUnit.TestUtilities;
using NUnit.TestUtilities.Collections;
using NUnit.TestUtilities.Comparers;
#if !PORTABLE && !NETSTANDARD1_6
using System.Data;
#endif
#if !NET_2_0
using System.Linq;
#endif
namespace NUnit.Framework.Assertions
{
/// <summary>
/// Test Library for the NUnit CollectionAssert class.
/// </summary>
[TestFixture()]
public class CollectionAssertTest
{
#region AllItemsAreInstancesOfType
[Test()]
public void ItemsOfType()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string));
}
[Test]
public void ItemsOfTypeFailure()
{
var collection = new SimpleObjectCollection("x", "y", new object());
var expectedMessage =
" Expected: all items instance of <System.String>" + Environment.NewLine +
" But was: < \"x\", \"y\", <System.Object> >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string)));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreNotNull
[Test()]
public void ItemsNotNull()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreNotNull(collection);
}
[Test]
public void ItemsNotNullFailure()
{
var collection = new SimpleObjectCollection("x", null, "z");
var expectedMessage =
" Expected: all items not null" + Environment.NewLine +
" But was: < \"x\", null, \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreNotNull(collection));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreUnique
[Test]
public void Unique_WithObjects()
{
CollectionAssert.AllItemsAreUnique(
new SimpleObjectCollection(new object(), new object(), new object()));
}
[Test]
public void Unique_WithStrings()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "z"));
}
[Test]
public void Unique_WithNull()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", null, "z"));
}
[Test]
public void UniqueFailure()
{
var expectedMessage =
" Expected: all items unique" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "x")));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void UniqueFailure_WithTwoNulls()
{
Assert.Throws<AssertionException>(
() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", null, "y", null, "z")));
}
#endregion
#region AreEqual
[Test]
public void AreEqual()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
Assert.AreEqual(set1,set2);
}
[Test]
public void AreEqualFailCount()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "z", "a");
var expectedMessage =
" Expected is <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements, actual is <NUnit.TestUtilities.Collections.SimpleObjectList> with 4 elements" + Environment.NewLine +
" Values differ at index [3]" + Environment.NewLine +
" Extra: < \"a\" >";
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqualFail()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "a");
var expectedMessage =
" Expected and actual are both <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements" + Environment.NewLine +
" Values differ at index [2]" + Environment.NewLine +
" String lengths are both 1. Strings differ at index 0." + Environment.NewLine +
" Expected: \"z\"" + Environment.NewLine +
" But was: \"a\"" + Environment.NewLine +
" -----------^" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1,set2,new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqual_HandlesNull()
{
object[] set1 = new object[3];
object[] set2 = new object[3];
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
}
[Test]
public void EnsureComparerIsUsed()
{
// Create two collections
int[] array1 = new int[2];
int[] array2 = new int[2];
array1[0] = 4;
array1[1] = 5;
array2[0] = 99;
array2[1] = -99;
CollectionAssert.AreEqual(array1, array2, new AlwaysEqualComparer());
}
[Test]
public void AreEqual_UsingIterator()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, CountToThree());
}
IEnumerable CountToThree()
{
yield return 1;
yield return 2;
yield return 3;
}
[Test]
public void AreEqual_UsingIterator_Fails()
{
int[] array = new int[] { 1, 3, 5 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, CountToThree()); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [1]").And.
Contains("Expected: 3").And.
Contains("But was: 2"));
}
#if !NET_2_0
[Test]
public void AreEqual_UsingLinqQuery()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, array.Select((item) => item));
}
[Test]
public void AreEqual_UsingLinqQuery_Fails()
{
int[] array = new int[] { 1, 2, 3 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, array.Select((item) => item * 2)); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [0]").And.
Contains("Expected: 1").And.
Contains("But was: 2"));
}
#endif
#endregion
#region AreEquivalent
[Test]
public void Equivalent()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("z", "y", "x");
CollectionAssert.AreEquivalent(set1,set2);
}
[Test]
public void EquivalentFailOne()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("x", "y", "x");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void EquivalentFailTwo()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "x");
ICollection set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"x\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEquivalentHandlesNull()
{
ICollection set1 = new SimpleObjectCollection(null, "x", null, "z");
ICollection set2 = new SimpleObjectCollection("z", null, "x", null);
CollectionAssert.AreEquivalent(set1,set2);
}
#endregion
#region AreNotEqual
[Test]
public void AreNotEqual()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
CollectionAssert.AreNotEqual(set1,set2,"test");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test");
CollectionAssert.AreNotEqual(set1,set2,"test {0}","1");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test {0}","1");
}
[Test]
public void AreNotEqual_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: not equal to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEqual(set1, set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreNotEqual_HandlesNull()
{
object[] set1 = new object[3];
var set2 = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
}
#endregion
#region AreNotEquivalent
[Test]
public void NotEquivalent()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
[Test]
public void NotEquivalent_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "z", "y");
var expectedMessage =
" Expected: not equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void NotEquivalentHandlesNull()
{
var set1 = new SimpleObjectCollection("x", null, "z");
var set2 = new SimpleObjectCollection("x", null, "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
#endregion
#region Contains
[Test]
public void Contains_IList()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.Contains(list, "x");
}
[Test]
public void Contains_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.Contains(collection,"x");
}
[Test]
public void ContainsFails_ILIst()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: collection containing \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: collection containing \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(collection,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyIList()
{
var list = new SimpleObjectList();
var expectedMessage =
" Expected: collection containing \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyICollection()
{
var ca = new SimpleObjectCollection(new object[0]);
var expectedMessage =
" Expected: collection containing \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(ca,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsNull_IList()
{
Object[] oa = new object[] { 1, 2, 3, null, 4, 5 };
CollectionAssert.Contains( oa, null );
}
[Test]
public void ContainsNull_ICollection()
{
var ca = new SimpleObjectCollection(new object[] { 1, 2, 3, null, 4, 5 });
CollectionAssert.Contains( ca, null );
}
#endregion
#region DoesNotContain
[Test]
public void DoesNotContain()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"a");
}
[Test]
public void DoesNotContain_Empty()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"x");
}
[Test]
public void DoesNotContain_Fails()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: not collection containing \"y\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.DoesNotContain(list,"y"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region IsSubsetOf
[Test]
public void IsSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
[Test]
public void IsSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
var expectedMessage =
" Expected: subset of < \"y\", \"z\", \"a\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsSubsetOf(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
#endregion
#region IsNotSubsetOf
[Test]
public void IsNotSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
Assert.That(set1, Is.Not.SubsetOf(set2));
}
[Test]
public void IsNotSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
var expectedMessage =
" Expected: not subset of < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsNotSubsetOf(set2,set1));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsNotSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
}
#endregion
#region IsOrdered
[Test]
public void IsOrdered()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Fails()
{
var list = new SimpleObjectList("x", "z", "y");
var expectedMessage =
" Expected: collection ordered" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsOrdered(list));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsOrdered_Allows_adjacent_equal_values()
{
var list = new SimpleObjectList("x", "x", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Handles_null()
{
var list = new SimpleObjectList("x", null, "z");
var ex = Assert.Throws<ArgumentNullException>(() => CollectionAssert.IsOrdered(list));
Assert.That(ex.Message, Does.Contain("index 1"));
}
[Test]
public void IsOrdered_ContainedTypesMustBeCompatible()
{
var list = new SimpleObjectList(1, "x");
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_TypesMustImplementIComparable()
{
var list = new SimpleObjectList(new object(), new object());
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_Handles_custom_comparison()
{
var list = new SimpleObjectList(new object(), new object());
CollectionAssert.IsOrdered(list, new AlwaysEqualComparer());
}
[Test]
public void IsOrdered_Handles_custom_comparison2()
{
var list = new SimpleObjectList(2, 1);
CollectionAssert.IsOrdered(list, new TestComparer());
}
#endregion
#region Equals
[Test]
public void EqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.Equals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used for Assertions"));
}
[Test]
public void ReferenceEqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions"));
}
#endregion
}
}
| |
namespace Lucene.Net.Search
{
using NUnit.Framework;
/*
* 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 Term = Lucene.Net.Index.Term;
/// <summary>
/// TestExplanations subclass focusing on basic query types
/// </summary>
[TestFixture]
public class TestSimpleExplanations : TestExplanations
{
// we focus on queries that don't rewrite to other queries.
// if we get those covered well, then the ones that rewrite should
// also be covered.
/* simple term tests */
[Test]
public virtual void TestT1()
{
Qtest(new TermQuery(new Term(FIELD, "w1")), new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestT2()
{
TermQuery termQuery = new TermQuery(new Term(FIELD, "w1"));
termQuery.Boost = 100;
Qtest(termQuery, new int[] { 0, 1, 2, 3 });
}
/* MatchAllDocs */
[Test]
public virtual void TestMA1()
{
Qtest(new MatchAllDocsQuery(), new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMA2()
{
Query q = new MatchAllDocsQuery();
q.Boost = 1000;
Qtest(q, new int[] { 0, 1, 2, 3 });
}
/* some simple phrase tests */
[Test]
public virtual void TestP1()
{
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Add(new Term(FIELD, "w1"));
phraseQuery.Add(new Term(FIELD, "w2"));
Qtest(phraseQuery, new int[] { 0 });
}
[Test]
public virtual void TestP2()
{
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Add(new Term(FIELD, "w1"));
phraseQuery.Add(new Term(FIELD, "w3"));
Qtest(phraseQuery, new int[] { 1, 3 });
}
[Test]
public virtual void TestP3()
{
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Slop = 1;
phraseQuery.Add(new Term(FIELD, "w1"));
phraseQuery.Add(new Term(FIELD, "w2"));
Qtest(phraseQuery, new int[] { 0, 1, 2 });
}
[Test]
public virtual void TestP4()
{
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Slop = 1;
phraseQuery.Add(new Term(FIELD, "w2"));
phraseQuery.Add(new Term(FIELD, "w3"));
Qtest(phraseQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestP5()
{
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Slop = 1;
phraseQuery.Add(new Term(FIELD, "w3"));
phraseQuery.Add(new Term(FIELD, "w2"));
Qtest(phraseQuery, new int[] { 1, 3 });
}
[Test]
public virtual void TestP6()
{
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Slop = 2;
phraseQuery.Add(new Term(FIELD, "w3"));
phraseQuery.Add(new Term(FIELD, "w2"));
Qtest(phraseQuery, new int[] { 0, 1, 3 });
}
[Test]
public virtual void TestP7()
{
PhraseQuery phraseQuery = new PhraseQuery();
phraseQuery.Slop = 3;
phraseQuery.Add(new Term(FIELD, "w3"));
phraseQuery.Add(new Term(FIELD, "w2"));
Qtest(phraseQuery, new int[] { 0, 1, 2, 3 });
}
/* some simple filtered query tests */
[Test]
public virtual void TestFQ1()
{
Qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "w1")), new ItemizedFilter(new int[] { 0, 1, 2, 3 })), new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestFQ2()
{
Qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "w1")), new ItemizedFilter(new int[] { 0, 2, 3 })), new int[] { 0, 2, 3 });
}
[Test]
public virtual void TestFQ3()
{
Qtest(new FilteredQuery(new TermQuery(new Term(FIELD, "xx")), new ItemizedFilter(new int[] { 1, 3 })), new int[] { 3 });
}
[Test]
public virtual void TestFQ4()
{
TermQuery termQuery = new TermQuery(new Term(FIELD, "xx"));
termQuery.Boost = 1000;
Qtest(new FilteredQuery(termQuery, new ItemizedFilter(new int[] { 1, 3 })), new int[] { 3 });
}
[Test]
public virtual void TestFQ6()
{
Query q = new FilteredQuery(new TermQuery(new Term(FIELD, "xx")), new ItemizedFilter(new int[] { 1, 3 }));
q.Boost = 1000;
Qtest(q, new int[] { 3 });
}
/* ConstantScoreQueries */
[Test]
public virtual void TestCSQ1()
{
Query q = new ConstantScoreQuery(new ItemizedFilter(new int[] { 0, 1, 2, 3 }));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestCSQ2()
{
Query q = new ConstantScoreQuery(new ItemizedFilter(new int[] { 1, 3 }));
Qtest(q, new int[] { 1, 3 });
}
[Test]
public virtual void TestCSQ3()
{
Query q = new ConstantScoreQuery(new ItemizedFilter(new int[] { 0, 2 }));
q.Boost = 1000;
Qtest(q, new int[] { 0, 2 });
}
/* DisjunctionMaxQuery */
[Test]
public virtual void TestDMQ1()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(new TermQuery(new Term(FIELD, "w1")));
q.Add(new TermQuery(new Term(FIELD, "w5")));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestDMQ2()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(new TermQuery(new Term(FIELD, "w1")));
q.Add(new TermQuery(new Term(FIELD, "w5")));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestDMQ3()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(new TermQuery(new Term(FIELD, "QQ")));
q.Add(new TermQuery(new Term(FIELD, "w5")));
Qtest(q, new int[] { 0 });
}
[Test]
public virtual void TestDMQ4()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
q.Add(new TermQuery(new Term(FIELD, "QQ")));
q.Add(new TermQuery(new Term(FIELD, "xx")));
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestDMQ5()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
booleanQuery.Add(new TermQuery(new Term(FIELD, "QQ")), BooleanClause.Occur.MUST_NOT);
q.Add(booleanQuery);
q.Add(new TermQuery(new Term(FIELD, "xx")));
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestDMQ6()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.MUST_NOT);
booleanQuery.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.SHOULD);
q.Add(booleanQuery);
q.Add(new TermQuery(new Term(FIELD, "xx")));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestDMQ7()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.MUST_NOT);
booleanQuery.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.SHOULD);
q.Add(booleanQuery);
q.Add(new TermQuery(new Term(FIELD, "w2")));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestDMQ8()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
boostedQuery.Boost = 100;
booleanQuery.Add(boostedQuery, BooleanClause.Occur.SHOULD);
q.Add(booleanQuery);
TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx"));
xxBoostedQuery.Boost = 100000;
q.Add(xxBoostedQuery);
Qtest(q, new int[] { 0, 2, 3 });
}
[Test]
public virtual void TestDMQ9()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.5f);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w5"));
boostedQuery.Boost = 100;
booleanQuery.Add(boostedQuery, BooleanClause.Occur.SHOULD);
q.Add(booleanQuery);
TermQuery xxBoostedQuery = new TermQuery(new Term(FIELD, "xx"));
xxBoostedQuery.Boost = 0;
q.Add(xxBoostedQuery);
Qtest(q, new int[] { 0, 2, 3 });
}
/* MultiPhraseQuery */
[Test]
public virtual void TestMPQ1()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new string[] { "w1" }));
q.Add(Ta(new string[] { "w2", "w3", "xx" }));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMPQ2()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new string[] { "w1" }));
q.Add(Ta(new string[] { "w2", "w3" }));
Qtest(q, new int[] { 0, 1, 3 });
}
[Test]
public virtual void TestMPQ3()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new string[] { "w1", "xx" }));
q.Add(Ta(new string[] { "w2", "w3" }));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMPQ4()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new string[] { "w1" }));
q.Add(Ta(new string[] { "w2" }));
Qtest(q, new int[] { 0 });
}
[Test]
public virtual void TestMPQ5()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new string[] { "w1" }));
q.Add(Ta(new string[] { "w2" }));
q.Slop = 1;
Qtest(q, new int[] { 0, 1, 2 });
}
[Test]
public virtual void TestMPQ6()
{
MultiPhraseQuery q = new MultiPhraseQuery();
q.Add(Ta(new string[] { "w1", "w3" }));
q.Add(Ta(new string[] { "w2" }));
q.Slop = 1;
Qtest(q, new int[] { 0, 1, 2, 3 });
}
/* some simple tests of boolean queries containing term queries */
[Test]
public virtual void TestBQ1()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
query.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.MUST);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ2()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.MUST);
query.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.MUST);
Qtest(query, new int[] { 2, 3 });
}
[Test]
public virtual void TestBQ3()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
query.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.MUST);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ4()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ5()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), BooleanClause.Occur.MUST);
innerQuery.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ6()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(new TermQuery(new Term(FIELD, "w5")), BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.MUST_NOT);
Qtest(outerQuery, new int[] { 1, 2, 3 });
}
[Test]
public virtual void TestBQ7()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.SHOULD);
childLeft.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.MUST);
Qtest(outerQuery, new int[] { 0 });
}
[Test]
public virtual void TestBQ8()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.SHOULD);
childLeft.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ9()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
childLeft.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.SHOULD);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.MUST_NOT);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ10()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
childLeft.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.SHOULD);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.MUST_NOT);
outerQuery.Add(innerQuery, BooleanClause.Occur.MUST);
Qtest(outerQuery, new int[] { 1 });
}
[Test]
public virtual void TestBQ11()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
TermQuery boostedQuery = new TermQuery(new Term(FIELD, "w1"));
boostedQuery.Boost = 1000;
query.Add(boostedQuery, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ14()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), BooleanClause.Occur.SHOULD);
q.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ15()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), BooleanClause.Occur.MUST_NOT);
q.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ16()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), BooleanClause.Occur.SHOULD);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
booleanQuery.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
q.Add(booleanQuery, BooleanClause.Occur.SHOULD);
Qtest(q, new int[] { 0, 1 });
}
[Test]
public virtual void TestBQ17()
{
BooleanQuery q = new BooleanQuery(true);
q.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.SHOULD);
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
booleanQuery.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
q.Add(booleanQuery, BooleanClause.Occur.SHOULD);
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestBQ19()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.MUST_NOT);
query.Add(new TermQuery(new Term(FIELD, "w3")), BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 0, 1 });
}
[Test]
public virtual void TestBQ20()
{
BooleanQuery q = new BooleanQuery();
q.MinimumNumberShouldMatch = 2;
q.Add(new TermQuery(new Term(FIELD, "QQQQQ")), BooleanClause.Occur.SHOULD);
q.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
q.Add(new TermQuery(new Term(FIELD, "zz")), BooleanClause.Occur.SHOULD);
q.Add(new TermQuery(new Term(FIELD, "w5")), BooleanClause.Occur.SHOULD);
q.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.SHOULD);
Qtest(q, new int[] { 0, 3 });
}
/* BQ of TQ: using alt so some fields have zero boost and some don't */
[Test]
public virtual void TestMultiFieldBQ1()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
query.Add(new TermQuery(new Term(ALTFIELD, "w2")), BooleanClause.Occur.MUST);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ2()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.MUST);
query.Add(new TermQuery(new Term(ALTFIELD, "w3")), BooleanClause.Occur.MUST);
Qtest(query, new int[] { 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ3()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term(FIELD, "yy")), BooleanClause.Occur.SHOULD);
query.Add(new TermQuery(new Term(ALTFIELD, "w3")), BooleanClause.Occur.MUST);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ4()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "w2")), BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ5()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), BooleanClause.Occur.MUST);
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "w2")), BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ6()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.SHOULD);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "w5")), BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.MUST_NOT);
Qtest(outerQuery, new int[] { 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ7()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(ALTFIELD, "xx")), BooleanClause.Occur.SHOULD);
childLeft.Add(new TermQuery(new Term(ALTFIELD, "w2")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(ALTFIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.MUST);
Qtest(outerQuery, new int[] { 0 });
}
[Test]
public virtual void TestMultiFieldBQ8()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(ALTFIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(FIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(ALTFIELD, "xx")), BooleanClause.Occur.SHOULD);
childLeft.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.MUST_NOT);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.SHOULD);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ9()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
childLeft.Add(new TermQuery(new Term(FIELD, "w2")), BooleanClause.Occur.SHOULD);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.MUST_NOT);
outerQuery.Add(innerQuery, BooleanClause.Occur.SHOULD);
Qtest(outerQuery, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQ10()
{
BooleanQuery outerQuery = new BooleanQuery();
outerQuery.Add(new TermQuery(new Term(FIELD, "w1")), BooleanClause.Occur.MUST);
BooleanQuery innerQuery = new BooleanQuery();
innerQuery.Add(new TermQuery(new Term(ALTFIELD, "qq")), BooleanClause.Occur.SHOULD);
BooleanQuery childLeft = new BooleanQuery();
childLeft.Add(new TermQuery(new Term(FIELD, "xx")), BooleanClause.Occur.MUST_NOT);
childLeft.Add(new TermQuery(new Term(ALTFIELD, "w2")), BooleanClause.Occur.SHOULD);
innerQuery.Add(childLeft, BooleanClause.Occur.SHOULD);
BooleanQuery childRight = new BooleanQuery();
childRight.Add(new TermQuery(new Term(ALTFIELD, "w3")), BooleanClause.Occur.MUST);
childRight.Add(new TermQuery(new Term(FIELD, "w4")), BooleanClause.Occur.MUST);
innerQuery.Add(childRight, BooleanClause.Occur.MUST_NOT);
outerQuery.Add(innerQuery, BooleanClause.Occur.MUST);
Qtest(outerQuery, new int[] { 1 });
}
/* BQ of PQ: using alt so some fields have zero boost and some don't */
[Test]
public virtual void TestMultiFieldBQofPQ1()
{
BooleanQuery query = new BooleanQuery();
PhraseQuery leftChild = new PhraseQuery();
leftChild.Add(new Term(FIELD, "w1"));
leftChild.Add(new Term(FIELD, "w2"));
query.Add(leftChild, BooleanClause.Occur.SHOULD);
PhraseQuery rightChild = new PhraseQuery();
rightChild.Add(new Term(ALTFIELD, "w1"));
rightChild.Add(new Term(ALTFIELD, "w2"));
query.Add(rightChild, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 0 });
}
[Test]
public virtual void TestMultiFieldBQofPQ2()
{
BooleanQuery query = new BooleanQuery();
PhraseQuery leftChild = new PhraseQuery();
leftChild.Add(new Term(FIELD, "w1"));
leftChild.Add(new Term(FIELD, "w3"));
query.Add(leftChild, BooleanClause.Occur.SHOULD);
PhraseQuery rightChild = new PhraseQuery();
rightChild.Add(new Term(ALTFIELD, "w1"));
rightChild.Add(new Term(ALTFIELD, "w3"));
query.Add(rightChild, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 1, 3 });
}
[Test]
public virtual void TestMultiFieldBQofPQ3()
{
BooleanQuery query = new BooleanQuery();
PhraseQuery leftChild = new PhraseQuery();
leftChild.Slop = 1;
leftChild.Add(new Term(FIELD, "w1"));
leftChild.Add(new Term(FIELD, "w2"));
query.Add(leftChild, BooleanClause.Occur.SHOULD);
PhraseQuery rightChild = new PhraseQuery();
rightChild.Slop = 1;
rightChild.Add(new Term(ALTFIELD, "w1"));
rightChild.Add(new Term(ALTFIELD, "w2"));
query.Add(rightChild, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 0, 1, 2 });
}
[Test]
public virtual void TestMultiFieldBQofPQ4()
{
BooleanQuery query = new BooleanQuery();
PhraseQuery leftChild = new PhraseQuery();
leftChild.Slop = 1;
leftChild.Add(new Term(FIELD, "w2"));
leftChild.Add(new Term(FIELD, "w3"));
query.Add(leftChild, BooleanClause.Occur.SHOULD);
PhraseQuery rightChild = new PhraseQuery();
rightChild.Slop = 1;
rightChild.Add(new Term(ALTFIELD, "w2"));
rightChild.Add(new Term(ALTFIELD, "w3"));
query.Add(rightChild, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestMultiFieldBQofPQ5()
{
BooleanQuery query = new BooleanQuery();
PhraseQuery leftChild = new PhraseQuery();
leftChild.Slop = 1;
leftChild.Add(new Term(FIELD, "w3"));
leftChild.Add(new Term(FIELD, "w2"));
query.Add(leftChild, BooleanClause.Occur.SHOULD);
PhraseQuery rightChild = new PhraseQuery();
rightChild.Slop = 1;
rightChild.Add(new Term(ALTFIELD, "w3"));
rightChild.Add(new Term(ALTFIELD, "w2"));
query.Add(rightChild, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 1, 3 });
}
[Test]
public virtual void TestMultiFieldBQofPQ6()
{
BooleanQuery query = new BooleanQuery();
PhraseQuery leftChild = new PhraseQuery();
leftChild.Slop = 2;
leftChild.Add(new Term(FIELD, "w3"));
leftChild.Add(new Term(FIELD, "w2"));
query.Add(leftChild, BooleanClause.Occur.SHOULD);
PhraseQuery rightChild = new PhraseQuery();
rightChild.Slop = 2;
rightChild.Add(new Term(ALTFIELD, "w3"));
rightChild.Add(new Term(ALTFIELD, "w2"));
query.Add(rightChild, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 0, 1, 3 });
}
[Test]
public virtual void TestMultiFieldBQofPQ7()
{
BooleanQuery query = new BooleanQuery();
PhraseQuery leftChild = new PhraseQuery();
leftChild.Slop = 3;
leftChild.Add(new Term(FIELD, "w3"));
leftChild.Add(new Term(FIELD, "w2"));
query.Add(leftChild, BooleanClause.Occur.SHOULD);
PhraseQuery rightChild = new PhraseQuery();
rightChild.Slop = 1;
rightChild.Add(new Term(ALTFIELD, "w3"));
rightChild.Add(new Term(ALTFIELD, "w2"));
query.Add(rightChild, BooleanClause.Occur.SHOULD);
Qtest(query, new int[] { 0, 1, 2, 3 });
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// Represents an intrinsic debugger method with byref return type.
/// </summary>
internal sealed class PlaceholderMethodSymbol : MethodSymbol, Cci.ISignature
{
internal delegate ImmutableArray<TypeParameterSymbol> GetTypeParameters(PlaceholderMethodSymbol method);
internal delegate ImmutableArray<ParameterSymbol> GetParameters(PlaceholderMethodSymbol method);
internal delegate TypeSymbol GetReturnType(PlaceholderMethodSymbol method);
private readonly NamedTypeSymbol _container;
private readonly string _name;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly TypeSymbol _returnType;
private readonly ImmutableArray<ParameterSymbol> _parameters;
internal PlaceholderMethodSymbol(
NamedTypeSymbol container,
string name,
GetTypeParameters getTypeParameters,
GetReturnType getReturnType,
GetParameters getParameters)
{
_container = container;
_name = name;
_typeParameters = getTypeParameters(this);
_returnType = getReturnType(this);
_parameters = getParameters(this);
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override bool ReturnsVoid
{
get { return false; }
}
internal override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeSymbol ReturnType
{
get { return _returnType; }
}
bool Cci.ISignature.ReturnValueIsByRef
{
get { return true; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override ushort CountOfCustomModifiersPrecedingByRef
{
get { return 0; }
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
return this.IsGenericMethod ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion : IEquatable<Quaternion>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
/// <summary>Z value</summary>
public float Z;
/// <summary>W value</summary>
public float W;
#region Constructors
public Quaternion(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public Quaternion(Vector3 vectorPart, float scalarPart)
{
X = vectorPart.X;
Y = vectorPart.Y;
Z = vectorPart.Z;
W = scalarPart;
}
/// <summary>
/// Build a quaternion from normalized float values
/// </summary>
/// <param name="x">X value from -1.0 to 1.0</param>
/// <param name="y">Y value from -1.0 to 1.0</param>
/// <param name="z">Z value from -1.0 to 1.0</param>
public Quaternion(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
float xyzsum = 1 - X * X - Y * Y - Z * Z;
W = (xyzsum > 0) ? (float)Math.Sqrt(xyzsum) : 0;
}
/// <summary>
/// Constructor, builds a quaternion object from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing four four-byte floats</param>
/// <param name="pos">Offset in the byte array to start reading at</param>
/// <param name="normalized">Whether the source data is normalized or
/// not. If this is true 12 bytes will be read, otherwise 16 bytes will
/// be read.</param>
public Quaternion(byte[] byteArray, int pos, bool normalized)
{
X = Y = Z = W = 0;
FromBytes(byteArray, pos, normalized);
}
public Quaternion(Quaternion q)
{
X = q.X;
Y = q.Y;
Z = q.Z;
W = q.W;
}
#endregion Constructors
#region Public Methods
public float Length()
{
return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}
public float LengthSquared()
{
return (X * X + Y * Y + Z * Z + W * W);
}
/// <summary>
/// Normalizes the quaternion
/// </summary>
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Builds a quaternion object from a byte array
/// </summary>
/// <param name="byteArray">The source byte array</param>
/// <param name="pos">Offset in the byte array to start reading at</param>
/// <param name="normalized">Whether the source data is normalized or
/// not. If this is true 12 bytes will be read, otherwise 16 bytes will
/// be read.</param>
public void FromBytes(byte[] byteArray, int pos, bool normalized)
{
if (!normalized)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[16];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
Array.Reverse(conversionBuffer, 12, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
W = BitConverter.ToSingle(conversionBuffer, 12);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
W = BitConverter.ToSingle(byteArray, pos + 12);
}
}
else
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[16];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
}
float xyzsum = 1f - X * X - Y * Y - Z * Z;
W = (xyzsum > 0f) ? (float)Math.Sqrt(xyzsum) : 0f;
}
}
/// <summary>
/// Normalize this quaternion and serialize it to a byte array
/// </summary>
/// <returns>A 12 byte array containing normalized X, Y, and Z floating
/// point values in order using little endian byte ordering</returns>
public byte[] GetBytes()
{
byte[] bytes = new byte[12];
float norm;
norm = (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
if (norm != 0f)
{
norm = 1f / norm;
float x, y, z;
if (W >= 0f)
{
x = X; y = Y; z = Z;
}
else
{
x = -X; y = -Y; z = -Z;
}
Buffer.BlockCopy(BitConverter.GetBytes(norm * x), 0, bytes, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(norm * y), 0, bytes, 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(norm * z), 0, bytes, 8, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(bytes, 0, 4);
Array.Reverse(bytes, 4, 4);
Array.Reverse(bytes, 8, 4);
}
}
else
{
throw new InvalidOperationException(String.Format(
"Quaternion {0} normalized to zero", ToString()));
}
return bytes;
}
/// <summary>
/// Convert this quaternion to euler angles
/// </summary>
/// <param name="roll">X euler angle</param>
/// <param name="pitch">Y euler angle</param>
/// <param name="yaw">Z euler angle</param>
public void GetEulerAngles(out float roll, out float pitch, out float yaw)
{
float sqx = X * X;
float sqy = Y * Y;
float sqz = Z * Z;
float sqw = W * W;
// Unit will be a correction factor if the quaternion is not normalized
float unit = sqx + sqy + sqz + sqw;
double test = X * Y + Z * W;
if (test > 0.499f * unit)
{
// Singularity at north pole
yaw = 2f * (float)Math.Atan2(X, W);
pitch = (float)Math.PI / 2f;
roll = 0f;
}
else if (test < -0.499f * unit)
{
// Singularity at south pole
yaw = -2f * (float)Math.Atan2(X, W);
pitch = -(float)Math.PI / 2f;
roll = 0f;
}
else
{
yaw = (float)Math.Atan2(2f * Y * W - 2f * X * Z, sqx - sqy - sqz + sqw);
pitch = (float)Math.Asin(2f * test / unit);
roll = (float)Math.Atan2(2f * X * W - 2f * Y * Z, -sqx + sqy - sqz + sqw);
}
}
/// <summary>
/// Conver this quaternion to an angle around an axis
/// </summary>
/// <param name="axis">Unit vector describing the axis</param>
/// <param name="angle">Angle around the axis, in radians</param>
public void GetAxisAngle(out Vector3 axis, out float angle)
{
axis = new Vector3();
float scale = (float)Math.Sqrt(X * X + Y * Y + Z * Z);
if (scale < Single.Epsilon || W > 1.0f || W < -1.0f)
{
angle = 0.0f;
axis.X = 0.0f;
axis.Y = 1.0f;
axis.Z = 0.0f;
}
else
{
angle = 2.0f * (float)Math.Acos(W);
float ooscale = 1f / scale;
axis.X = X * ooscale;
axis.Y = Y * ooscale;
axis.Z = Z * ooscale;
}
}
#endregion Public Methods
#region Static Methods
public static Quaternion Add(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X += quaternion2.X;
quaternion1.Y += quaternion2.Y;
quaternion1.Z += quaternion2.Z;
quaternion1.W += quaternion2.W;
return quaternion1;
}
/// <summary>
/// Returns the conjugate (spatial inverse) of a quaternion
/// </summary>
private static Quaternion Conjugate(Quaternion quaternion)
{
quaternion.X = -quaternion.X;
quaternion.Y = -quaternion.Y;
quaternion.Z = -quaternion.Z;
return quaternion;
}
/// <summary>
/// Build a quaternion from an axis and an angle of rotation around
/// that axis
/// </summary>
public static Quaternion CreateFromAxisAngle(float axisX, float axisY, float axisZ, float angle)
{
Vector3 axis = new Vector3(axisX, axisY, axisZ);
return CreateFromAxisAngle(axis, angle);
}
/// <summary>
/// Build a quaternion from an axis and an angle of rotation around
/// that axis
/// </summary>
/// <param name="axis">Axis of rotation</param>
/// <param name="angle">Angle of rotation</param>
public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
{
Quaternion q;
axis = Vector3.Normalize(axis);
angle *= 0.5f;
float c = (float)Math.Cos(angle);
float s = (float)Math.Sin(angle);
q.X = axis.X * s;
q.Y = axis.Y * s;
q.Z = axis.Z * s;
q.W = c;
return Quaternion.Normalize(q);
}
/// <summary>
/// Creates a quaternion from a vector containing roll, pitch, and yaw
/// in radians
/// </summary>
/// <param name="eulers">Vector representation of the euler angles in
/// radians</param>
/// <returns>Quaternion representation of the euler angles</returns>
public static Quaternion CreateFromEulers(Vector3 eulers)
{
return CreateFromEulers(eulers.X, eulers.Y, eulers.Z);
}
/// <summary>
/// Creates a quaternion from roll, pitch, and yaw euler angles in
/// radians
/// </summary>
/// <param name="roll">X angle in radians</param>
/// <param name="pitch">Y angle in radians</param>
/// <param name="yaw">Z angle in radians</param>
/// <returns>Quaternion representation of the euler angles</returns>
public static Quaternion CreateFromEulers(float roll, float pitch, float yaw)
{
if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI)
throw new ArgumentException("Euler angles must be in radians");
double atCos = Math.Cos(roll / 2f);
double atSin = Math.Sin(roll / 2f);
double leftCos = Math.Cos(pitch / 2f);
double leftSin = Math.Sin(pitch / 2f);
double upCos = Math.Cos(yaw / 2f);
double upSin = Math.Sin(yaw / 2f);
double atLeftCos = atCos * leftCos;
double atLeftSin = atSin * leftSin;
return new Quaternion(
(float)(atSin * leftCos * upCos + atCos * leftSin * upSin),
(float)(atCos * leftSin * upCos - atSin * leftCos * upSin),
(float)(atLeftCos * upSin + atLeftSin * upCos),
(float)(atLeftCos * upCos - atLeftSin * upSin)
);
}
public static Quaternion CreateFromRotationMatrix(Matrix4 m)
{
Quaternion quat;
float trace = m.Trace();
if (trace > Single.Epsilon)
{
float s = (float)Math.Sqrt(trace + 1f);
quat.W = s * 0.5f;
s = 0.5f / s;
quat.X = (m.M23 - m.M32) * s;
quat.Y = (m.M31 - m.M13) * s;
quat.Z = (m.M12 - m.M21) * s;
}
else
{
if (m.M11 > m.M22 && m.M11 > m.M33)
{
float s = (float)Math.Sqrt(1f + m.M11 - m.M22 - m.M33);
quat.X = 0.5f * s;
s = 0.5f / s;
quat.Y = (m.M12 + m.M21) * s;
quat.Z = (m.M13 + m.M31) * s;
quat.W = (m.M23 - m.M32) * s;
}
else if (m.M22 > m.M33)
{
float s = (float)Math.Sqrt(1f + m.M22 - m.M11 - m.M33);
quat.Y = 0.5f * s;
s = 0.5f / s;
quat.X = (m.M21 + m.M12) * s;
quat.Z = (m.M32 + m.M23) * s;
quat.W = (m.M31 - m.M13) * s;
}
else
{
float s = (float)Math.Sqrt(1f + m.M33 - m.M11 - m.M22);
quat.Z = 0.5f * s;
s = 0.5f / s;
quat.X = (m.M31 + m.M13) * s;
quat.Y = (m.M32 + m.M23) * s;
quat.W = (m.M12 - m.M21) * s;
}
}
return quat;
}
public static Quaternion Divide(Quaternion quaternion1, Quaternion quaternion2)
{
float x = quaternion1.X;
float y = quaternion1.Y;
float z = quaternion1.Z;
float w = quaternion1.W;
float q2lensq = quaternion2.LengthSquared(); //num14
float ooq2lensq = 1f / q2lensq;
float x2 = -quaternion2.X * ooq2lensq;
float y2 = -quaternion2.Y * ooq2lensq;
float z2 = -quaternion2.Z * ooq2lensq;
float w2 = quaternion2.W * ooq2lensq;
return new Quaternion(
((x * w2) + (x2 * w)) + (y * z2) - (z * y2),
((y * w2) + (y2 * w)) + (z * x2) - (x * z2),
((z * w2) + (z2 * w)) + (x * y2) - (y * x2),
(w * w2) - ((x * x2) + (y * y2)) + (z * z2));
}
public static float Dot(Quaternion q1, Quaternion q2)
{
return (q1.X * q2.X) + (q1.Y * q2.Y) + (q1.Z * q2.Z) + (q1.W * q2.W);
}
/// <summary>
/// Conjugates and renormalizes a vector
/// </summary>
public static Quaternion Inverse(Quaternion quaternion)
{
float norm = quaternion.LengthSquared();
if (norm == 0f)
{
quaternion.X = quaternion.Y = quaternion.Z = quaternion.W = 0f;
}
else
{
float oonorm = 1f / norm;
quaternion = Conjugate(quaternion);
quaternion.X *= oonorm;
quaternion.Y *= oonorm;
quaternion.Z *= oonorm;
quaternion.W *= oonorm;
}
return quaternion;
}
/// <summary>
/// Spherical linear interpolation between two quaternions
/// </summary>
public static Quaternion Slerp(Quaternion q1, Quaternion q2, float amount)
{
float angle = Dot(q1, q2);
if (angle < 0f)
{
q1 *= -1f;
angle *= -1f;
}
float scale;
float invscale;
if ((angle + 1f) > 0.05f)
{
if ((1f - angle) >= 0.05f)
{
// slerp
float theta = (float)Math.Acos(angle);
float invsintheta = 1f / (float)Math.Sin(theta);
scale = (float)Math.Sin(theta * (1f - amount)) * invsintheta;
invscale = (float)Math.Sin(theta * amount) * invsintheta;
}
else
{
// lerp
scale = 1f - amount;
invscale = amount;
}
}
else
{
q2.X = -q1.Y;
q2.Y = q1.X;
q2.Z = -q1.W;
q2.W = q1.Z;
scale = (float)Math.Sin(Utils.PI * (0.5f - amount));
invscale = (float)Math.Sin(Utils.PI * amount);
}
return (q1 * scale) + (q2 * invscale);
}
public static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X -= quaternion2.X;
quaternion1.Y -= quaternion2.Y;
quaternion1.Z -= quaternion2.Z;
quaternion1.W -= quaternion2.W;
return quaternion1;
}
public static Quaternion Multiply(Quaternion q1, Quaternion q2)
{
return new Quaternion(
(q1.W * q2.X) + (q1.X * q2.W) + (q1.Y * q2.Z) - (q1.Z * q2.Y),
(q1.W * q2.Y) - (q1.X * q2.Z) + (q1.Y * q2.W) + (q1.Z * q2.X),
(q1.W * q2.Z) + (q1.X * q2.Y) - (q1.Y * q2.X) + (q1.Z * q2.W),
(q1.W * q2.W) - (q1.X * q2.X) - (q1.Y * q2.Y) - (q1.Z * q2.Z)
);
}
public static Quaternion Multiply(Quaternion quaternion, float scaleFactor)
{
quaternion.X *= scaleFactor;
quaternion.Y *= scaleFactor;
quaternion.Z *= scaleFactor;
quaternion.W *= scaleFactor;
return quaternion;
}
public static Quaternion Negate(Quaternion quaternion)
{
quaternion.X = -quaternion.X;
quaternion.Y = -quaternion.Y;
quaternion.Z = -quaternion.Z;
quaternion.W = -quaternion.W;
return quaternion;
}
public static Quaternion Normalize(Quaternion q)
{
const float MAG_THRESHOLD = 0.0000001f;
float mag = q.Length();
// Catch very small rounding errors when normalizing
if (mag > MAG_THRESHOLD)
{
float oomag = 1f / mag;
q.X *= oomag;
q.Y *= oomag;
q.Z *= oomag;
q.W *= oomag;
}
else
{
q.X = 0f;
q.Y = 0f;
q.Z = 0f;
q.W = 1f;
}
return q;
}
public static Quaternion Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
if (split.Length == 3)
{
return new Quaternion(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture));
}
else
{
return new Quaternion(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture),
float.Parse(split[3].Trim(), Utils.EnUsCulture));
}
}
public static bool TryParse(string val, out Quaternion result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = new Quaternion();
return false;
}
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Quaternion) ? this == (Quaternion)obj : false;
}
public bool Equals(Quaternion other)
{
return W == other.W
&& X == other.X
&& Y == other.Y
&& Z == other.Z;
}
public override int GetHashCode()
{
return (X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode());
}
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W);
}
/// <summary>
/// Get a string representation of the quaternion elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the quaternion</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W);
}
#endregion Overrides
#region Operators
public static bool operator ==(Quaternion quaternion1, Quaternion quaternion2)
{
return quaternion1.W == quaternion2.W
&& quaternion1.X == quaternion2.X
&& quaternion1.Y == quaternion2.Y
&& quaternion1.Z == quaternion2.Z;
}
public static bool operator !=(Quaternion quaternion1, Quaternion quaternion2)
{
return !(quaternion1 == quaternion2);
}
public static Quaternion operator +(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X += quaternion2.X;
quaternion1.Y += quaternion2.Y;
quaternion1.Z += quaternion2.Z;
quaternion1.W += quaternion2.W;
return quaternion1;
}
public static Quaternion operator -(Quaternion quaternion)
{
quaternion.X = -quaternion.X;
quaternion.Y = -quaternion.Y;
quaternion.Z = -quaternion.Z;
quaternion.W = -quaternion.W;
return quaternion;
}
public static Quaternion operator -(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X -= quaternion2.X;
quaternion1.Y -= quaternion2.Y;
quaternion1.Z -= quaternion2.Z;
quaternion1.W -= quaternion2.W;
return quaternion1;
}
public static Quaternion operator *(Quaternion q1, Quaternion q2)
{
return new Quaternion(
(q1.W * q2.X) + (q1.X * q2.W) + (q1.Y * q2.Z) - (q1.Z * q2.Y),
(q1.W * q2.Y) - (q1.X * q2.Z) + (q1.Y * q2.W) + (q1.Z * q2.X),
(q1.W * q2.Z) + (q1.X * q2.Y) - (q1.Y * q2.X) + (q1.Z * q2.W),
(q1.W * q2.W) - (q1.X * q2.X) - (q1.Y * q2.Y) - (q1.Z * q2.Z)
);
}
public static Quaternion operator *(Quaternion quaternion, float scaleFactor)
{
quaternion.X *= scaleFactor;
quaternion.Y *= scaleFactor;
quaternion.Z *= scaleFactor;
quaternion.W *= scaleFactor;
return quaternion;
}
public static Quaternion operator /(Quaternion quaternion1, Quaternion quaternion2)
{
return Divide(quaternion1, quaternion2);
}
#endregion Operators
/// <summary>A quaternion with a value of 0,0,0,1</summary>
public readonly static Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//=============================================================================
//
//
// Purpose: Define HResult constants. Every exception has one of these.
//
//
//===========================================================================*/
using System;
namespace System
{
// Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that
// range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc).
// In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type
// HResults. Also note that some of our HResults have to map to certain
// COM HR's, etc.
// Another arbitrary decision... Feel free to change this, as long as you
// renumber the HResults yourself (and update rexcep.h).
// Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f.
// Security will use 0x1640 -> 0x165f
// There are HResults files in the IO, Remoting, Reflection &
// Security/Util directories as well, so choose your HResults carefully.
internal static class HResults
{
internal const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54);
internal const int CLDB_E_FILE_CORRUPT = unchecked((int)0x8013110e);
internal const int CLDB_E_FILE_OLDVER = unchecked((int)0x80131107);
internal const int CLDB_E_INDEX_NOTFOUND = unchecked((int)0x80131124);
internal const int CLR_E_BIND_ASSEMBLY_NOT_FOUND = unchecked((int)0x80132004);
internal const int CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH = unchecked((int)0x80132001);
internal const int CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW = unchecked((int)0x80132000);
internal const int CLR_E_BIND_TYPE_NOT_FOUND = unchecked((int)0x80132005);
internal const int CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT = unchecked((int)0x80132003);
internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D);
internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D);
internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014);
internal const int COR_E_APPLICATION = unchecked((int)0x80131600);
internal const int COR_E_ARGUMENT = unchecked((int)0x80070057);
internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502);
internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216);
internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503);
internal const int COR_E_ASSEMBLYEXPECTED = unchecked((int)0x80131018);
internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B);
internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015);
internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542);
internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504);
internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605);
internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541);
internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO
internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524);
internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529);
internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523);
internal const int COR_E_EXCEPTION = unchecked((int)0x80131500);
internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506);
internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507);
internal const int COR_E_FIXUPSINEXE = unchecked((int)0x80131019);
internal const int COR_E_FORMAT = unchecked((int)0x80131537);
internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508);
internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578);
internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002);
internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527);
internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601);
internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531);
internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509);
internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153a);
internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577);
internal const int COR_E_LOADING_REFERENCE_ASSEMBLY = unchecked((int)0x80131058);
internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535);
internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A);
internal const int COR_E_METHODACCESS = unchecked((int)0x80131510);
internal const int COR_E_MISSINGFIELD = unchecked((int)0x80131511);
internal const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532);
internal const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512);
internal const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513);
internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536);
internal const int COR_E_MODULE_HASH_CHECK_FAILED = unchecked((int)0x80131039);
internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514);
internal const int COR_E_NEWER_RUNTIME = unchecked((int)0x8013101b);
internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528);
internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515);
internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003);
internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622);
internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B);
internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E);
internal const int COR_E_OVERFLOW = unchecked((int)0x80131516);
internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539);
internal const int COR_E_RANK = unchecked((int)0x80131517);
internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602);
internal const int COR_E_REMOTING = unchecked((int)0x8013150b);
internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153e);
internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538);
internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533);
internal const int COR_E_SECURITY = unchecked((int)0x8013150A);
internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C);
internal const int COR_E_SERVER = unchecked((int)0x8013150e);
internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9);
internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518);
internal const int COR_E_SYSTEM = unchecked((int)0x80131501);
internal const int COR_E_TARGET = unchecked((int)0x80131603);
internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604);
internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e);
internal const int COR_E_THREADABORTED = unchecked((int)0x80131530);
internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519);
internal const int COR_E_THREADSTART = unchecked((int)0x80131525);
internal const int COR_E_THREADSTATE = unchecked((int)0x80131520);
internal const int COR_E_TIMEOUT = unchecked((int)0x80131505);
internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543);
internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534);
internal const int COR_E_TYPELOAD = unchecked((int)0x80131522);
internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005);
internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D);
internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C);
internal const int CORSEC_E_CRYPTO = unchecked((int)0x80131430);
internal const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431);
internal const int CORSEC_E_INVALID_IMAGE_FORMAT = unchecked((int)0x8013141d);
internal const int CORSEC_E_INVALID_PUBLICKEY = unchecked((int)0x8013141e);
internal const int CORSEC_E_INVALID_STRONGNAME = unchecked((int)0x8013141a);
internal const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417);
internal const int CORSEC_E_MISSING_STRONGNAME = unchecked((int)0x8013141b);
internal const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418);
internal const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416);
internal const int CORSEC_E_SIGNATURE_MISMATCH = unchecked((int)0x80131420);
internal const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131419);
internal const int CTL_E_DEVICEIOERROR = unchecked((int)0x800A0039);
internal const int CTL_E_DIVISIONBYZERO = unchecked((int)0x800A000B);
internal const int CTL_E_FILENOTFOUND = unchecked((int)0x800A0035);
internal const int CTL_E_OUTOFMEMORY = unchecked((int)0x800A0007);
internal const int CTL_E_OUTOFSTACKSPACE = unchecked((int)0x800A001C);
internal const int CTL_E_OVERFLOW = unchecked((int)0x800A0006);
internal const int CTL_E_PATHFILEACCESSERROR = unchecked((int)0x800A004B);
internal const int CTL_E_PATHNOTFOUND = unchecked((int)0x800A004C);
internal const int CTL_E_PERMISSIONDENIED = unchecked((int)0x800A0046);
internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F);
internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E);
internal const int E_FAIL = unchecked((int)0x80004005);
internal const int E_HANDLE = unchecked((int)0x80070006);
internal const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018);
internal const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000E);
internal const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000D);
internal const int E_INVALIDARG = unchecked((int)0x80070057);
internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014);
internal const int E_NOTIMPL = unchecked((int)0x80004001);
internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E);
internal const int E_POINTER = unchecked((int)0x80004003L);
internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A);
internal const int ERROR_BAD_EXE_FORMAT = unchecked((int)0x800700C1);
internal const int ERROR_BAD_NET_NAME = unchecked((int)0x80070043);
internal const int ERROR_BAD_NETPATH = unchecked((int)0x80070035);
internal const int ERROR_DISK_CORRUPT = unchecked((int)0x80070571);
internal const int ERROR_DLL_INIT_FAILED = unchecked((int)0x8007045A);
internal const int ERROR_DLL_NOT_FOUND = unchecked((int)0x80070485);
internal const int ERROR_EXE_MARKED_INVALID = unchecked((int)0x800700C0);
internal const int ERROR_FILE_CORRUPT = unchecked((int)0x80070570);
internal const int ERROR_FILE_INVALID = unchecked((int)0x800703EE);
internal const int ERROR_FILE_NOT_FOUND = unchecked((int)0x80070002);
internal const int ERROR_INVALID_DLL = unchecked((int)0x80070482);
internal const int ERROR_INVALID_NAME = unchecked((int)0x8007007B);
internal const int ERROR_INVALID_ORDINAL = unchecked((int)0x800700B6);
internal const int ERROR_INVALID_PARAMETER = unchecked((int)0x80070057);
internal const int ERROR_LOCK_VIOLATION = unchecked((int)0x80070021);
internal const int ERROR_MOD_NOT_FOUND = unchecked((int)0x8007007E);
internal const int ERROR_NO_UNICODE_TRANSLATION = unchecked((int)0x80070459);
internal const int ERROR_NOACCESS = unchecked((int)0x800703E6);
internal const int ERROR_NOT_OWNER = unchecked((int)0x80070120);
internal const int ERROR_NOT_READY = unchecked((int)0x80070015);
internal const int ERROR_OPEN_FAILED = unchecked((int)0x8007006E);
internal const int ERROR_PATH_NOT_FOUND = unchecked((int)0x80070003);
internal const int ERROR_SHARING_VIOLATION = unchecked((int)0x80070020);
internal const int ERROR_TIMEOUT = unchecked((int)0x800705B4);
internal const int ERROR_TOO_MANY_OPEN_FILES = unchecked((int)0x80070004);
internal const int ERROR_UNRECOGNIZED_VOLUME = unchecked((int)0x800703ED);
internal const int ERROR_WRONG_TARGET_NAME = unchecked((int)0x80070574);
internal const int FUSION_E_ASM_MODULE_MISSING = unchecked((int)0x80131042);
internal const int FUSION_E_CACHEFILE_FAILED = unchecked((int)0x80131052);
internal const int FUSION_E_CODE_DOWNLOAD_DISABLED = unchecked((int)0x80131048);
internal const int FUSION_E_HOST_GAC_ASM_MISMATCH = unchecked((int)0x80131050);
internal const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047);
internal const int FUSION_E_INVALID_PRIVATE_ASM_LOCATION = unchecked((int)0x80131041);
internal const int FUSION_E_LOADFROM_BLOCKED = unchecked((int)0x80131051);
internal const int FUSION_E_PRIVATE_ASM_DISALLOWED = unchecked((int)0x80131044);
internal const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040);
internal const int FUSION_E_SIGNATURE_CHECK_FAILED = unchecked((int)0x80131045);
internal const int INET_E_CANNOT_CONNECT = unchecked((int)0x800C0004);
internal const int INET_E_CONNECTION_TIMEOUT = unchecked((int)0x800C000B);
internal const int INET_E_DATA_NOT_AVAILABLE = unchecked((int)0x800C0007);
internal const int INET_E_DOWNLOAD_FAILURE = unchecked((int)0x800C0008);
internal const int INET_E_OBJECT_NOT_FOUND = unchecked((int)0x800C0006);
internal const int INET_E_RESOURCE_NOT_FOUND = unchecked((int)0x800C0005);
internal const int INET_E_UNKNOWN_PROTOCOL = unchecked((int)0x800C000D);
internal const int ISS_E_ALLOC_TOO_LARGE = unchecked((int)0x80131484);
internal const int ISS_E_BLOCK_SIZE_TOO_SMALL = unchecked((int)0x80131483);
internal const int ISS_E_CALLER = unchecked((int)0x801314A1);
internal const int ISS_E_CORRUPTED_STORE_FILE = unchecked((int)0x80131480);
internal const int ISS_E_CREATE_DIR = unchecked((int)0x80131468);
internal const int ISS_E_CREATE_MUTEX = unchecked((int)0x80131464);
internal const int ISS_E_DEPRECATE = unchecked((int)0x801314A0);
internal const int ISS_E_FILE_NOT_MAPPED = unchecked((int)0x80131482);
internal const int ISS_E_FILE_WRITE = unchecked((int)0x80131466);
internal const int ISS_E_GET_FILE_SIZE = unchecked((int)0x80131463);
internal const int ISS_E_ISOSTORE = unchecked((int)0x80131450);
internal const int ISS_E_LOCK_FAILED = unchecked((int)0x80131465);
internal const int ISS_E_MACHINE = unchecked((int)0x801314A3);
internal const int ISS_E_MACHINE_DACL = unchecked((int)0x801314A4);
internal const int ISS_E_MAP_VIEW_OF_FILE = unchecked((int)0x80131462);
internal const int ISS_E_OPEN_FILE_MAPPING = unchecked((int)0x80131461);
internal const int ISS_E_OPEN_STORE_FILE = unchecked((int)0x80131460);
internal const int ISS_E_PATH_LENGTH = unchecked((int)0x801314A2);
internal const int ISS_E_SET_FILE_POINTER = unchecked((int)0x80131467);
internal const int ISS_E_STORE_NOT_OPEN = unchecked((int)0x80131469);
internal const int ISS_E_STORE_VERSION = unchecked((int)0x80131481);
internal const int ISS_E_TABLE_ROW_NOT_FOUND = unchecked((int)0x80131486);
internal const int ISS_E_USAGE_WILL_EXCEED_QUOTA = unchecked((int)0x80131485);
internal const int META_E_BAD_SIGNATURE = unchecked((int)0x80131192);
internal const int META_E_CA_FRIENDS_SN_REQUIRED = unchecked((int)0x801311e6);
internal const int MSEE_E_ASSEMBLYLOADINPROGRESS = unchecked((int)0x80131016);
internal const int RO_E_CLOSED = unchecked((int)0x80000013);
internal const int E_BOUNDS = unchecked((int)0x8000000B);
internal const int RO_E_METADATA_NAME_NOT_FOUND = unchecked((int)0x8000000F);
internal const int SECURITY_E_INCOMPATIBLE_EVIDENCE = unchecked((int)0x80131403);
internal const int SECURITY_E_INCOMPATIBLE_SHARE = unchecked((int)0x80131401);
internal const int SECURITY_E_UNVERIFIABLE = unchecked((int)0x80131402);
internal const int STG_E_PATHNOTFOUND = unchecked((int)0x80030003);
public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003);
public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined
public const int COR_E_FILELOAD = unchecked((int)0x80131621);
public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002);
public const int COR_E_IO = unchecked((int)0x80131620);
public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE);
}
}
| |
// 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.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoggerOperations operations.
/// </summary>
public partial interface ILoggerOperations
{
/// <summary>
/// Lists a collection of loggers in the specified service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" />
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<LoggerContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<LoggerContract> odataQuery = default(ODataQuery<LoggerContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the details of the logger specified by its identifier.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service
/// instance.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<LoggerContract,LoggerGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates a logger.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service
/// instance.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<LoggerContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, LoggerContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates an existing logger.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service
/// instance.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the logger to update. A value of
/// "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, LoggerUpdateContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified logger.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='loggerid'>
/// Logger identifier. Must be unique in the API Management service
/// instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the logger to delete. A value of
/// "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists a collection of loggers in the specified service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<LoggerContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Foundation;
using CoreFoundation;
using UIKit;
namespace ZXing.Mobile
{
public partial class MobileBarcodeScanner : MobileBarcodeScannerBase
{
IScannerViewController viewController;
readonly WeakReference<UIViewController> weakAppController;
readonly ManualResetEvent scanResultResetEvent = new ManualResetEvent(false);
public MobileBarcodeScanner(UIViewController delegateController)
=> weakAppController = new WeakReference<UIViewController>(delegateController);
public MobileBarcodeScanner()
=> weakAppController = new WeakReference<UIViewController>(Xamarin.Essentials.Platform.GetCurrentUIViewController());
public Task<Result> Scan(bool useAVCaptureEngine)
=> Scan(new MobileBarcodeScanningOptions(), useAVCaptureEngine);
Task<Result> PlatformScan(MobileBarcodeScanningOptions options)
=> Scan(options, false);
void PlatformScanContinuously(MobileBarcodeScanningOptions options, Action<Result> scanHandler)
=> InternalScanContinuously(options, false, scanHandler);
public void ScanContinuously(MobileBarcodeScanningOptions options, bool useAVCaptureEngine, Action<Result> scanHandler)
=> InternalScanContinuously(options, useAVCaptureEngine, scanHandler);
void InternalScanContinuously(MobileBarcodeScanningOptions options, bool useAVCaptureEngine, Action<Result> scanHandler)
{
try
{
var sv = new Version(0, 0, 0);
Version.TryParse(UIDevice.CurrentDevice.SystemVersion, out sv);
var is7orgreater = sv.Major >= 7;
var allRequestedFormatsSupported = true;
if (useAVCaptureEngine)
allRequestedFormatsSupported = AVCaptureScannerView.SupportsAllRequestedBarcodeFormats(options.PossibleFormats);
if (weakAppController.TryGetTarget(out var appController))
{
var tcs = new TaskCompletionSource<object>();
appController?.InvokeOnMainThread(() =>
{
if (useAVCaptureEngine && is7orgreater && allRequestedFormatsSupported)
{
viewController = new AVCaptureScannerViewController(options, this);
viewController.ContinuousScanning = true;
}
else
{
if (useAVCaptureEngine && !is7orgreater)
Console.WriteLine("Not iOS 7 or greater, cannot use AVCapture for barcode decoding, using ZXing instead");
else if (useAVCaptureEngine && !allRequestedFormatsSupported)
Console.WriteLine("Not all requested barcode formats were supported by AVCapture, using ZXing instead");
viewController = new ZXing.Mobile.ZXingScannerViewController(options, this);
viewController.ContinuousScanning = true;
}
viewController.OnScannedResult += barcodeResult =>
{
// If null, stop scanning was called
if (barcodeResult == null)
{
((UIViewController)viewController).InvokeOnMainThread(() =>
{
((UIViewController)viewController).DismissViewController(true, null);
});
}
scanHandler(barcodeResult);
};
appController?.PresentViewController((UIViewController)viewController, true, null);
});
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public Task<Result> Scan(MobileBarcodeScanningOptions options, bool useAVCaptureEngine) => Task.Factory.StartNew(() =>
{
try
{
scanResultResetEvent.Reset();
Result result = null;
var sv = new Version(0, 0, 0);
Version.TryParse(UIDevice.CurrentDevice.SystemVersion, out sv);
var is7orgreater = sv.Major >= 7;
var allRequestedFormatsSupported = true;
if (useAVCaptureEngine)
allRequestedFormatsSupported = AVCaptureScannerView.SupportsAllRequestedBarcodeFormats(options.PossibleFormats);
if (weakAppController.TryGetTarget(out var appController))
{
appController?.InvokeOnMainThread(() =>
{
if (useAVCaptureEngine && is7orgreater && allRequestedFormatsSupported)
{
viewController = new AVCaptureScannerViewController(options, this);
}
else
{
if (useAVCaptureEngine && !is7orgreater)
Console.WriteLine("Not iOS 7 or greater, cannot use AVCapture for barcode decoding, using ZXing instead");
else if (useAVCaptureEngine && !allRequestedFormatsSupported)
Console.WriteLine("Not all requested barcode formats were supported by AVCapture, using ZXing instead");
viewController = new ZXing.Mobile.ZXingScannerViewController(options, this);
}
viewController.OnScannedResult += barcodeResult =>
{
((UIViewController)viewController).InvokeOnMainThread(() =>
{
viewController.Cancel();
// Handle error situation that occurs when user manually closes scanner in the same moment that a QR code is detected
try
{
((UIViewController)viewController).DismissViewController(true, () =>
{
result = barcodeResult;
scanResultResetEvent.Set();
});
}
catch (ObjectDisposedException)
{
// In all likelihood, iOS has decided to close the scanner at this point. But just in case it executes the
// post-scan code instead, set the result so we will not get a NullReferenceException.
result = barcodeResult;
scanResultResetEvent.Set();
}
});
};
appController?.PresentViewController((UIViewController)viewController, true, null);
});
}
scanResultResetEvent.WaitOne();
((UIViewController)viewController).Dispose();
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
});
void PlatformCancel()
{
if (viewController != null)
{
((UIViewController)viewController).InvokeOnMainThread(() =>
{
viewController.Cancel();
// Calling with animated:true here will result in a blank screen when the scanner is closed on iOS 7.
((UIViewController)viewController).DismissViewController(true, null);
});
}
scanResultResetEvent.Set();
}
void PlatformTorch(bool on)
=> viewController?.Torch(on);
void PlatformToggleTorch()
=> viewController?.ToggleTorch();
void PlatformAutoFocus()
{
//Does nothing on iOS
}
void PlatformPauseAnalysis()
=> viewController?.PauseAnalysis();
void PlatformResumeAnalysis()
=> viewController?.ResumeAnalysis();
bool PlatformIsTorchOn
=> viewController.IsTorchOn;
public UIView CustomOverlay { get; set; }
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderAvOpenhomeOrgCredentials1 : IDisposable
{
/// <summary>
/// Set the value of the Ids property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyIds(string aValue);
/// <summary>
/// Get a copy of the value of the Ids property
/// </summary>
/// <returns>Value of the Ids property.</param>
string PropertyIds();
/// <summary>
/// Set the value of the PublicKey property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyPublicKey(string aValue);
/// <summary>
/// Get a copy of the value of the PublicKey property
/// </summary>
/// <returns>Value of the PublicKey property.</param>
string PropertyPublicKey();
/// <summary>
/// Set the value of the SequenceNumber property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertySequenceNumber(uint aValue);
/// <summary>
/// Get a copy of the value of the SequenceNumber property
/// </summary>
/// <returns>Value of the SequenceNumber property.</param>
uint PropertySequenceNumber();
}
/// <summary>
/// Provider for the av.openhome.org:Credentials:1 UPnP service
/// </summary>
public class DvProviderAvOpenhomeOrgCredentials1 : DvProvider, IDisposable, IDvProviderAvOpenhomeOrgCredentials1
{
private GCHandle iGch;
private ActionDelegate iDelegateSet;
private ActionDelegate iDelegateClear;
private ActionDelegate iDelegateSetEnabled;
private ActionDelegate iDelegateGet;
private ActionDelegate iDelegateLogin;
private ActionDelegate iDelegateReLogin;
private ActionDelegate iDelegateGetIds;
private ActionDelegate iDelegateGetPublicKey;
private ActionDelegate iDelegateGetSequenceNumber;
private PropertyString iPropertyIds;
private PropertyString iPropertyPublicKey;
private PropertyUint iPropertySequenceNumber;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderAvOpenhomeOrgCredentials1(DvDevice aDevice)
: base(aDevice, "av.openhome.org", "Credentials", 1)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Enable the Ids property.
/// </summary>
public void EnablePropertyIds()
{
List<String> allowedValues = new List<String>();
iPropertyIds = new PropertyString(new ParameterString("Ids", allowedValues));
AddProperty(iPropertyIds);
}
/// <summary>
/// Enable the PublicKey property.
/// </summary>
public void EnablePropertyPublicKey()
{
List<String> allowedValues = new List<String>();
iPropertyPublicKey = new PropertyString(new ParameterString("PublicKey", allowedValues));
AddProperty(iPropertyPublicKey);
}
/// <summary>
/// Enable the SequenceNumber property.
/// </summary>
public void EnablePropertySequenceNumber()
{
iPropertySequenceNumber = new PropertyUint(new ParameterUint("SequenceNumber"));
AddProperty(iPropertySequenceNumber);
}
/// <summary>
/// Set the value of the Ids property
/// </summary>
/// <remarks>Can only be called if EnablePropertyIds has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyIds(string aValue)
{
if (iPropertyIds == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyIds, aValue);
}
/// <summary>
/// Get a copy of the value of the Ids property
/// </summary>
/// <remarks>Can only be called if EnablePropertyIds has previously been called.</remarks>
/// <returns>Value of the Ids property.</returns>
public string PropertyIds()
{
if (iPropertyIds == null)
throw new PropertyDisabledError();
return iPropertyIds.Value();
}
/// <summary>
/// Set the value of the PublicKey property
/// </summary>
/// <remarks>Can only be called if EnablePropertyPublicKey has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyPublicKey(string aValue)
{
if (iPropertyPublicKey == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyPublicKey, aValue);
}
/// <summary>
/// Get a copy of the value of the PublicKey property
/// </summary>
/// <remarks>Can only be called if EnablePropertyPublicKey has previously been called.</remarks>
/// <returns>Value of the PublicKey property.</returns>
public string PropertyPublicKey()
{
if (iPropertyPublicKey == null)
throw new PropertyDisabledError();
return iPropertyPublicKey.Value();
}
/// <summary>
/// Set the value of the SequenceNumber property
/// </summary>
/// <remarks>Can only be called if EnablePropertySequenceNumber has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertySequenceNumber(uint aValue)
{
if (iPropertySequenceNumber == null)
throw new PropertyDisabledError();
return SetPropertyUint(iPropertySequenceNumber, aValue);
}
/// <summary>
/// Get a copy of the value of the SequenceNumber property
/// </summary>
/// <remarks>Can only be called if EnablePropertySequenceNumber has previously been called.</remarks>
/// <returns>Value of the SequenceNumber property.</returns>
public uint PropertySequenceNumber()
{
if (iPropertySequenceNumber == null)
throw new PropertyDisabledError();
return iPropertySequenceNumber.Value();
}
/// <summary>
/// Signal that the action Set is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Set must be overridden if this is called.</remarks>
protected void EnableActionSet()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Set");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddInputParameter(new ParameterString("UserName", allowedValues));
action.AddInputParameter(new ParameterBinary("Password"));
iDelegateSet = new ActionDelegate(DoSet);
EnableAction(action, iDelegateSet, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Clear is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Clear must be overridden if this is called.</remarks>
protected void EnableActionClear()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Clear");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
iDelegateClear = new ActionDelegate(DoClear);
EnableAction(action, iDelegateClear, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action SetEnabled is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// SetEnabled must be overridden if this is called.</remarks>
protected void EnableActionSetEnabled()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetEnabled");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddInputParameter(new ParameterBool("Enabled"));
iDelegateSetEnabled = new ActionDelegate(DoSetEnabled);
EnableAction(action, iDelegateSetEnabled, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Get is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Get must be overridden if this is called.</remarks>
protected void EnableActionGet()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Get");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddOutputParameter(new ParameterString("UserName", allowedValues));
action.AddOutputParameter(new ParameterBinary("Password"));
action.AddOutputParameter(new ParameterBool("Enabled"));
action.AddOutputParameter(new ParameterString("Status", allowedValues));
action.AddOutputParameter(new ParameterString("Data", allowedValues));
iDelegateGet = new ActionDelegate(DoGet);
EnableAction(action, iDelegateGet, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Login is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Login must be overridden if this is called.</remarks>
protected void EnableActionLogin()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Login");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddOutputParameter(new ParameterString("Token", allowedValues));
iDelegateLogin = new ActionDelegate(DoLogin);
EnableAction(action, iDelegateLogin, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action ReLogin is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// ReLogin must be overridden if this is called.</remarks>
protected void EnableActionReLogin()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ReLogin");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddInputParameter(new ParameterString("CurrentToken", allowedValues));
action.AddOutputParameter(new ParameterString("NewToken", allowedValues));
iDelegateReLogin = new ActionDelegate(DoReLogin);
EnableAction(action, iDelegateReLogin, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetIds is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetIds must be overridden if this is called.</remarks>
protected void EnableActionGetIds()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetIds");
action.AddOutputParameter(new ParameterRelated("Ids", iPropertyIds));
iDelegateGetIds = new ActionDelegate(DoGetIds);
EnableAction(action, iDelegateGetIds, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetPublicKey is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetPublicKey must be overridden if this is called.</remarks>
protected void EnableActionGetPublicKey()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetPublicKey");
action.AddOutputParameter(new ParameterRelated("PublicKey", iPropertyPublicKey));
iDelegateGetPublicKey = new ActionDelegate(DoGetPublicKey);
EnableAction(action, iDelegateGetPublicKey, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetSequenceNumber is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetSequenceNumber must be overridden if this is called.</remarks>
protected void EnableActionGetSequenceNumber()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetSequenceNumber");
action.AddOutputParameter(new ParameterRelated("SequenceNumber", iPropertySequenceNumber));
iDelegateGetSequenceNumber = new ActionDelegate(DoGetSequenceNumber);
EnableAction(action, iDelegateGetSequenceNumber, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Set action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Set action for the owning device.
///
/// Must be implemented iff EnableActionSet was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aUserName"></param>
/// <param name="aPassword"></param>
protected virtual void Set(IDvInvocation aInvocation, string aId, string aUserName, byte[] aPassword)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Clear action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Clear action for the owning device.
///
/// Must be implemented iff EnableActionClear was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
protected virtual void Clear(IDvInvocation aInvocation, string aId)
{
throw (new ActionDisabledError());
}
/// <summary>
/// SetEnabled action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// SetEnabled action for the owning device.
///
/// Must be implemented iff EnableActionSetEnabled was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aEnabled"></param>
protected virtual void SetEnabled(IDvInvocation aInvocation, string aId, bool aEnabled)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Get action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Get action for the owning device.
///
/// Must be implemented iff EnableActionGet was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aUserName"></param>
/// <param name="aPassword"></param>
/// <param name="aEnabled"></param>
/// <param name="aStatus"></param>
/// <param name="aData"></param>
protected virtual void Get(IDvInvocation aInvocation, string aId, out string aUserName, out byte[] aPassword, out bool aEnabled, out string aStatus, out string aData)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Login action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Login action for the owning device.
///
/// Must be implemented iff EnableActionLogin was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aToken"></param>
protected virtual void Login(IDvInvocation aInvocation, string aId, out string aToken)
{
throw (new ActionDisabledError());
}
/// <summary>
/// ReLogin action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// ReLogin action for the owning device.
///
/// Must be implemented iff EnableActionReLogin was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aCurrentToken"></param>
/// <param name="aNewToken"></param>
protected virtual void ReLogin(IDvInvocation aInvocation, string aId, string aCurrentToken, out string aNewToken)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetIds action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetIds action for the owning device.
///
/// Must be implemented iff EnableActionGetIds was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIds"></param>
protected virtual void GetIds(IDvInvocation aInvocation, out string aIds)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetPublicKey action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetPublicKey action for the owning device.
///
/// Must be implemented iff EnableActionGetPublicKey was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aPublicKey"></param>
protected virtual void GetPublicKey(IDvInvocation aInvocation, out string aPublicKey)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetSequenceNumber action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetSequenceNumber action for the owning device.
///
/// Must be implemented iff EnableActionGetSequenceNumber was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aSequenceNumber"></param>
protected virtual void GetSequenceNumber(IDvInvocation aInvocation, out uint aSequenceNumber)
{
throw (new ActionDisabledError());
}
private static int DoSet(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string userName;
byte[] password;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
userName = invocation.ReadString("UserName");
password = invocation.ReadBinary("Password");
invocation.ReadEnd();
self.Set(invocation, id, userName, password);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Set");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "Set"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Set", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Set", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoClear(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
invocation.ReadEnd();
self.Clear(invocation, id);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Clear");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "Clear"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Clear", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Clear", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoSetEnabled(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
bool enabled;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
enabled = invocation.ReadBool("Enabled");
invocation.ReadEnd();
self.SetEnabled(invocation, id, enabled);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "SetEnabled");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "SetEnabled"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "SetEnabled", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "SetEnabled", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGet(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string userName;
byte[] password;
bool enabled;
string status;
string data;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
invocation.ReadEnd();
self.Get(invocation, id, out userName, out password, out enabled, out status, out data);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Get");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "Get"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Get", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("UserName", userName);
invocation.WriteBinary("Password", password);
invocation.WriteBool("Enabled", enabled);
invocation.WriteString("Status", status);
invocation.WriteString("Data", data);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Get", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoLogin(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string token;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
invocation.ReadEnd();
self.Login(invocation, id, out token);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Login");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "Login"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Login", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Token", token);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "Login", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoReLogin(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string currentToken;
string newToken;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
currentToken = invocation.ReadString("CurrentToken");
invocation.ReadEnd();
self.ReLogin(invocation, id, currentToken, out newToken);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "ReLogin");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "ReLogin"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ReLogin", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("NewToken", newToken);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ReLogin", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetIds(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string ids;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetIds(invocation, out ids);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetIds");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetIds"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetIds", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Ids", ids);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetIds", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetPublicKey(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string publicKey;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetPublicKey(invocation, out publicKey);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetPublicKey");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetPublicKey"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetPublicKey", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("PublicKey", publicKey);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetPublicKey", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetSequenceNumber(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint sequenceNumber;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetSequenceNumber(invocation, out sequenceNumber);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetSequenceNumber");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetSequenceNumber"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetSequenceNumber", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("SequenceNumber", sequenceNumber);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetSequenceNumber", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using DotSpatial.NTSExtension;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// ShadedRelief.
/// </summary>
public class ShadedRelief : Descriptor, IShadedRelief
{
#region Fields
private float _ambientIntensity;
private float _elevationFactor;
private float _extrusion;
private bool _hasChanged; // set to true when a property changes, and false again when the raster symbolizer calculates the HillShadeMap
private bool _isUsed;
private double _lightDirection;
private float _lightIntensity;
private double _zenithAngle;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ShadedRelief"/> class preset for elevation in feet and coordinates in decimal degrees.
/// </summary>
public ShadedRelief()
: this(ElevationScenario.ElevationFeetProjectionDegrees)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ShadedRelief"/> class based on some more common
/// elevation to geographic coordinate system scenarios.
/// </summary>
/// <param name="scenario">Scenario to use.</param>
public ShadedRelief(ElevationScenario scenario)
{
// These scenarios just give a quick approximate calc for the elevation factor
switch (scenario)
{
case ElevationScenario.ElevationCentimetersProjectionDegrees:
_elevationFactor = 1F / (160934.4F * 69F);
break;
case ElevationScenario.ElevationCentimetersProjectionFeet:
_elevationFactor = 0.0328084F;
break;
case ElevationScenario.ElevationCentimetersProjectionMeters:
_elevationFactor = 1F / 100F;
break;
case ElevationScenario.ElevationFeetProjectionDegrees:
_elevationFactor = 1F / (5280F * 69F);
break;
case ElevationScenario.ElevationFeetProjectionFeet:
_elevationFactor = 1F;
break;
case ElevationScenario.ElevationFeetProjectionMeters:
_elevationFactor = 1F / 3.28F;
break;
case ElevationScenario.ElevationMetersProjectionDegrees:
_elevationFactor = 1F / (1609F * 69F);
break;
case ElevationScenario.ElevationMetersProjectionFeet:
_elevationFactor = 1F * 3.28F;
break;
case ElevationScenario.ElevationMetersProjectionMeters:
_elevationFactor = 1F;
break;
}
// Light direction is SouthEast at about 45 degrees up
_zenithAngle = 45;
_lightDirection = 45;
_lightIntensity = .7F;
_ambientIntensity = .8F;
_extrusion = 5;
// _elevationFactor = 0.0000027F;
_isUsed = false;
_hasChanged = false;
}
#endregion
#region Events
/// <summary>
/// Occurs when the shading for this object has been altered.
/// </summary>
public event EventHandler ShadingChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets a float specifying how strong the ambient directional light is. This should probably be about 1.
/// </summary>
[Category("Shaded Relief")]
[Description("Gets or sets a float specifying how strong the ambient directional light is. This should probably be about 1.")]
[Serialize("AmbientIntensity")]
public float AmbientIntensity
{
get
{
return _ambientIntensity;
}
set
{
_ambientIntensity = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets the elevation factor. This is kept separate from extrusion to reduce confusion. This is a conversion factor that will
/// convert the units of elevation into the same units that the latitude and longitude are stored in.
/// To convert feet to decimal degrees is around a factor of .00000274.
/// </summary>
[Category("Shaded Relief")]
[Description("This is kept separate from extrusion to reduce confusion. This is a conversion factor that will convert the units of elevation into the same units that the latitude and longitude are stored in. To convert feet to decimal degrees is around a factor of .00000274")]
[Serialize("ElevationFactor")]
public float ElevationFactor
{
get
{
return _elevationFactor;
}
set
{
_elevationFactor = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a float value expression that modifies the "height" of the apparent shaded relief. A value
/// of 1 should show the mountains at their true elevations, presuming the ElevationFactor is
/// correct. A value of 0 would be totally flat, while 2 would be twice the value.
/// </summary>
[Category("Shaded Relief")]
[Serialize("Extrusion")]
[Description("A float value expression that modifies the height of the apparent shaded relief. A value of 1 should show the mountains at their true elevations, presuming the ElevationFactor is correct. A value of 0 would be totally flat, while 2 would be twice the value.")]
public float Extrusion
{
get
{
return _extrusion;
}
set
{
_extrusion = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a value indicating whether or not the values have been changed on this ShadedRelief more recently than
/// a HillShade map has been calculated from it.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool HasChanged
{
get
{
return _hasChanged;
}
set
{
_hasChanged = value;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a value indicating whether the ShadedRelief should be used or not.
/// </summary>
[Category("Shaded Relief")]
[Serialize("IsUsed")]
[Description("Gets or sets a boolean value indicating whether the ShadedRelief should be used or not.")]
public bool IsUsed
{
get
{
return _isUsed;
}
set
{
_isUsed = value;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a double that represents the light direction in degrees clockwise from North.
/// </summary>
[Category("Shaded Relief")]
[Description("The azimuth angle in degrees for the light direction. The angle is measured clockwise from North.")]
public double LightDirection
{
get
{
return _lightDirection;
}
set
{
_lightDirection = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets a float that should probably be around 1, which controls the light intensity.
/// </summary>
[Category("Shaded Relief")]
[Serialize("LightIntensity")]
[Description("This specifies a float that should probably be around 1, which controls the light intensity.")]
public float LightIntensity
{
get
{
return _lightIntensity;
}
set
{
_lightIntensity = value;
_hasChanged = true;
OnShadingChanged();
}
}
/// <summary>
/// Gets or sets the zenith angle for the light direction in degrees from 0 (at the horizon) to 90 (straight up).
/// </summary>
[Category("Shaded Relief")]
[Serialize("ZenithAngle")]
[Description("Gets or sets the zenith angle for the light direction in degrees from 0 (at the horizon) to 90 (straight up).")]
public double ZenithAngle
{
get
{
return _zenithAngle;
}
set
{
_zenithAngle = value;
_hasChanged = true;
OnShadingChanged();
}
}
#endregion
#region Methods
/// <summary>
/// Returns a normalized vector in 3 dimensions representing the angle
/// of the light source.
/// </summary>
/// <returns>The light direction.</returns>
public FloatVector3 GetLightDirection()
{
double angle = LightDirection * Math.PI / 180;
double zAngle = ZenithAngle * Math.PI / 180;
double x = Math.Sin(angle) * Math.Cos(zAngle);
double y = Math.Cos(angle) * Math.Cos(zAngle);
double z = Math.Sin(zAngle);
return new FloatVector3((float)x, (float)y, (float)z);
}
/// <summary>
/// Fires the ShadingChanged event.
/// </summary>
protected virtual void OnShadingChanged()
{
ShadingChanged?.Invoke(this, EventArgs.Empty);
}
#endregion
}
}
| |
#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.IO;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Text;
using System.Diagnostics;
#if HAVE_XLINQ
using System.Xml.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between .NET types and JSON types.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
/// </example>
public static class JsonConvert
{
/// <summary>
/// Gets or sets a function that creates default <see cref="JsonSerializerSettings"/>.
/// Default settings are automatically used by serialization methods on <see cref="JsonConvert"/>,
/// and <see cref="JToken.ToObject{T}()"/> and <see cref="JToken.FromObject(object)"/> on <see cref="JToken"/>.
/// To serialize without using any default settings create a <see cref="JsonSerializer"/> with
/// <see cref="JsonSerializer.Create()"/>.
/// </summary>
public static Func<JsonSerializerSettings> DefaultSettings { get; set; }
/// <summary>
/// Represents JavaScript's boolean value <c>true</c> as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value <c>false</c> as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's <c>null</c> as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's <c>undefined</c> as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's <c>NaN</c> as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
return ToString(value, DateFormatHandling.IsoDateFormat);
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value, DateFormatHandling format)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
#endif
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#if HAVE_BIG_INTEGER
private static string ToStringInternal(BigInteger value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
#endif
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value)))
{
return text;
}
if (floatFormatHandling == FloatFormatHandling.DefaultValue)
{
return (!nullable) ? "0.0" : Null;
}
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
{
return text;
}
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
{
return text;
}
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Decimal"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return ToString(value, '"');
}
internal static string ToString(Guid value, char quoteChar)
{
string text;
string qc;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
text = value.ToString("D", CultureInfo.InvariantCulture);
qc = quoteChar.ToString(CultureInfo.InvariantCulture);
#else
text = value.ToString("D");
qc = quoteChar.ToString();
#endif
return qc + text + qc;
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return ToString(value, '"');
}
internal static string ToString(TimeSpan value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
if (value == null)
{
return Null;
}
return ToString(value, '"');
}
internal static string ToString(Uri value, char quoteChar)
{
return ToString(value.OriginalString, quoteChar);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter)
{
return ToString(value, delimiter, StringEscapeHandling.Default);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <param name="stringEscapeHandling">The string escape handling.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling)
{
if (delimiter != '"' && delimiter != '\'')
{
throw new ArgumentException("Delimiter must be a single or double quote.", nameof(delimiter));
}
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
{
return Null;
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value.GetType());
switch (typeCode)
{
case PrimitiveTypeCode.String:
return ToString((string)value);
case PrimitiveTypeCode.Char:
return ToString((char)value);
case PrimitiveTypeCode.Boolean:
return ToString((bool)value);
case PrimitiveTypeCode.SByte:
return ToString((sbyte)value);
case PrimitiveTypeCode.Int16:
return ToString((short)value);
case PrimitiveTypeCode.UInt16:
return ToString((ushort)value);
case PrimitiveTypeCode.Int32:
return ToString((int)value);
case PrimitiveTypeCode.Byte:
return ToString((byte)value);
case PrimitiveTypeCode.UInt32:
return ToString((uint)value);
case PrimitiveTypeCode.Int64:
return ToString((long)value);
case PrimitiveTypeCode.UInt64:
return ToString((ulong)value);
case PrimitiveTypeCode.Single:
return ToString((float)value);
case PrimitiveTypeCode.Double:
return ToString((double)value);
case PrimitiveTypeCode.DateTime:
return ToString((DateTime)value);
case PrimitiveTypeCode.Decimal:
return ToString((decimal)value);
#if HAVE_DB_NULL_TYPE_CODE
case PrimitiveTypeCode.DBNull:
return Null;
#endif
#if HAVE_DATE_TIME_OFFSET
case PrimitiveTypeCode.DateTimeOffset:
return ToString((DateTimeOffset)value);
#endif
case PrimitiveTypeCode.Guid:
return ToString((Guid)value);
case PrimitiveTypeCode.Uri:
return ToString((Uri)value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan)value);
#if HAVE_BIG_INTEGER
case PrimitiveTypeCode.BigInteger:
return ToStringInternal((BigInteger)value);
#endif
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#region Serialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value)
{
return SerializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, JsonSerializerSettings settings)
{
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
return SerializeObjectInternal(value, type, jsonSerializer);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
jsonSerializer.Formatting = formatting;
return SerializeObjectInternal(value, type, jsonSerializer);
}
private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString();
}
#endregion
#region Deserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{
return DeserializeObject<T>(value, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T)DeserializeObject(value, typeof(T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
{
jsonSerializer.CheckAdditionalContent = true;
}
using (JsonTextReader reader = new JsonTextReader(new StringReader(value)))
{
return jsonSerializer.Deserialize(reader, type);
}
}
#endregion
#region Populate
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
[DebuggerStepThrough]
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
{
jsonSerializer.Populate(jsonReader, target);
if (settings != null && settings.CheckAdditionalContent)
{
while (jsonReader.Read())
{
if (jsonReader.TokenType != JsonToken.Comment)
{
throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
}
}
}
}
}
#endregion
#region Xml
#if HAVE_XML_DOCUMENT
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the <see cref="XmlNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <see cref="XmlNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <param name="encodeSpecialCharacters">
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#if HAVE_XLINQ
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string using formatting and omits the root object if <paramref name="omitRootObject"/> is <c>true</c>.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root element specified by <paramref name="deserializeRootElementName"/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <param name="encodeSpecialCharacters">
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
#endregion
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using NServiceKit.ServiceInterface;
namespace NServiceKit.FluentValidation
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using Internal;
using Results;
using Validators;
/// <summary>
/// Extension methods that provide the default set of validators.
/// </summary>
public static class DefaultValidatorExtensions {
/// <summary>
/// Defines a 'not null' validator on the current rule builder.
/// Validation will fail if the property is null.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotNull<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) {
return ruleBuilder.SetValidator(new NotNullValidator());
}
/// <summary>
/// Defines a 'not empty' validator on the current rule builder.
/// Validation will fail if the property is null, an empty or the default value for the type (for example, 0 for integers)
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotEmpty<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) {
return ruleBuilder.SetValidator(new NotEmptyValidator(default(TProperty)));
}
/// <summary>
/// Defines a length validator on the current rule builder, but only for string properties.
/// Validation will fail if the length of the string is outside of the specifed range. The range is inclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Length<T>(this IRuleBuilder<T, string> ruleBuilder, int min, int max) {
return ruleBuilder.SetValidator(new LengthValidator(min, max));
}
/// <summary>
/// Defines a length validator on the current rule builder, but only for string properties.
/// Validation will fail if the length of the string is not equal to the length specified.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="exactLength"></param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Length<T>(this IRuleBuilder<T, string> ruleBuilder, int exactLength) {
return ruleBuilder.SetValidator(new ExactLengthValidator(exactLength));
}
/// <summary>
/// Defines a regular expression validator on the current rule builder, but only for string properties.
/// Validation will fail if the value returned by the lambda does not match the regular expression.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The regular expression to check the value against.</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> Matches<T>(this IRuleBuilder<T, string> ruleBuilder, string expression) {
return ruleBuilder.SetValidator(new RegularExpressionValidator(expression));
}
/// <summary>
/// Defines a regular expression validator on the current rule builder, but only for string properties.
/// Validation will fail if the value returned by the lambda is not a valid email address.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, string> EmailAddress<T>(this IRuleBuilder<T, string> ruleBuilder) {
return ruleBuilder.SetValidator(new EmailValidator());
}
/// <summary>
/// Defines a 'not equal' validator on the current rule builder.
/// Validation will fail if the specified value is equal to the value of the property.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="toCompare">The value to compare</param>
/// <param name="comparer">Equality comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotEqual<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
TProperty toCompare, IEqualityComparer comparer = null) {
return ruleBuilder.SetValidator(new NotEqualValidator(toCompare, comparer));
}
/// <summary>
/// Defines a 'not equal' validator on the current rule builder using a lambda to specify the value.
/// Validation will fail if the value returned by the lambda is equal to the value of the property.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda expression to provide the comparison value</param>
/// <param name="comparer">Equality Comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> NotEqual<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Expression<Func<T, TProperty>> expression, IEqualityComparer comparer = null) {
var func = expression.Compile();
return ruleBuilder.SetValidator(new NotEqualValidator(func.CoerceToNonGeneric(), expression.GetMember(), comparer));
}
/// <summary>
/// Defines an 'equals' validator on the current rule builder.
/// Validation will fail if the specified value is not equal to the value of the property.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="toCompare">The value to compare</param>
/// <param name="comparer">Equality Comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Equal<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty toCompare, IEqualityComparer comparer = null) {
return ruleBuilder.SetValidator(new EqualValidator(toCompare, comparer));
}
/// <summary>
/// Defines an 'equals' validator on the current rule builder using a lambda to specify the comparison value.
/// Validation will fail if the value returned by the lambda is not equal to the value of the property.
/// </summary>
/// <typeparam name="T">The type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda expression to provide the comparison value</param>
/// <param name="comparer">Equality comparer to use</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Equal<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Expression<Func<T, TProperty>> expression, IEqualityComparer comparer = null) {
var func = expression.Compile();
return ruleBuilder.SetValidator(new EqualValidator(func.CoerceToNonGeneric(), expression.GetMember(), comparer));
}
/// <summary>
/// Defines a predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Must<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Func<TProperty, bool> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.Must((x, val) => predicate(val));
}
/// <summary>
/// Defines a predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// This overload accepts the object being validated in addition to the property being validated.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Must<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Func<T, TProperty, bool> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.Must((x, val, propertyValidatorContext) => predicate(x, val));
}
/// <summary>
/// Defines a predicate validator on the current rule builder using a lambda expression to specify the predicate.
/// Validation will fail if the specified lambda returns false.
/// Validation will succeed if the specifed lambda returns true.
/// This overload accepts the object being validated in addition to the property being validated.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="predicate">A lambda expression specifying the predicate</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> Must<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Func<T, TProperty, PropertyValidatorContext, bool> predicate) {
predicate.Guard("Cannot pass a null predicate to Must.");
return ruleBuilder.SetValidator(new PredicateValidator((instance, property, propertyValidatorContext) => predicate((T)instance, (TProperty)property, propertyValidatorContext)));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
TProperty valueToCompare)
where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThan<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder,
TProperty valueToCompare)
where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, TProperty valueToCompare) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty valueToCompare) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than' validator on the current rule builder.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty valueToCompare)
where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than' validator on the current rule builder.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> GreaterThan<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty valueToCompare)
where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, TProperty valueToCompare) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'greater than or equal' validator on the current rule builder.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty valueToCompare) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(valueToCompare));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda that should return the value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : IComparable<TProperty>, IComparable {
expression.Guard("Cannot pass null to LessThan");
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than the specified value.
/// The validation will fail if the property value is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">A lambda that should return the value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThan<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : struct, IComparable<TProperty>, IComparable {
expression.Guard("Cannot pass null to LessThan");
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, Expression<Func<T, TProperty>> expression)
where TProperty : IComparable<TProperty>, IComparable {
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than or equal' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is less than or equal to the specified value.
/// The validation will fail if the property value is greater than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> LessThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, Expression<Func<T, TProperty>> expression)
where TProperty : struct, IComparable<TProperty>, IComparable
{
var func = expression.Compile();
return ruleBuilder.SetValidator(new LessThanOrEqualValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThan<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : IComparable<TProperty>, IComparable {
var func = expression.Compile();
return ruleBuilder.SetValidator(new GreaterThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than the specified value.
/// The validation will fail if the property value is less than or equal to the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="expression">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> GreaterThan<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder,
Expression<Func<T, TProperty>> expression)
where TProperty : struct, IComparable<TProperty>, IComparable
{
var func = expression.Compile();
return ruleBuilder.SetValidator(new GreaterThanValidator(func.CoerceToNonGeneric(), expression.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, TProperty> ruleBuilder, Expression<Func<T, TProperty>> valueToCompare)
where TProperty : IComparable<TProperty>, IComparable {
var func = valueToCompare.Compile();
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(func.CoerceToNonGeneric(), valueToCompare.GetMember()));
}
/// <summary>
/// Defines a 'less than' validator on the current rule builder using a lambda expression.
/// The validation will succeed if the property value is greater than or equal the specified value.
/// The validation will fail if the property value is less than the specified value.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="valueToCompare">The value being compared</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> GreaterThanOrEqualTo<T, TProperty>(
this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, Expression<Func<T, TProperty>> valueToCompare)
where TProperty : struct, IComparable<TProperty>, IComparable
{
var func = valueToCompare.Compile();
return ruleBuilder.SetValidator(new GreaterThanOrEqualValidator(func.CoerceToNonGeneric(), valueToCompare.GetMember()));
}
/// <summary>
/// Validates certain properties of the specified instance.
/// </summary>
/// <param name="validator">The current validator</param>
/// <param name="instance">The object to validate</param>
/// <param name="propertyExpressions">Expressions to specify the properties to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, params Expression<Func<T, object>>[] propertyExpressions) {
var context = new ValidationContext<T>(instance, new PropertyChain(), MemberNameValidatorSelector.FromExpressions(propertyExpressions));
return validator.Validate(context);
}
/// <summary>
/// Validates certain properties of the specified instance.
/// </summary>
/// <param name="validator"></param>
/// <param name="instance">The object to validate</param>
/// <param name="properties">The names of the properties to validate.</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, params string[] properties) {
var context = new ValidationContext<T>(instance, new PropertyChain(), new MemberNameValidatorSelector(properties));
return validator.Validate(context);
}
/// <summary>Validates certain properties of the specified instance.</summary>
///
/// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="validator">The current validator.</param>
/// <param name="instance"> The object to validate.</param>
/// <param name="selector"> The selector.</param>
/// <param name="ruleSet"> Set the rule belongs to.</param>
///
/// <returns>A ValidationResult object containing any validation failures.</returns>
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, IValidatorSelector selector = null, string ruleSet = null) {
if(selector != null && ruleSet != null) {
throw new InvalidOperationException("Cannot specify both an IValidatorSelector and a RuleSet.");
}
if(selector == null) {
selector = new DefaultValidatorSelector();
}
if(ruleSet != null) {
selector = new RulesetValidatorSelector(ruleSet);
}
var context = new ValidationContext<T>(instance, new PropertyChain(), selector);
return validator.Validate(context);
}
/// <summary>
/// Performs validation and then throws an exception if validation fails.
/// </summary>
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance) {
var result = validator.Validate(instance);
if(! result.IsValid) {
throw new ValidationException(result.Errors);
}
}
/// <summary>Performs validation and then throws an exception if validation fails.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="validator">The current validator.</param>
/// <param name="instance"> The object to validate.</param>
/// <param name="ruleSet"> Set the rule belongs to.</param>
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, ApplyTo ruleSet)
{
validator.ValidateAndThrow(instance, ruleSet.ToString().ToUpper());
}
/// <summary>Performs validation and then throws an exception if validation fails.</summary>
///
/// <exception cref="ValidationException">Thrown when a Validation error condition occurs.</exception>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="validator">The current validator.</param>
/// <param name="instance"> The object to validate.</param>
/// <param name="ruleSet"> Set the rule belongs to.</param>
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet)
{
var result = validator.Validate(instance, (IValidatorSelector)null, ruleSet);
if (!result.IsValid)
{
throw new ValidationException(result.Errors);
}
}
/// <summary>
/// Defines an 'inclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is inclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> InclusiveBetween<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty from, TProperty to) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new InclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines an 'inclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is inclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> InclusiveBetween<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty from, TProperty to) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new InclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines an 'exclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is exclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, TProperty> ExclusiveBetween<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, TProperty from, TProperty to) where TProperty : IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new ExclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines an 'exclusive between' validator on the current rule builder, but only for properties of types that implement IComparable.
/// Validation will fail if the value of the property is outside of the specifed range. The range is exclusive.
/// </summary>
/// <typeparam name="T">Type of object being validated</typeparam>
/// <typeparam name="TProperty">Type of property being validated</typeparam>
/// <param name="ruleBuilder">The rule builder on which the validator should be defined</param>
/// <param name="from">The lowest allowed value</param>
/// <param name="to">The highest allowed value</param>
/// <returns></returns>
public static IRuleBuilderOptions<T, Nullable<TProperty>> ExclusiveBetween<T, TProperty>(this IRuleBuilder<T, Nullable<TProperty>> ruleBuilder, TProperty from, TProperty to) where TProperty : struct, IComparable<TProperty>, IComparable {
return ruleBuilder.SetValidator(new ExclusiveBetweenValidator(from, to));
}
/// <summary>
/// Defines a credit card validator for the current rule builder that ensures that the specified string is a valid credit card number.
/// </summary>
public static IRuleBuilderOptions<T,string> CreditCard<T>(this IRuleBuilder<T, string> ruleBuilder) {
return ruleBuilder.SetValidator(new CreditCardValidator());
}
}
}
| |
/*
* TestGuid.cs - Tests for the "ActivationArguments" 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
*/
using CSUnit;
using System;
#if CONFIG_FRAMEWORK_2_0
public class TestActivationArguments : TestCase
{
// Constructor.
public TestActivationArguments(String name) : base(name)
{
// Nothing to do here.
}
// Set up for the tests.
protected override void Setup()
{
// Nothing to do here.
}
// Clean up after the tests.
protected override void Cleanup()
{
// Nothing to do here.
}
public void TestActivationArgumentsConstructor01()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments(null);
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor02()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments(null, null);
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor03()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments(null, null, null);
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor04()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test");
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor05()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test", null);
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor06()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test", new String[] {null});
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor07()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test", new String[] {null, null});
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor08()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test", new String[] {null, null, null});
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor09()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test", new String[] {"A", "B", "C"});
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor10()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test",
new String[] {"A", "B", "C"}, null);
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsConstructor11()
{
try
{
ActivationArguments activationArguments =
new ActivationArguments("Test",
new String[] { "A", "B", "C" },
new String[] { null });
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name);
}
}
public void TestActivationArgumentsFullName01()
{
ActivationArguments activationArguments;
try
{
activationArguments = new ActivationArguments("Test");
AssertEquals("Fullname 1:",
activationArguments.ApplicationFullName, "Test");
activationArguments.ApplicationFullName = "Test1";
AssertEquals("Fullname 2:",
activationArguments.ApplicationFullName, "Test1");
AssertNull("Fullname 3:",
activationArguments.ApplicationManifestPaths);
AssertNull("Fullname 4:", activationArguments.ActivationData);
try
{
activationArguments.ApplicationFullName = null;
Fail("Test Fullname 3 should have thrown an ArgumentNullException");
}
catch (ArgumentNullException)
{
// success
}
activationArguments.ApplicationFullName = String.Empty;
AssertEquals("Fullname 2:",
activationArguments.ApplicationFullName,
String.Empty);
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name +
" at\n" + e.StackTrace);
}
}
public void TestActivationArgumentsManifestPaths01()
{
ActivationArguments activationArguments;
try
{
activationArguments = new ActivationArguments("Test", null);
AssertNull("ApplicationManifestPaths 1:",
activationArguments.ApplicationManifestPaths);
activationArguments.ApplicationManifestPaths = null;
AssertNull("ApplicationManifestPaths 2:",
activationArguments.ApplicationManifestPaths);
// MS docs say this should be an Array with two items but it
// does not throw an exception in this case
activationArguments.ApplicationManifestPaths =
new String[] { null };
AssertNotNull("ApplicationManifestPaths 3:",
activationArguments.ApplicationManifestPaths);
AssertEquals("ApplicationManifestPaths 4:",
activationArguments.ApplicationManifestPaths.Length,
1);
AssertNull("ApplicationManifestPaths 5:",
activationArguments.ApplicationManifestPaths[0]);
activationArguments.ApplicationManifestPaths =
new String[] { null, null };
AssertNotNull("ApplicationManifestPaths 6:",
activationArguments.ApplicationManifestPaths);
AssertEquals("ApplicationManifestPaths 7:",
activationArguments.ApplicationManifestPaths.Length,
2);
AssertNull("ApplicationManifestPaths 8:",
activationArguments.ApplicationManifestPaths[0]);
AssertNull("ApplicationManifestPaths 9:",
activationArguments.ApplicationManifestPaths[1]);
// MS docs say this should be an Array with two items but
// it does not throw an exception in this case
activationArguments.ApplicationManifestPaths =
new String[] { null, null, null };
AssertNotNull("ApplicationManifestPaths 10:",
activationArguments.ApplicationManifestPaths);
AssertEquals("ApplicationManifestPaths 11:",
activationArguments.ApplicationManifestPaths.Length,
3);
AssertNull("ApplicationManifestPaths 12:",
activationArguments.ApplicationManifestPaths[0]);
AssertNull("ApplicationManifestPaths 13:",
activationArguments.ApplicationManifestPaths[1]);
AssertNull("ApplicationManifestPaths 13:",
activationArguments.ApplicationManifestPaths[2]);
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name +
" at\n" + e.StackTrace);
}
}
public void TestActivationArgumentsManifestPaths02()
{
ActivationArguments activationArguments;
String[] strings = { "A", "B" };
try
{
activationArguments = new ActivationArguments("Test", strings);
AssertEquals("activationArguments 1:",
activationArguments.ApplicationManifestPaths.Length, 2);
AssertEquals("activationArguments 2:",
activationArguments.ApplicationManifestPaths[0],
strings[0]);
AssertEquals("activationArguments 3:",
activationArguments.ApplicationManifestPaths[1],
strings[1]);
strings[0] = "C";
AssertEquals("activationArguments 3:",
activationArguments.ApplicationManifestPaths[0],
"C");
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name +
" at\n" + e.StackTrace);
}
}
public void TestActivationArgumentsActivationData01()
{
ActivationArguments activationArguments;
try
{
activationArguments = new ActivationArguments("Test", null, null);
AssertNull("ActivationData 1:",
activationArguments.ActivationData);
activationArguments.ActivationData = null;
AssertNull("ActivationData 2:",
activationArguments.ActivationData);
activationArguments.ActivationData = new String[] { "A" };
AssertNotNull("ActivationData 3:",
activationArguments.ActivationData);
AssertEquals("ActivationData 4:",
activationArguments.ActivationData.Length, 1);
AssertEquals("ActivationData 5:",
activationArguments.ActivationData[0], "A");
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name +
" at\n" + e.StackTrace);
}
}
public void TestActivationArgumentsActivationData02()
{
ActivationArguments activationArguments;
String[] strings = { "A", "B" };
try
{
activationArguments =
new ActivationArguments("Test", null, strings);
AssertEquals("ActivationData 1:",
activationArguments.ActivationData.Length, 2);
AssertEquals("ActivationData 2:",
activationArguments.ActivationData[0], strings[0]);
AssertEquals("ActivationData 3:",
activationArguments.ActivationData[1], strings[1]);
strings[0] = "C";
AssertEquals("ActivationData 4:",
activationArguments.ActivationData[0], "C");
}
catch (Exception e)
{
Fail("Test should not have thrown an " + e.GetType().Name +
" at\n" + e.StackTrace);
}
}
} // class TestActivationArguments
#endif // CONFIG_FRAMEWORK_2_0
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Account.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Account.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Configuration Profiles.
/// </summary>
[RoutePrefix("api/v1.0/account/configuration-profile")]
public class ConfigurationProfileController : FrapidApiController
{
/// <summary>
/// The ConfigurationProfile repository.
/// </summary>
private readonly IConfigurationProfileRepository ConfigurationProfileRepository;
public ConfigurationProfileController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.ConfigurationProfileRepository = new Frapid.Account.DataAccess.ConfigurationProfile
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public ConfigurationProfileController(IConfigurationProfileRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.ConfigurationProfileRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "configuration profile" entity.
/// </summary>
/// <returns>Returns the "configuration profile" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/account/configuration-profile/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "profile_id",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "profile_id", PropertyName = "ProfileId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "profile_name", PropertyName = "ProfileName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "is_active", PropertyName = "IsActive", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "allow_registration", PropertyName = "AllowRegistration", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "registration_office_id", PropertyName = "RegistrationOfficeId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "registration_role_id", PropertyName = "RegistrationRoleId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "allow_facebook_registration", PropertyName = "AllowFacebookRegistration", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "allow_google_registration", PropertyName = "AllowGoogleRegistration", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "google_signin_client_id", PropertyName = "GoogleSigninClientId", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "google_signin_scope", PropertyName = "GoogleSigninScope", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "facebook_app_id", PropertyName = "FacebookAppId", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "facebook_scope", PropertyName = "FacebookScope", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of configuration profiles.
/// </summary>
/// <returns>Returns the count of the configuration profiles.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/account/configuration-profile/count")]
[Authorize]
public long Count()
{
try
{
return this.ConfigurationProfileRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of configuration profile.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/account/configuration-profile/all")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ConfigurationProfile> GetAll()
{
try
{
return this.ConfigurationProfileRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of configuration profile for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/account/configuration-profile/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.ConfigurationProfileRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of configuration profile.
/// </summary>
/// <param name="profileId">Enter ProfileId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{profileId}")]
[Route("~/api/account/configuration-profile/{profileId}")]
[Authorize]
public Frapid.Account.Entities.ConfigurationProfile Get(int profileId)
{
try
{
return this.ConfigurationProfileRepository.Get(profileId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/account/configuration-profile/get")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ConfigurationProfile> Get([FromUri] int[] profileIds)
{
try
{
return this.ConfigurationProfileRepository.Get(profileIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of configuration profile.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/account/configuration-profile/first")]
[Authorize]
public Frapid.Account.Entities.ConfigurationProfile GetFirst()
{
try
{
return this.ConfigurationProfileRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of configuration profile.
/// </summary>
/// <param name="profileId">Enter ProfileId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{profileId}")]
[Route("~/api/account/configuration-profile/previous/{profileId}")]
[Authorize]
public Frapid.Account.Entities.ConfigurationProfile GetPrevious(int profileId)
{
try
{
return this.ConfigurationProfileRepository.GetPrevious(profileId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of configuration profile.
/// </summary>
/// <param name="profileId">Enter ProfileId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{profileId}")]
[Route("~/api/account/configuration-profile/next/{profileId}")]
[Authorize]
public Frapid.Account.Entities.ConfigurationProfile GetNext(int profileId)
{
try
{
return this.ConfigurationProfileRepository.GetNext(profileId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of configuration profile.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/account/configuration-profile/last")]
[Authorize]
public Frapid.Account.Entities.ConfigurationProfile GetLast()
{
try
{
return this.ConfigurationProfileRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 configuration profiles on each page, sorted by the property ProfileId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/account/configuration-profile")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ConfigurationProfile> GetPaginatedResult()
{
try
{
return this.ConfigurationProfileRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 configuration profiles on each page, sorted by the property ProfileId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/account/configuration-profile/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ConfigurationProfile> GetPaginatedResult(long pageNumber)
{
try
{
return this.ConfigurationProfileRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of configuration profiles using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered configuration profiles.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/account/configuration-profile/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ConfigurationProfileRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 configuration profiles on each page, sorted by the property ProfileId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/account/configuration-profile/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ConfigurationProfile> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.ConfigurationProfileRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of configuration profiles using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered configuration profiles.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/account/configuration-profile/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.ConfigurationProfileRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 configuration profiles on each page, sorted by the property ProfileId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/account/configuration-profile/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Account.Entities.ConfigurationProfile> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.ConfigurationProfileRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of configuration profiles.
/// </summary>
/// <returns>Returns an enumerable key/value collection of configuration profiles.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/account/configuration-profile/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.ConfigurationProfileRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for configuration profiles.
/// </summary>
/// <returns>Returns an enumerable custom field collection of configuration profiles.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/account/configuration-profile/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.ConfigurationProfileRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for configuration profiles.
/// </summary>
/// <returns>Returns an enumerable custom field collection of configuration profiles.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/account/configuration-profile/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.ConfigurationProfileRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of ConfigurationProfile class.
/// </summary>
/// <param name="configurationProfile">Your instance of configuration profiles class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/account/configuration-profile/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic configurationProfile = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (configurationProfile == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.ConfigurationProfileRepository.AddOrEdit(configurationProfile, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of ConfigurationProfile class.
/// </summary>
/// <param name="configurationProfile">Your instance of configuration profiles class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{configurationProfile}")]
[Route("~/api/account/configuration-profile/add/{configurationProfile}")]
[Authorize]
public void Add(Frapid.Account.Entities.ConfigurationProfile configurationProfile)
{
if (configurationProfile == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ConfigurationProfileRepository.Add(configurationProfile);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of ConfigurationProfile class.
/// </summary>
/// <param name="configurationProfile">Your instance of ConfigurationProfile class to edit.</param>
/// <param name="profileId">Enter the value for ProfileId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{profileId}")]
[Route("~/api/account/configuration-profile/edit/{profileId}")]
[Authorize]
public void Edit(int profileId, [FromBody] Frapid.Account.Entities.ConfigurationProfile configurationProfile)
{
if (configurationProfile == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.ConfigurationProfileRepository.Update(configurationProfile, profileId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of ConfigurationProfile class.
/// </summary>
/// <param name="collection">Your collection of ConfigurationProfile class to bulk import.</param>
/// <returns>Returns list of imported profileIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any ConfigurationProfile class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/account/configuration-profile/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> configurationProfileCollection = this.ParseCollection(collection);
if (configurationProfileCollection == null || configurationProfileCollection.Count.Equals(0))
{
return null;
}
try
{
return this.ConfigurationProfileRepository.BulkImport(configurationProfileCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of ConfigurationProfile class via ProfileId.
/// </summary>
/// <param name="profileId">Enter the value for ProfileId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{profileId}")]
[Route("~/api/account/configuration-profile/delete/{profileId}")]
[Authorize]
public void Delete(int profileId)
{
try
{
this.ConfigurationProfileRepository.Delete(profileId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryDivideTests
{
#region Test methods
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
public static void CheckByteDivideTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteDivide(array[i], array[j]);
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
public static void CheckSByteDivideTest()
{
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++)
{
VerifySByteDivide(array[i], array[j]);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckUShortDivideTest(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++)
{
VerifyUShortDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckShortDivideTest(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++)
{
VerifyShortDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckUIntDivideTest(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++)
{
VerifyUIntDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckIntDivideTest(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++)
{
VerifyIntDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckULongDivideTest(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++)
{
VerifyULongDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void CheckLongDivideTest(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++)
{
VerifyLongDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatDivideTest(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++)
{
VerifyFloatDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleDivideTest(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++)
{
VerifyDoubleDivide(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalDivideTest(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++)
{
VerifyDecimalDivide(array[i], array[j], useInterpreter);
}
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
public static void CheckCharDivideTest()
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharDivide(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteDivide(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
private static void VerifySByteDivide(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
private static void VerifyUShortDivide(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Divide(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal((ushort)(a / b), f());
}
private static void VerifyShortDivide(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Divide(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(unchecked((short)(a / b)), f());
}
private static void VerifyUIntDivide(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Divide(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyIntDivide(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Divide(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (b == -1 && a == int.MinValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyULongDivide(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Divide(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyLongDivide(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Divide(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else if (b == -1 && a == long.MinValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyFloatDivide(float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Divide(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(a / b, f());
}
private static void VerifyDoubleDivide(double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Divide(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(a / b, f());
}
private static void VerifyDecimalDivide(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Divide(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
if (b == 0)
Assert.Throws<DivideByZeroException>(() => f());
else
Assert.Equal(a / b, f());
}
private static void VerifyCharDivide(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Divide(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.Divide(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.Divide(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.Divide(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Divide(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e = Expression.Divide(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a / b)", e.ToString());
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.TeleTrust;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO.Pem;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.OpenSsl
{
/**
* Class for reading OpenSSL PEM encoded streams containing
* X509 certificates, PKCS8 encoded keys and PKCS7 objects.
* <p>
* In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Keys and
* Certificates will be returned using the appropriate java.security type.</p>
*/
public class PemReader
: Org.BouncyCastle.Utilities.IO.Pem.PemReader
{
// private static readonly IDictionary parsers = new Hashtable();
static PemReader()
{
// parsers.Add("CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
// parsers.Add("NEW CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
// parsers.Add("CERTIFICATE", new X509CertificateParser(provider));
// parsers.Add("X509 CERTIFICATE", new X509CertificateParser(provider));
// parsers.Add("X509 CRL", new X509CRLParser(provider));
// parsers.Add("PKCS7", new PKCS7Parser());
// parsers.Add("ATTRIBUTE CERTIFICATE", new X509AttributeCertificateParser());
// parsers.Add("EC PARAMETERS", new ECNamedCurveSpecParser());
// parsers.Add("PUBLIC KEY", new PublicKeyParser(provider));
// parsers.Add("RSA PUBLIC KEY", new RSAPublicKeyParser(provider));
// parsers.Add("RSA PRIVATE KEY", new RSAKeyPairParser(provider));
// parsers.Add("DSA PRIVATE KEY", new DSAKeyPairParser(provider));
// parsers.Add("EC PRIVATE KEY", new ECDSAKeyPairParser(provider));
// parsers.Add("ENCRYPTED PRIVATE KEY", new EncryptedPrivateKeyParser(provider));
// parsers.Add("PRIVATE KEY", new PrivateKeyParser(provider));
}
private readonly IPasswordFinder pFinder;
/**
* Create a new PemReader
*
* @param reader the Reader
*/
public PemReader(
TextReader reader)
: this(reader, null)
{
}
/**
* Create a new PemReader with a password finder
*
* @param reader the Reader
* @param pFinder the password finder
*/
public PemReader(
TextReader reader,
IPasswordFinder pFinder)
: base(reader)
{
this.pFinder = pFinder;
}
public object ReadObject()
{
PemObject obj = ReadPemObject();
if (obj == null)
return null;
// TODO Follow Java build and map to parser objects?
// if (parsers.Contains(obj.Type))
// return ((PemObjectParser)parsers[obj.Type]).ParseObject(obj);
if (obj.Type.EndsWith("PRIVATE KEY"))
return ReadPrivateKey(obj);
switch (obj.Type)
{
case "PUBLIC KEY":
return ReadPublicKey(obj);
case "RSA PUBLIC KEY":
return ReadRsaPublicKey(obj);
case "CERTIFICATE REQUEST":
case "NEW CERTIFICATE REQUEST":
return ReadCertificateRequest(obj);
case "CERTIFICATE":
case "X509 CERTIFICATE":
return ReadCertificate(obj);
case "PKCS7":
return ReadPkcs7(obj);
case "X509 CRL":
return ReadCrl(obj);
case "ATTRIBUTE CERTIFICATE":
return ReadAttributeCertificate(obj);
// TODO Add back in when tests done, and return type issue resolved
//case "EC PARAMETERS":
// return ReadECParameters(obj);
default:
throw new IOException("unrecognised object: " + obj.Type);
}
}
private AsymmetricKeyParameter ReadRsaPublicKey(PemObject pemObject)
{
RsaPublicKeyStructure rsaPubStructure = RsaPublicKeyStructure.GetInstance(
Asn1Object.FromByteArray(pemObject.Content));
return new RsaKeyParameters(
false, // not private
rsaPubStructure.Modulus,
rsaPubStructure.PublicExponent);
}
private AsymmetricKeyParameter ReadPublicKey(PemObject pemObject)
{
return PublicKeyFactory.CreateKey(pemObject.Content);
}
/**
* Reads in a X509Certificate.
*
* @return the X509Certificate
* @throws IOException if an I/O error occured
*/
private X509Certificate ReadCertificate(PemObject pemObject)
{
try
{
return new X509CertificateParser().ReadCertificate(pemObject.Content);
}
catch (Exception e)
{
throw new PemException("problem parsing cert: " + e.ToString());
}
}
/**
* Reads in a X509CRL.
*
* @return the X509Certificate
* @throws IOException if an I/O error occured
*/
private X509Crl ReadCrl(PemObject pemObject)
{
try
{
return new X509CrlParser().ReadCrl(pemObject.Content);
}
catch (Exception e)
{
throw new PemException("problem parsing cert: " + e.ToString());
}
}
/**
* Reads in a PKCS10 certification request.
*
* @return the certificate request.
* @throws IOException if an I/O error occured
*/
private Pkcs10CertificationRequest ReadCertificateRequest(PemObject pemObject)
{
try
{
return new Pkcs10CertificationRequest(pemObject.Content);
}
catch (Exception e)
{
throw new PemException("problem parsing cert: " + e.ToString());
}
}
/**
* Reads in a X509 Attribute Certificate.
*
* @return the X509 Attribute Certificate
* @throws IOException if an I/O error occured
*/
private IX509AttributeCertificate ReadAttributeCertificate(PemObject pemObject)
{
return new X509V2AttributeCertificate(pemObject.Content);
}
/**
* Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
* API.
*
* @return the X509Certificate
* @throws IOException if an I/O error occured
*/
// TODO Consider returning Asn1.Pkcs.ContentInfo
private Asn1.Cms.ContentInfo ReadPkcs7(PemObject pemObject)
{
try
{
return Asn1.Cms.ContentInfo.GetInstance(
Asn1Object.FromByteArray(pemObject.Content));
}
catch (Exception e)
{
throw new PemException("problem parsing PKCS7 object: " + e.ToString());
}
}
/**
* Read a Key Pair
*/
private object ReadPrivateKey(PemObject pemObject)
{
//
// extract the key
//
Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY"));
string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();
byte[] keyBytes = pemObject.Content;
IDictionary fields = Platform.CreateHashtable();
foreach (PemHeader header in pemObject.Headers)
{
fields[header.Name] = header.Value;
}
string procType = (string) fields["Proc-Type"];
if (procType == "4,ENCRYPTED")
{
if (pFinder == null)
throw new PasswordException("No password finder specified, but a password is required");
char[] password = pFinder.GetPassword();
if (password == null)
throw new PasswordException("Password is null, but a password is required");
string dekInfo = (string) fields["DEK-Info"];
string[] tknz = dekInfo.Split(',');
string dekAlgName = tknz[0].Trim();
byte[] iv = Hex.Decode(tknz[1].Trim());
keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
}
try
{
AsymmetricKeyParameter pubSpec, privSpec;
Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(keyBytes);
switch (type)
{
case "RSA":
{
if (seq.Count != 9)
throw new PemException("malformed sequence in RSA private key");
RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);
pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
privSpec = new RsaPrivateCrtKeyParameters(
rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
rsa.Coefficient);
break;
}
case "DSA":
{
if (seq.Count != 6)
throw new PemException("malformed sequence in DSA private key");
// TODO Create an ASN1 object somewhere for this?
//DerInteger v = (DerInteger)seq[0];
DerInteger p = (DerInteger)seq[1];
DerInteger q = (DerInteger)seq[2];
DerInteger g = (DerInteger)seq[3];
DerInteger y = (DerInteger)seq[4];
DerInteger x = (DerInteger)seq[5];
DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);
privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
pubSpec = new DsaPublicKeyParameters(y.Value, parameters);
break;
}
case "EC":
{
ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(
X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());
PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());
// TODO Are the keys returned here ECDSA, as Java version forces?
privSpec = PrivateKeyFactory.CreateKey(privInfo);
DerBitString pubKey = pKey.GetPublicKey();
if (pubKey != null)
{
SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());
// TODO Are the keys returned here ECDSA, as Java version forces?
pubSpec = PublicKeyFactory.CreateKey(pubInfo);
}
else
{
pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey(
(ECPrivateKeyParameters)privSpec);
}
break;
}
case "ENCRYPTED":
{
char[] password = pFinder.GetPassword();
if (password == null)
throw new PasswordException("Password is null, but a password is required");
return PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq));
}
case "":
{
return PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq));
}
default:
throw new ArgumentException("Unknown key type: " + type, "type");
}
return new AsymmetricCipherKeyPair(pubSpec, privSpec);
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw new PemException(
"problem creating " + type + " private key: " + e.ToString());
}
}
// TODO Add an equivalent class for ECNamedCurveParameterSpec?
//private ECNamedCurveParameterSpec ReadECParameters(
// private X9ECParameters ReadECParameters(PemObject pemObject)
// {
// DerObjectIdentifier oid = (DerObjectIdentifier)Asn1Object.FromByteArray(pemObject.Content);
//
// //return ECNamedCurveTable.getParameterSpec(oid.Id);
// return GetCurveParameters(oid.Id);
// }
//private static ECDomainParameters GetCurveParameters(
private static X9ECParameters GetCurveParameters(
string name)
{
// TODO ECGost3410NamedCurves support (returns ECDomainParameters though)
X9ECParameters ecP = X962NamedCurves.GetByName(name);
if (ecP == null)
{
ecP = SecNamedCurves.GetByName(name);
if (ecP == null)
{
ecP = NistNamedCurves.GetByName(name);
if (ecP == null)
{
ecP = TeleTrusTNamedCurves.GetByName(name);
if (ecP == null)
throw new Exception("unknown curve name: " + name);
}
}
}
//return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
return ecP;
}
}
}
| |
using J2N;
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Search
{
/*
* 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 ArrayUtil = Lucene.Net.Util.ArrayUtil;
/// <summary>
/// A <see cref="Scorer"/> for OR like queries, counterpart of <see cref="ConjunctionScorer"/>.
/// This <see cref="Scorer"/> implements <see cref="DocIdSetIterator.Advance(int)"/> and uses Advance() on the given <see cref="Scorer"/>s.
/// <para/>
/// This implementation uses the minimumMatch constraint actively to efficiently
/// prune the number of candidates, it is hence a mixture between a pure <see cref="DisjunctionScorer"/>
/// and a <see cref="ConjunctionScorer"/>.
/// </summary>
internal class MinShouldMatchSumScorer : Scorer
{
/// <summary>
/// The overall number of non-finalized scorers </summary>
private int numScorers;
/// <summary>
/// The minimum number of scorers that should match </summary>
private readonly int mm;
/// <summary>
/// A static array of all subscorers sorted by decreasing cost </summary>
private readonly Scorer[] sortedSubScorers;
/// <summary>
/// A monotonically increasing index into the array pointing to the next subscorer that is to be excluded </summary>
private int sortedSubScorersIdx = 0;
private readonly Scorer[] subScorers; // the first numScorers-(mm-1) entries are valid
private int nrInHeap; // 0..(numScorers-(mm-1)-1)
/// <summary>
/// mmStack is supposed to contain the most costly subScorers that still did
/// not run out of docs, sorted by increasing sparsity of docs returned by that subScorer.
/// For now, the cost of subscorers is assumed to be inversely correlated with sparsity.
/// </summary>
private readonly Scorer[] mmStack; // of size mm-1: 0..mm-2, always full
/// <summary>
/// The document number of the current match. </summary>
private int doc = -1;
/// <summary>
/// The number of subscorers that provide the current match. </summary>
protected int m_nrMatchers = -1;
private double score = float.NaN;
/// <summary>
/// Construct a <see cref="MinShouldMatchSumScorer"/>.
/// </summary>
/// <param name="weight"> The weight to be used. </param>
/// <param name="subScorers"> A collection of at least two subscorers. </param>
/// <param name="minimumNrMatchers"> The positive minimum number of subscorers that should
/// match to match this query.
/// <para/>When <paramref name="minimumNrMatchers"/> is bigger than
/// the number of <paramref name="subScorers"/>, no matches will be produced.
/// <para/>When <paramref name="minimumNrMatchers"/> equals the number of <paramref name="subScorers"/>,
/// it is more efficient to use <see cref="ConjunctionScorer"/>. </param>
public MinShouldMatchSumScorer(Weight weight, IList<Scorer> subScorers, int minimumNrMatchers)
: base(weight)
{
this.nrInHeap = this.numScorers = subScorers.Count;
if (minimumNrMatchers <= 0)
{
throw new ArgumentException("Minimum nr of matchers must be positive");
}
if (numScorers <= 1)
{
throw new ArgumentException("There must be at least 2 subScorers");
}
this.mm = minimumNrMatchers;
this.sortedSubScorers = subScorers.ToArray();
// sorting by decreasing subscorer cost should be inversely correlated with
// next docid (assuming costs are due to generating many postings)
ArrayUtil.TimSort(sortedSubScorers, Comparer<Scorer>.Create((o1, o2) => (o2.GetCost() - o1.GetCost()).Signum()));
// take mm-1 most costly subscorers aside
this.mmStack = new Scorer[mm - 1];
for (int i = 0; i < mm - 1; i++)
{
mmStack[i] = sortedSubScorers[i];
}
nrInHeap -= mm - 1;
this.sortedSubScorersIdx = mm - 1;
// take remaining into heap, if any, and heapify
this.subScorers = new Scorer[nrInHeap];
for (int i = 0; i < nrInHeap; i++)
{
this.subScorers[i] = this.sortedSubScorers[mm - 1 + i];
}
MinheapHeapify();
if (Debugging.AssertsEnabled) Debugging.Assert(MinheapCheck());
}
/// <summary>
/// Construct a <see cref="DisjunctionScorer"/>, using one as the minimum number
/// of matching <paramref name="subScorers"/>.
/// </summary>
public MinShouldMatchSumScorer(Weight weight, IList<Scorer> subScorers)
: this(weight, subScorers, 1)
{
}
public override sealed ICollection<ChildScorer> GetChildren()
{
List<ChildScorer> children = new List<ChildScorer>(numScorers);
for (int i = 0; i < numScorers; i++)
{
children.Add(new ChildScorer(subScorers[i], "SHOULD"));
}
return children;
}
public override int NextDoc()
{
if (Debugging.AssertsEnabled) Debugging.Assert(doc != NO_MORE_DOCS);
while (true)
{
// to remove current doc, call next() on all subScorers on current doc within heap
while (subScorers[0].DocID == doc)
{
if (subScorers[0].NextDoc() != NO_MORE_DOCS)
{
MinheapSiftDown(0);
}
else
{
MinheapRemoveRoot();
numScorers--;
if (numScorers < mm)
{
return doc = NO_MORE_DOCS;
}
}
//assert minheapCheck();
}
EvaluateSmallestDocInHeap();
if (m_nrMatchers >= mm) // doc satisfies mm constraint
{
break;
}
}
return doc;
}
private void EvaluateSmallestDocInHeap()
{
// within heap, subScorer[0] now contains the next candidate doc
doc = subScorers[0].DocID;
if (doc == NO_MORE_DOCS)
{
m_nrMatchers = int.MaxValue; // stop looping
return;
}
// 1. score and count number of matching subScorers within heap
score = subScorers[0].GetScore();
m_nrMatchers = 1;
CountMatches(1);
CountMatches(2);
// 2. score and count number of matching subScorers within stack,
// short-circuit: stop when mm can't be reached for current doc, then perform on heap next()
// TODO instead advance() might be possible, but complicates things
for (int i = mm - 2; i >= 0; i--) // first advance sparsest subScorer
{
if (mmStack[i].DocID >= doc || mmStack[i].Advance(doc) != NO_MORE_DOCS)
{
if (mmStack[i].DocID == doc) // either it was already on doc, or got there via advance()
{
m_nrMatchers++;
score += mmStack[i].GetScore();
} // scorer advanced to next after doc, check if enough scorers left for current doc
else
{
if (m_nrMatchers + i < mm) // too few subScorers left, abort advancing
{
return; // continue looping TODO consider advance() here
}
}
} // subScorer exhausted
else
{
numScorers--;
if (numScorers < mm) // too few subScorers left
{
doc = NO_MORE_DOCS;
m_nrMatchers = int.MaxValue; // stop looping
return;
}
if (mm - 2 - i > 0)
{
// shift RHS of array left
Array.Copy(mmStack, i + 1, mmStack, i, mm - 2 - i);
}
// find next most costly subScorer within heap TODO can this be done better?
while (!MinheapRemove(sortedSubScorers[sortedSubScorersIdx++]))
{
//assert minheapCheck();
}
// add the subScorer removed from heap to stack
mmStack[mm - 2] = sortedSubScorers[sortedSubScorersIdx - 1];
if (m_nrMatchers + i < mm) // too few subScorers left, abort advancing
{
return; // continue looping TODO consider advance() here
}
}
}
}
// TODO: this currently scores, but so did the previous impl
// TODO: remove recursion.
// TODO: consider separating scoring out of here, then modify this
// and afterNext() to terminate when nrMatchers == minimumNrMatchers
// then also change freq() to just always compute it from scratch
private void CountMatches(int root)
{
if (root < nrInHeap && subScorers[root].DocID == doc)
{
m_nrMatchers++;
score += subScorers[root].GetScore();
CountMatches((root << 1) + 1);
CountMatches((root << 1) + 2);
}
}
/// <summary>
/// Returns the score of the current document matching the query. Initially
/// invalid, until <see cref="NextDoc()"/> is called the first time.
/// </summary>
public override float GetScore()
{
return (float)score;
}
public override int DocID => doc;
public override int Freq => m_nrMatchers;
/// <summary>
/// Advances to the first match beyond the current whose document number is
/// greater than or equal to a given target.
/// <para/>
/// The implementation uses the Advance() method on the subscorers.
/// </summary>
/// <param name="target"> The target document number. </param>
/// <returns> The document whose number is greater than or equal to the given
/// target, or -1 if none exist. </returns>
public override int Advance(int target)
{
if (numScorers < mm)
{
return doc = NO_MORE_DOCS;
}
// advance all Scorers in heap at smaller docs to at least target
while (subScorers[0].DocID < target)
{
if (subScorers[0].Advance(target) != NO_MORE_DOCS)
{
MinheapSiftDown(0);
}
else
{
MinheapRemoveRoot();
numScorers--;
if (numScorers < mm)
{
return doc = NO_MORE_DOCS;
}
}
//assert minheapCheck();
}
EvaluateSmallestDocInHeap();
if (m_nrMatchers >= mm)
{
return doc;
}
else
{
return NextDoc();
}
}
public override long GetCost()
{
// cost for merging of lists analog to DisjunctionSumScorer
long costCandidateGeneration = 0;
for (int i = 0; i < nrInHeap; i++)
{
costCandidateGeneration += subScorers[i].GetCost();
}
// TODO is cost for advance() different to cost for iteration + heap merge
// and how do they compare overall to pure disjunctions?
const float c1 = 1.0f, c2 = 1.0f; // maybe a constant, maybe a proportion between costCandidateGeneration and sum(subScorer_to_be_advanced.cost())?
return (long)(c1 * costCandidateGeneration + c2 * costCandidateGeneration * (mm - 1)); // advance() cost - heap-merge cost
}
/// <summary>
/// Organize <see cref="subScorers"/> into a min heap with scorers generating the earliest document on top.
/// </summary>
protected void MinheapHeapify()
{
for (int i = (nrInHeap >> 1) - 1; i >= 0; i--)
{
MinheapSiftDown(i);
}
}
/// <summary>
/// The subtree of <see cref="subScorers"/> at root is a min heap except possibly for its root element.
/// Bubble the root down as required to make the subtree a heap.
/// </summary>
protected void MinheapSiftDown(int root)
{
// TODO could this implementation also move rather than swapping neighbours?
Scorer scorer = subScorers[root];
int doc = scorer.DocID;
int i = root;
while (i <= (nrInHeap >> 1) - 1)
{
int lchild = (i << 1) + 1;
Scorer lscorer = subScorers[lchild];
int ldoc = lscorer.DocID;
int rdoc = int.MaxValue, rchild = (i << 1) + 2;
Scorer rscorer = null;
if (rchild < nrInHeap)
{
rscorer = subScorers[rchild];
rdoc = rscorer.DocID;
}
if (ldoc < doc)
{
if (rdoc < ldoc)
{
subScorers[i] = rscorer;
subScorers[rchild] = scorer;
i = rchild;
}
else
{
subScorers[i] = lscorer;
subScorers[lchild] = scorer;
i = lchild;
}
}
else if (rdoc < doc)
{
subScorers[i] = rscorer;
subScorers[rchild] = scorer;
i = rchild;
}
else
{
return;
}
}
}
protected void MinheapSiftUp(int i)
{
Scorer scorer = subScorers[i];
int doc = scorer.DocID;
// find right place for scorer
while (i > 0)
{
int parent = (i - 1) >> 1;
Scorer pscorer = subScorers[parent];
int pdoc = pscorer.DocID;
if (pdoc > doc) // move root down, make space
{
subScorers[i] = subScorers[parent];
i = parent;
} // done, found right place
else
{
break;
}
}
subScorers[i] = scorer;
}
/// <summary>
/// Remove the root <see cref="Scorer"/> from <see cref="subScorers"/> and re-establish it as a heap
/// </summary>
protected void MinheapRemoveRoot()
{
if (nrInHeap == 1)
{
//subScorers[0] = null; // not necessary
nrInHeap = 0;
}
else
{
nrInHeap--;
subScorers[0] = subScorers[nrInHeap];
//subScorers[nrInHeap] = null; // not necessary
MinheapSiftDown(0);
}
}
/// <summary>
/// Removes a given <see cref="Scorer"/> from the heap by placing end of heap at that
/// position and bubbling it either up or down
/// </summary>
protected bool MinheapRemove(Scorer scorer)
{
// find scorer: O(nrInHeap)
for (int i = 0; i < nrInHeap; i++)
{
if (subScorers[i] == scorer) // remove scorer
{
subScorers[i] = subScorers[--nrInHeap];
//if (i != nrInHeap) subScorers[nrInHeap] = null; // not necessary
MinheapSiftUp(i);
MinheapSiftDown(i);
return true;
}
}
return false; // scorer already exhausted
}
internal virtual bool MinheapCheck()
{
return MinheapCheck(0);
}
private bool MinheapCheck(int root)
{
if (root >= nrInHeap)
{
return true;
}
int lchild = (root << 1) + 1;
int rchild = (root << 1) + 2;
if (lchild < nrInHeap && subScorers[root].DocID > subScorers[lchild].DocID)
{
return false;
}
if (rchild < nrInHeap && subScorers[root].DocID > subScorers[rchild].DocID)
{
return false;
}
return MinheapCheck(lchild) && MinheapCheck(rchild);
}
}
}
| |
#if UNITY_2017_2_OR_NEWER
using PlayFab.Json;
using PlayFab.SharedModels;
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace PlayFab.Internal
{
public class PlayFabUnityHttp : IPlayFabTransportPlugin
{
private bool _isInitialized = false;
private readonly int _pendingWwwMessages = 0;
public string AuthKey { get; set; }
public string EntityToken { get; set; }
public bool IsInitialized { get { return _isInitialized; } }
public void Initialize() { _isInitialized = true; }
public void Update() { }
public void OnDestroy() { }
public void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback)
{
PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine(fullUrl, null, successCallback, errorCallback));
}
public void SimplePutCall(string fullUrl, byte[] payload, Action successCallback, Action<string> errorCallback)
{
PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine(fullUrl, payload, (result) => { successCallback(); }, errorCallback));
}
private static IEnumerator SimpleCallCoroutine(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
if (payload == null)
{
using (UnityWebRequest www = UnityWebRequest.Get(fullUrl))
{
#if UNITY_2017_2_OR_NEWER
yield return www.SendWebRequest();
#else
yield return www.Send();
#endif
if (!string.IsNullOrEmpty(www.error))
errorCallback(www.error);
else
successCallback(www.downloadHandler.data);
};
}
else
{
var putRequest = UnityWebRequest.Put(fullUrl, payload);
#if UNITY_2017_2_OR_NEWER
putRequest.chunkedTransfer = false; // can be removed after Unity's PUT will be more stable
putRequest.SendWebRequest();
#else
putRequest.Send();
#endif
#if !UNITY_WEBGL
while (putRequest.uploadProgress < 1 && putRequest.downloadProgress < 1)
{
yield return 1;
}
#else
while (!putRequest.isDone)
{
yield return 1;
}
#endif
if (!string.IsNullOrEmpty(putRequest.error))
errorCallback(putRequest.error);
else
successCallback(null);
}
}
public void MakeApiCall(object reqContainerObj)
{
CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj;
reqContainer.RequestHeaders["Content-Type"] = "application/json";
#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
if (PlayFabSettings.CompressApiData)
{
reqContainer.RequestHeaders["Content-Encoding"] = "GZIP";
reqContainer.RequestHeaders["Accept-Encoding"] = "GZIP";
using (var stream = new MemoryStream())
{
using (var zipstream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Compress,
Ionic.Zlib.CompressionLevel.BestCompression))
{
zipstream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
}
reqContainer.Payload = stream.ToArray();
}
}
#endif
// Start the www corouting to Post, and get a response or error which is then passed to the callbacks.
PlayFabHttp.instance.StartCoroutine(Post(reqContainer));
}
private IEnumerator Post(CallRequestContainer reqContainer)
{
#if PLAYFAB_REQUEST_TIMING
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var startTime = DateTime.UtcNow;
#endif
var www = new UnityWebRequest(reqContainer.FullUrl)
{
uploadHandler = new UploadHandlerRaw(reqContainer.Payload),
downloadHandler = new DownloadHandlerBuffer(),
method = "POST"
};
foreach (var headerPair in reqContainer.RequestHeaders)
{
if (!string.IsNullOrEmpty(headerPair.Key) && !string.IsNullOrEmpty(headerPair.Value))
www.SetRequestHeader(headerPair.Key, headerPair.Value);
else
Debug.LogWarning("Null header: " + headerPair.Key + " = " + headerPair.Value);
}
#if UNITY_2017_2_OR_NEWER
yield return www.SendWebRequest();
#else
yield return www.Send();
#endif
#if PLAYFAB_REQUEST_TIMING
stopwatch.Stop();
var timing = new PlayFabHttp.RequestTiming {
StartTimeUtc = startTime,
ApiEndpoint = reqContainer.ApiEndpoint,
WorkerRequestMs = (int)stopwatch.ElapsedMilliseconds,
MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
};
PlayFabHttp.SendRequestTiming(timing);
#endif
if (!string.IsNullOrEmpty(www.error))
{
OnError(www.error, reqContainer);
}
else
{
try
{
byte[] responseBytes = www.downloadHandler.data;
bool isGzipCompressed = responseBytes != null && responseBytes[0] == 31 && responseBytes[1] == 139;
string responseText = "Unexpected error: cannot decompress GZIP stream.";
if (!isGzipCompressed && responseBytes != null)
responseText = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length);
#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
if (isGzipCompressed)
{
var stream = new MemoryStream(responseBytes);
using (var gZipStream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress, false))
{
var buffer = new byte[4096];
using (var output = new MemoryStream())
{
int read;
while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0)
output.Write(buffer, 0, read);
output.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(output);
var jsonResponse = streamReader.ReadToEnd();
//Debug.Log(jsonResponse);
OnResponse(jsonResponse, reqContainer);
//Debug.Log("Successful UnityHttp decompress for: " + www.url);
}
}
}
else
#endif
{
OnResponse(responseText, reqContainer);
}
}
catch (Exception e)
{
OnError("Unhandled error in PlayFabUnityHttp: " + e, reqContainer);
}
}
www.Dispose();
}
public int GetPendingMessages()
{
return _pendingWwwMessages;
}
public void OnResponse(string response, CallRequestContainer reqContainer)
{
try
{
#if PLAYFAB_REQUEST_TIMING
var startTime = DateTime.UtcNow;
#endif
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
var httpResult = serializer.DeserializeObject<HttpResponseObject>(response);
if (httpResult.code == 200)
{
// We have a good response from the server
reqContainer.JsonResponse = serializer.SerializeObject(httpResult.data);
reqContainer.DeserializeResultJson();
reqContainer.ApiResult.Request = reqContainer.ApiRequest;
reqContainer.ApiResult.CustomData = reqContainer.CustomData;
PlayFabHttp.instance.OnPlayFabApiResult(reqContainer.ApiResult);
#if !DISABLE_PLAYFABCLIENT_API
PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult);
#endif
try
{
PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult,
ApiProcessingEventType.Post);
}
catch (Exception e)
{
Debug.LogException(e);
}
try
{
reqContainer.InvokeSuccessCallback();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
else
{
if (reqContainer.ErrorCallback != null)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, response, reqContainer.CustomData);
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
reqContainer.ErrorCallback(reqContainer.Error);
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void OnError(string error, CallRequestContainer reqContainer)
{
reqContainer.JsonResponse = error;
if (reqContainer.ErrorCallback != null)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData);
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
reqContainer.ErrorCallback(reqContainer.Error);
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Messaging;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using TestExtensions;
using UnitTests.StorageTests;
using Xunit;
namespace UnitTests.MembershipTests
{
internal static class SiloInstanceTableTestConstants
{
internal static readonly TimeSpan Timeout = TimeSpan.FromMinutes(1);
internal static readonly bool DeleteEntriesAfterTest = true; // false; // Set to false for Debug mode
internal static readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created";
internal static readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active";
internal static readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead";
}
[Collection(TestEnvironmentFixture.DefaultCollection)]
public abstract class MembershipTableTestsBase : IDisposable, IClassFixture<ConnectionStringFixture>
{
private readonly TestEnvironmentFixture environment;
private static readonly string hostName = Dns.GetHostName();
private readonly Logger logger;
private readonly IMembershipTable membershipTable;
private readonly IGatewayListProvider gatewayListProvider;
private readonly string deploymentId;
protected const string testDatabaseName = "OrleansMembershipTest";//for relational storage
protected MembershipTableTestsBase(ConnectionStringFixture fixture, TestEnvironmentFixture environment)
{
this.environment = environment;
LogManager.Initialize(new NodeConfiguration());
logger = LogManager.GetLogger(GetType().Name, LoggerType.Application);
deploymentId = "test-" + Guid.NewGuid();
logger.Info("DeploymentId={0}", deploymentId);
lock (fixture.SyncRoot)
{
if (fixture.ConnectionString == null)
fixture.ConnectionString = GetConnectionString();
}
var globalConfiguration = new GlobalConfiguration
{
DeploymentId = deploymentId,
AdoInvariant = GetAdoInvariant(),
DataConnectionString = fixture.ConnectionString
};
membershipTable = CreateMembershipTable(logger);
membershipTable.InitializeMembershipTable(globalConfiguration, true, logger).WithTimeout(TimeSpan.FromMinutes(1)).Wait();
var clientConfiguration = new ClientConfiguration
{
DeploymentId = globalConfiguration.DeploymentId,
AdoInvariant = globalConfiguration.AdoInvariant,
DataConnectionString = globalConfiguration.DataConnectionString
};
gatewayListProvider = CreateGatewayListProvider(logger);
gatewayListProvider.InitializeGatewayListProvider(clientConfiguration, logger).WithTimeout(TimeSpan.FromMinutes(1)).Wait();
}
public IGrainFactory GrainFactory => this.environment.GrainFactory;
public void Dispose()
{
if (membershipTable != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest)
{
membershipTable.DeleteMembershipTableEntries(deploymentId).Wait();
}
}
protected abstract IGatewayListProvider CreateGatewayListProvider(Logger logger);
protected abstract IMembershipTable CreateMembershipTable(Logger logger);
protected abstract string GetConnectionString();
protected virtual string GetAdoInvariant()
{
return null;
}
protected async Task MembershipTable_GetGateways()
{
var membershipEntries = Enumerable.Range(0, 10).Select(i => CreateMembershipEntryForTest()).ToArray();
membershipEntries[3].Status = SiloStatus.Active;
membershipEntries[3].ProxyPort = 0;
membershipEntries[5].Status = SiloStatus.Active;
membershipEntries[9].Status = SiloStatus.Active;
var data = await membershipTable.ReadAll();
Assert.NotNull(data);
Assert.Equal(0, data.Members.Count);
var version = data.Version;
foreach (var membershipEntry in membershipEntries)
{
Assert.True(await membershipTable.InsertRow(membershipEntry, version));
version = (await membershipTable.ReadRow(membershipEntry.SiloAddress)).Version;
}
var gateways = await gatewayListProvider.GetGateways();
var entries = new List<string>(gateways.Select(g => g.ToString()));
// only members with a non-zero Gateway port
Assert.False(entries.Contains(membershipEntries[3].SiloAddress.ToGatewayUri().ToString()));
// only Active members
Assert.True(entries.Contains(membershipEntries[5].SiloAddress.ToGatewayUri().ToString()));
Assert.True(entries.Contains(membershipEntries[9].SiloAddress.ToGatewayUri().ToString()));
Assert.Equal(2, entries.Count);
}
protected async Task MembershipTable_ReadAll_EmptyTable()
{
var data = await membershipTable.ReadAll();
Assert.NotNull(data);
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(0, data.Members.Count);
Assert.NotNull(data.Version.VersionEtag);
Assert.Equal(0, data.Version.Version);
}
protected async Task MembershipTable_InsertRow(bool extendedProtocol = true)
{
var membershipEntry = CreateMembershipEntryForTest();
var data = await membershipTable.ReadAll();
Assert.NotNull(data);
Assert.Equal(0, data.Members.Count);
TableVersion nextTableVersion = data.Version.Next();
bool ok = await membershipTable.InsertRow(membershipEntry, nextTableVersion);
Assert.True(ok, "InsertRow failed");
data = await membershipTable.ReadAll();
if (extendedProtocol)
Assert.Equal(1, data.Version.Version);
Assert.Equal(1, data.Members.Count);
}
protected async Task MembershipTable_ReadRow_Insert_Read(bool extendedProtocol = true)
{
MembershipTableData data = await membershipTable.ReadAll();
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(0, data.Members.Count);
TableVersion newTableVersion = data.Version.Next();
MembershipEntry newEntry = CreateMembershipEntryForTest();
bool ok = await membershipTable.InsertRow(newEntry, newTableVersion);
Assert.True(ok, "InsertRow failed");
ok = await membershipTable.InsertRow(newEntry, newTableVersion);
Assert.False(ok, "InsertRow should have failed - same entry, old table version");
if (extendedProtocol)
{
ok = await membershipTable.InsertRow(CreateMembershipEntryForTest(), newTableVersion);
Assert.False(ok, "InsertRow should have failed - new entry, old table version");
}
data = await membershipTable.ReadAll();
if (extendedProtocol)
Assert.Equal(1, data.Version.Version);
TableVersion nextTableVersion = data.Version.Next();
ok = await membershipTable.InsertRow(newEntry, nextTableVersion);
Assert.False(ok, "InsertRow should have failed - duplicate entry");
data = await membershipTable.ReadAll();
Assert.Equal(1, data.Members.Count);
data = await membershipTable.ReadRow(newEntry.SiloAddress);
if (extendedProtocol)
Assert.Equal(newTableVersion.Version, data.Version.Version);
logger.Info("Membership.ReadRow returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(1, data.Members.Count);
Assert.NotNull(data.Version.VersionEtag);
if (extendedProtocol)
{
Assert.NotEqual(newTableVersion.VersionEtag, data.Version.VersionEtag);
Assert.Equal(newTableVersion.Version, data.Version.Version);
}
var membershipEntry = data.Members[0].Item1;
string eTag = data.Members[0].Item2;
logger.Info("Membership.ReadRow returned MembershipEntry ETag={0} Entry={1}", eTag, membershipEntry);
Assert.NotNull(eTag);
Assert.NotNull(membershipEntry);
}
protected async Task MembershipTable_ReadAll_Insert_ReadAll(bool extendedProtocol = true)
{
MembershipTableData data = await membershipTable.ReadAll();
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(0, data.Members.Count);
TableVersion newTableVersion = data.Version.Next();
MembershipEntry newEntry = CreateMembershipEntryForTest();
bool ok = await membershipTable.InsertRow(newEntry, newTableVersion);
Assert.True(ok, "InsertRow failed");
data = await membershipTable.ReadAll();
logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data);
Assert.Equal(1, data.Members.Count);
Assert.NotNull(data.Version.VersionEtag);
if (extendedProtocol)
{
Assert.NotEqual(newTableVersion.VersionEtag, data.Version.VersionEtag);
Assert.Equal(newTableVersion.Version, data.Version.Version);
}
var membershipEntry = data.Members[0].Item1;
string eTag = data.Members[0].Item2;
logger.Info("Membership.ReadAll returned MembershipEntry ETag={0} Entry={1}", eTag, membershipEntry);
Assert.NotNull(eTag);
Assert.NotNull(membershipEntry);
}
protected async Task MembershipTable_UpdateRow(bool extendedProtocol = true)
{
var tableData = await membershipTable.ReadAll();
Assert.NotNull(tableData.Version);
Assert.Equal(0, tableData.Version.Version);
Assert.Equal(0, tableData.Members.Count);
for (int i = 1; i < 10; i++)
{
var siloEntry = CreateMembershipEntryForTest();
siloEntry.SuspectTimes =
new List<Tuple<SiloAddress, DateTime>>
{
new Tuple<SiloAddress, DateTime>(CreateSiloAddressForTest(), GetUtcNowWithSecondsResolution().AddSeconds(1)),
new Tuple<SiloAddress, DateTime>(CreateSiloAddressForTest(), GetUtcNowWithSecondsResolution().AddSeconds(2))
};
TableVersion tableVersion = tableData.Version.Next();
logger.Info("Calling InsertRow with Entry = {0} TableVersion = {1}", siloEntry, tableVersion);
bool ok = await membershipTable.InsertRow(siloEntry, tableVersion);
Assert.True(ok, "InsertRow failed");
tableData = await membershipTable.ReadAll();
var etagBefore = tableData.Get(siloEntry.SiloAddress).Item2;
Assert.NotNull(etagBefore);
if (extendedProtocol)
{
logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} old version={2}", siloEntry,
etagBefore, tableVersion != null ? tableVersion.ToString() : "null");
ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion);
Assert.False(ok, $"row update should have failed - Table Data = {tableData}");
tableData = await membershipTable.ReadAll();
}
tableVersion = tableData.Version.Next();
logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} correct version={2}", siloEntry,
etagBefore, tableVersion != null ? tableVersion.ToString() : "null");
ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion);
Assert.True(ok, $"UpdateRow failed - Table Data = {tableData}");
logger.Info("Calling UpdateRow with Entry = {0} old eTag = {1} old version={2}", siloEntry,
etagBefore, tableVersion != null ? tableVersion.ToString() : "null");
ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion);
Assert.False(ok, $"row update should have failed - Table Data = {tableData}");
tableData = await membershipTable.ReadAll();
var tuple = tableData.Get(siloEntry.SiloAddress);
Assert.Equal(tuple.Item1.ToFullString(true), siloEntry.ToFullString(true));
var etagAfter = tuple.Item2;
if (extendedProtocol)
{
logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} old version={2}", siloEntry,
etagAfter, tableVersion != null ? tableVersion.ToString() : "null");
ok = await membershipTable.UpdateRow(siloEntry, etagAfter, tableVersion);
Assert.False(ok, $"row update should have failed - Table Data = {tableData}");
}
tableData = await membershipTable.ReadAll();
etagBefore = etagAfter;
etagAfter = tableData.Get(siloEntry.SiloAddress).Item2;
Assert.Equal(etagBefore, etagAfter);
Assert.NotNull(tableData.Version);
if (extendedProtocol)
Assert.Equal(tableVersion.Version, tableData.Version.Version);
Assert.Equal(i, tableData.Members.Count);
}
}
protected async Task MembershipTable_UpdateRowInParallel(bool extendedProtocol = true)
{
var tableData = await membershipTable.ReadAll();
var data = CreateMembershipEntryForTest();
TableVersion newTableVer = tableData.Version.Next();
var insertions = Task.WhenAll(Enumerable.Range(1, 20).Select(i => membershipTable.InsertRow(data, newTableVer)));
Assert.True((await insertions).Single(x => x), "InsertRow failed");
await Task.WhenAll(Enumerable.Range(1, 19).Select(async i =>
{
bool done;
do
{
var updatedTableData = await membershipTable.ReadAll();
var updatedRow = updatedTableData.Get(data.SiloAddress);
TableVersion tableVersion = updatedTableData.Version.Next();
await Task.Delay(10);
done = await membershipTable.UpdateRow(updatedRow.Item1, updatedRow.Item2, tableVersion);
} while (!done);
})).WithTimeout(TimeSpan.FromSeconds(30));
tableData = await membershipTable.ReadAll();
Assert.NotNull(tableData.Version);
if (extendedProtocol)
Assert.Equal(20, tableData.Version.Version);
Assert.Equal(1, tableData.Members.Count);
}
protected async Task MembershipTable_UpdateIAmAlive(bool extendedProtocol = true)
{
MembershipTableData tableData = await membershipTable.ReadAll();
TableVersion newTableVersion = tableData.Version.Next();
MembershipEntry newEntry = CreateMembershipEntryForTest();
bool ok = await membershipTable.InsertRow(newEntry, newTableVersion);
Assert.True(ok);
var amAliveTime = DateTime.UtcNow;
// This mimics the arguments MembershipOracle.OnIAmAliveUpdateInTableTimer passes in
var entry = new MembershipEntry
{
SiloAddress = newEntry.SiloAddress,
IAmAliveTime = amAliveTime
};
await membershipTable.UpdateIAmAlive(entry);
tableData = await membershipTable.ReadAll();
Tuple<MembershipEntry, string> member = tableData.Members.First();
Assert.True((amAliveTime - member.Item1.IAmAliveTime).Duration() < TimeSpan.FromMilliseconds(1));
}
private static int generation;
// Utility methods
private static MembershipEntry CreateMembershipEntryForTest()
{
SiloAddress siloAddress = CreateSiloAddressForTest();
var membershipEntry = new MembershipEntry
{
SiloAddress = siloAddress,
HostName = hostName,
SiloName = "TestSiloName",
Status = SiloStatus.Joining,
ProxyPort = siloAddress.Endpoint.Port,
StartTime = GetUtcNowWithSecondsResolution(),
IAmAliveTime = GetUtcNowWithSecondsResolution()
};
return membershipEntry;
}
private static DateTime GetUtcNowWithSecondsResolution()
{
var now = DateTime.UtcNow;
return new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
}
private static SiloAddress CreateSiloAddressForTest()
{
var siloAddress = SiloAddress.NewLocalAddress(Interlocked.Increment(ref generation));
siloAddress.Endpoint.Port = 12345;
return siloAddress;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using Sitecore.Buckets.Util;
using Sitecore.ContentSearch;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
namespace Sitecore.DataBlaster.Load
{
/// <summary>
/// Should be created a fresh for every bulk import action.
/// </summary>
public class BulkLoadContext
{
private ILog _log;
public ILog Log
{
get { return _log; }
set
{
if (value == null) throw new ArgumentNullException(nameof(value));
_log = value;
}
}
public string FailureMessage { get; private set; }
public string Database { get; private set; }
/// <summary>
/// Stages data to temp tables, but don't merge it with existing data.
/// Useful for debugging.
/// </summary>
public bool StageDataWithoutProcessing { get; set; }
/// <summary>
/// Whether to lookup item ids in database by item name or use the item id provided in the value of the field.
/// </summary>
public bool LookupItemIds { get; set; }
/// <summary>
/// Performance optimization when loading items into a specific repository (supports bucketing).
/// </summary>
public ItemReference Destination { get; private set; }
/// <summary>
/// Whether to lookup blob ids in database or use the blob id provided in the value of the field.
/// </summary>
public bool LookupBlobIds { get; set; }
/// <summary>
/// Whether bulk load allows template changes.
/// Typically used during serialization.
/// When set, provided bulk items should contain ALL fields and not partial data.
/// </summary>
public bool AllowTemplateChanges { get; set; }
/// <summary>
/// In the initial version if Sitecore 9.3, they did not put all field records in the right fields table (versioned/unversioned/shared).
/// E.g. the Display Name is configured as unversioned field on the template, but the actual data is stored in the versioned table.
/// We need this extra flag to be able to disable the cleanup operation during bulk load, else the Display Name values will be removed, resulting in empty context menu's.
/// This flag is typically only relevant during deserialization actions.
/// </summary>
public bool AllowCleanupOfFields { get; set; } = true;
/// <summary>
/// Forces updates in Sitecore database, so that all loaded items will have an item change.
/// All modification dates will be reset.
/// </summary>
public bool ForceUpdates { get; set; }
/// <summary>
/// Additional processing rules for fiels which will affect all items with those specified fields.
/// </summary>
public IList<FieldRule> FieldRules { get; set; }
/// <summary>
/// Will ensure bucket folder structure for items that are directly added to a parent that is a bucket.
/// Be aware, this needs to do additional database reads while processing the item stream.
/// </summary>
public bool BucketIfNeeded { get; set; }
/// <summary>
/// Resolves the paths for items in buckets.
/// </summary>
public IDynamicBucketFolderPath BucketFolderPath { get; set; }
/// <summary>
/// Whether to remove updated items from Sitecore caches. Enabled by default.
/// This setting is not impacted by the value of <seealso cref="ClearCaches"/>.
/// </summary>
public bool RemoveItemsFromCaches { get; set; }
/// <summary>
/// Offers an alternative strategy to remove items from Sitecore caches, by clearing them completely.
/// This setting is not impacted by the value of <seealso cref="RemoveItemsFromCaches"/>.
///
/// When both the imported data set and the Sitecore caches are quite large, there is a performance impact in scanning the caches for entries that must be deleted.
/// In this case it could prove more useful to just clear the caches, instead of spending time to scan them. The performance impact is then in repopulation, though.
/// For settings that have an impact on cache removal performance, see <see cref="Sitecore.Configuration.Settings.Caching.CacheKeyIndexingEnabled"/>.
/// </summary>
public bool ClearCaches { get; set; }
/// <summary>
/// Whether to update the history engine of Sitecore. This engine is e.g. used for index syncs.
/// </summary>
public bool? UpdateHistory { get; set; }
/// <summary>
/// Whether to update the publish queue of Sitecore. This queue is used for incremental publishing.
/// </summary>
public bool? UpdatePublishQueue { get; set; }
/// <summary>
/// Whether to update the link database.
/// </summary>
public bool? UpdateLinkDatabase { get; set; }
/// <summary>
/// Whether to update the indexes of Sitecore. Enabled by default.
/// </summary>
public bool UpdateIndexes { get; set; }
private IList<ISearchIndex> _allIndexes;
private IList<ISearchIndex> _indexesToUpdate;
/// <summary>
/// Which indexes to update, will be detected from database by default.
/// </summary>
public IList<ISearchIndex> IndexesToUpdate
{
get
{
if (_indexesToUpdate != null)
return _indexesToUpdate;
// No specific indexes provided, fallback to all indexes for the current Database
if (_allIndexes != null)
return _allIndexes;
_allIndexes = ContentSearchManager.Indexes
.Where(idx => idx.Crawlers
.OfType<SitecoreItemCrawler>()
.Any(c => Database.Equals(c.Database, StringComparison.OrdinalIgnoreCase)))
.ToList();
return _allIndexes;
}
set { _indexesToUpdate = value; }
}
/// <summary>
/// Threshold percentage to refresh destination in index instead of updating it one by one.
/// </summary>
public int? IndexRefreshThresholdPercentage { get; set; }
/// <summary>
/// Threshold percentage to rebuild index instead of updating it one by one.
/// </summary>
public int? IndexRebuildThresholdPercentage { get; set; }
/// <summary>
/// Data is staged in database but no changes are made yet.
/// </summary>
public Action<BulkLoadContext> OnDataStaged { get; set; }
/// <summary>
/// Data is loaded in database.
/// </summary>
public Action<BulkLoadContext> OnDataLoaded { get; set; }
/// <summary>
/// Data is indexed.
/// </summary>
public Action<BulkLoadContext, ICollection<ItemChange>> OnDataIndexed { get; set; }
public LinkedList<ItemChange> ItemChanges { get; } = new LinkedList<ItemChange>();
protected internal BulkLoadContext(string database)
{
if (string.IsNullOrEmpty(database)) throw new ArgumentNullException(nameof(database));
Database = database;
RemoveItemsFromCaches = true;
UpdateIndexes = true;
Log = LoggerFactory.GetLogger(typeof(BulkLoader));
}
public void LookupItemsIn(Guid itemId, string itemPath)
{
LookupItemIds = true;
Destination = new ItemReference(itemId, itemPath);
}
public void LookupItemsIn(Item item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
LookupItemsIn(item.ID.Guid, item.Paths.Path);
}
public bool ShouldUpdateIndex(ISearchIndex searchIndex, ISearchIndexSummary searchIndexSummary)
{
// Always update when index has been explicitly set as to update
if (_indexesToUpdate != null && _indexesToUpdate.Contains(searchIndex))
return true;
// Only update when index is not empty: updating an empty index would trigger a rebuild.
return searchIndexSummary.NumberOfDocuments > 0;
}
#region Stage results and feedback
private readonly Dictionary<Stage, StageResult> _stageResults = new Dictionary<Stage, StageResult>();
public bool AnyStageFailed => _stageResults.Any(x => x.Value.HasFlag(StageResult.Failed));
protected virtual void AddStageResult(Stage stage, StageResult result)
{
StageResult r;
r = _stageResults.TryGetValue(stage, out r)
? r | result
: result;
_stageResults[stage] = r;
}
public virtual void StageSucceeded(Stage stage)
{
AddStageResult(stage, StageResult.Succeeded);
}
public virtual void StageFailed(Stage stage, Exception ex, string message)
{
AddStageResult(stage, StageResult.Failed);
if (ex == null)
Log.Fatal(message);
else
Log.Fatal(message +
$"\nException type: {ex.GetType().Name}\nException message: {ex.Message}\nStack trace: {ex.StackTrace}");
FailureMessage = message;
}
public virtual void StageFailed(Stage stage, string message)
{
StageFailed(stage, null, message);
}
public virtual void SkipItemWarning(string message)
{
Log.Warn(message + " Skipping item.");
}
public virtual void SkipItemDebug(string message)
{
Log.Debug(message + " Skipping item.");
}
#endregion
#region Tracked item data
/// <summary>
/// Tracks path and template info of the bulk item within the context,
/// so that we can check whether bucketing is still needed, or do lookups by path.
/// Doesn't keep a reference to the item, so that we're not too memory intensive.
/// </summary>
/// <param name="item">Item to attach.</param>
public virtual void TrackPathAndTemplateInfo(BulkLoadItem item)
{
// Cache template id per item.
var templateCache = GetTemplateCache();
templateCache[item.Id] = item.TemplateId;
// Cache path.
IDictionary<string, Guid> pathCache = null;
if (!string.IsNullOrWhiteSpace(item.ItemPath))
{
pathCache = GetPathCache();
pathCache[item.ItemPath] = item.Id;
}
// Cache lookup path.
if (!string.IsNullOrWhiteSpace(item.ItemLookupPath))
{
pathCache = pathCache ?? GetPathCache();
pathCache[item.ItemLookupPath] = item.Id;
}
}
private IDictionary<string, Guid> GetPathCache()
{
return GetOrAddState("Transform.PathCache",
() => new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase));
}
private IDictionary<Guid, Guid> GetTemplateCache()
{
return GetOrAddState("Import.TemplateCache",
() => new Dictionary<Guid, Guid>());
}
public virtual Guid? GetProcessedPath(string itemPath)
{
if (string.IsNullOrWhiteSpace(itemPath)) return null;
var cache = GetPathCache();
Guid id;
return cache.TryGetValue(itemPath, out id) ? id : (Guid?)null;
}
public virtual Guid? GetProcessedItemTemplateId(Guid itemId)
{
var cache = GetTemplateCache();
Guid id;
return cache.TryGetValue(itemId, out id) ? id : (Guid?)null;
}
#endregion
#region Additional state
private readonly Dictionary<string, object> _state =
new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets state from the context.
/// </summary>
/// <typeparam name="T">Type of the state.</typeparam>
/// <param name="key">Key for the state.</param>
/// <param name="defaultValue">Default value when state is not present.</param>
/// <returns>Retrieved state or default value.</returns>
/// <remarks>Not thread safe.</remarks>
public T GetState<T>(string key, T defaultValue = default(T))
{
object state;
if (!_state.TryGetValue(key, out state))
{
return defaultValue;
}
return (T)state;
}
/// <summary>
/// Gets or adds new state to the context.
/// </summary>
/// <typeparam name="T">Type of the state.</typeparam>
/// <param name="key">Key for the state.</param>
/// <param name="stateFactory">Factory to create new state.</param>
/// <returns>Retrieved or newly added state.</returns>
/// <remarks>Not thread safe.</remarks>
public T GetOrAddState<T>(string key, Func<T> stateFactory)
{
object state;
if (!_state.TryGetValue(key, out state))
{
state = stateFactory();
_state[key] = state;
}
return (T)state;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class IntellisenseFacts : AbstractAutoCompleteTestFixture
{
private readonly ILogger _logger;
public IntellisenseFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
this._logger = this.LoggerFactory.CreateLogger<IntellisenseFacts>();
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_is_correct_for_property(string filename)
{
const string input =
@"public class Class1 {
public int Foo { get; set; }
public Class1()
{
Foo$$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_is_correct_for_variable(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
var foo = 1;
foo$$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "foo");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_matches_snippet_for_snippet_response(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
Foo$$
}
public void Foo(int bar = 1)
{
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(2), "Foo()", "Foo(int bar = 1)");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_matches_snippet_for_non_snippet_response(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
Foo$$
}
public void Foo(int bar = 1)
{
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: false);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo(int bar = 1)");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_camel_case_completions(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.tp$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "TryParse");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_sub_sequence_completions(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.ng$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "NewGuid");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_sub_sequence_completions_without_matching_firstletter(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.gu$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "NewGuid");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_method_header(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.ng$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.MethodHeader).Take(1), "NewGuid()");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_variable_before_class(string filename)
{
const string input =
@"public class MyClass1 {
public MyClass1()
{
var myvar = 1;
my$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText), "myvar", "MyClass1");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_class_before_variable(string filename)
{
const string input =
@"public class MyClass1 {
public MyClass1()
{
var myvar = 1;
My$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText), "MyClass1", "myvar");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_empty_sequence_in_invalid_context(string filename)
{
const string source =
@"public class MyClass1 {
public MyClass1()
{
var x$$
}
}";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText), Array.Empty<string>());
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_attribute_without_attribute_suffix(string filename)
{
const string source =
@"using System;
public class BarAttribute : Attribute {}
[B$$
public class Foo {}";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "Bar");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_members_in_object_initializer_context(string filename)
{
const string source =
@"public class MyClass1 {
public string Foo {get; set;}
}
public class MyClass2 {
public MyClass2()
{
var c = new MyClass1 {
F$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText), "Foo");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_parameter_name_inside_a_method(string filename)
{
const string source =
@"public class MyClass1 {
public void SayHi(string text) {}
}
public class MyClass2 {
public MyClass2()
{
var c = new MyClass1();
c.SayHi(te$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "text:");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_override_signatures(string filename)
{
const string source =
@"class Foo
{
public virtual void Test(string text) {}
public virtual void Test(string text, string moreText) {}
}
class FooChild : Foo
{
override $$
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText), "Equals(object obj)", "GetHashCode()", "Test(string text)", "Test(string text, string moreText)", "ToString()");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_cref_completion(string filename)
{
const string source =
@" /// <summary>
/// A comment. <see cref=""My$$"" /> for more details
/// </summary>
public class MyClass1 {
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "MyClass1");
}
[Fact]
public async Task Returns_host_object_members_in_csx()
{
const string source =
"Prin$$";
var completions = await FindCompletionsAsync("dummy.csx", source);
ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "Print", "PrintOptions" });
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_true_for_lambda_expression_position1(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M(Func<int, int> a) { }
void M()
{
M(c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => c.IsSuggestionMode));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_true_for_lambda_expression_position2(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M()
{
Func<int, int> a = c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => c.IsSuggestionMode));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_false_for_normal_position1(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M(int a) { }
void M()
{
M(c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => !c.IsSuggestionMode));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_false_for_normal_position2(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M()
{
int a = c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => !c.IsSuggestionMode));
}
[Fact]
public async Task Scripting_by_default_returns_completions_for_CSharp7_1()
{
const string source =
@"
var number1 = 1;
var number2 = 2;
var tuple = (number1, number2);
tuple.n$$
";
var completions = await FindCompletionsAsync("dummy.csx", source);
ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "number1", "number2" });
}
[Fact]
public async Task Scripting_by_default_returns_completions_for_CSharp7_2()
{
const string source =
@"
public class Foo { private protected int myValue = 0; }
public class Bar : Foo
{
public Bar()
{
var x = myv$$
}
}
";
var completions = await FindCompletionsAsync("dummy.csx", source);
ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "myValue" });
}
private void ContainsCompletions(IEnumerable<string> completions, params string[] expected)
{
if (!completions.SequenceEqual(expected))
{
var builder = new StringBuilder();
builder.AppendLine("Expected");
builder.AppendLine("--------");
foreach (var completion in expected)
{
builder.AppendLine(completion);
}
builder.AppendLine();
builder.AppendLine("Found");
builder.AppendLine("-----");
foreach (var completion in completions)
{
builder.AppendLine(completion);
}
this._logger.LogError(builder.ToString());
}
Assert.Equal(expected, completions.ToArray());
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task TriggeredOnSpaceForObjectCreation(string filename)
{
const string input =
@"public class Class1 {
public M()
{
Class1 c = new $$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true, triggerChar: " ");
Assert.NotEmpty(completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task ReturnsAtleastOnePreselectOnNew(string filename)
{
const string input =
@"public class Class1 {
public M()
{
Class1 c = new $$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true, triggerChar: " ");
Assert.NotEmpty(completions.Where(completion => completion.Preselect == true));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task NotTriggeredOnSpaceWithoutObjectCreation(string filename)
{
const string input =
@"public class Class1 {
public M()
{
$$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true, triggerChar: " ");
Assert.Empty(completions);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BaseProcessor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System.Collections;
using System.Text;
using System.Diagnostics;
internal class BaseProcessor {
XmlNameTable nameTable;
SchemaNames schemaNames;
ValidationEventHandler eventHandler;
XmlSchemaCompilationSettings compilationSettings;
int errorCount = 0;
string NsXml;
public BaseProcessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
: this(nameTable, schemaNames, eventHandler, new XmlSchemaCompilationSettings()) {} //Use the default for XmlSchemaCollection
public BaseProcessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings) {
Debug.Assert(nameTable != null);
this.nameTable = nameTable;
this.schemaNames = schemaNames;
this.eventHandler = eventHandler;
this.compilationSettings = compilationSettings;
NsXml = nameTable.Add(XmlReservedNs.NsXml);
}
protected XmlNameTable NameTable {
get { return nameTable; }
}
protected SchemaNames SchemaNames {
get {
if (schemaNames == null) {
schemaNames = new SchemaNames(nameTable);
}
return schemaNames;
}
}
protected ValidationEventHandler EventHandler {
get { return eventHandler; }
}
protected XmlSchemaCompilationSettings CompilationSettings {
get { return compilationSettings; }
}
protected bool HasErrors {
get { return errorCount != 0; }
}
protected void AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item) {
if (qname.Name.Length == 0) {
return;
}
XmlSchemaObject existingObject = (XmlSchemaObject)table[qname];
if (existingObject != null) {
if (existingObject == item) {
return;
}
string code = Res.Sch_DupGlobalElement;
if (item is XmlSchemaAttributeGroup) {
string ns = nameTable.Add(qname.Namespace);
if (Ref.Equal(ns, NsXml)) { //Check for xml namespace
XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema();
XmlSchemaObject builtInAttributeGroup = schemaForXmlNS.AttributeGroups[qname];
if ((object)existingObject == (object)builtInAttributeGroup) {
table.Insert(qname, item);
return;
}
else if ((object)item == (object)builtInAttributeGroup) { //trying to overwrite customer's component with built-in, ignore built-in
return;
}
}
else if (IsValidAttributeGroupRedefine(existingObject, item, table)){ //check for redefines
return;
}
code = Res.Sch_DupAttributeGroup;
}
else if (item is XmlSchemaAttribute) {
string ns = nameTable.Add(qname.Namespace);
if (Ref.Equal(ns, NsXml)) {
XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema();
XmlSchemaObject builtInAttribute = schemaForXmlNS.Attributes[qname];
if ((object)existingObject == (object)builtInAttribute) { //replace built-in one
table.Insert(qname, item);
return;
}
else if ((object)item == (object)builtInAttribute) { //trying to overwrite customer's component with built-in, ignore built-in
return;
}
}
code = Res.Sch_DupGlobalAttribute;
}
else if (item is XmlSchemaSimpleType) {
if (IsValidTypeRedefine(existingObject, item, table)) {
return;
}
code = Res.Sch_DupSimpleType;
}
else if (item is XmlSchemaComplexType) {
if (IsValidTypeRedefine(existingObject, item, table)) {
return;
}
code = Res.Sch_DupComplexType;
}
else if (item is XmlSchemaGroup) {
if (IsValidGroupRedefine(existingObject, item, table)){ //check for redefines
return;
}
code = Res.Sch_DupGroup;
}
else if (item is XmlSchemaNotation) {
code = Res.Sch_DupNotation;
}
else if (item is XmlSchemaIdentityConstraint) {
code = Res.Sch_DupIdentityConstraint;
}
else {
Debug.Assert(item is XmlSchemaElement);
}
SendValidationEvent(code, qname.ToString(), item);
}
else {
table.Add(qname, item);
}
}
private bool IsValidAttributeGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) {
XmlSchemaAttributeGroup attGroup = item as XmlSchemaAttributeGroup;
XmlSchemaAttributeGroup existingAttGroup = existingObject as XmlSchemaAttributeGroup;
if (existingAttGroup == attGroup.Redefined) { //attribute group is the redefinition of existingObject
if (existingAttGroup.AttributeUses.Count == 0) { //If the existing one is not already compiled, then replace.
table.Insert(attGroup.QualifiedName, attGroup); //Update with redefined entry
return true;
}
}
else if (existingAttGroup.Redefined == attGroup) { //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
return true;
}
return false;
}
private bool IsValidGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) {
XmlSchemaGroup group = item as XmlSchemaGroup;
XmlSchemaGroup existingGroup = existingObject as XmlSchemaGroup;
if (existingGroup == group.Redefined) { //group is the redefinition of existingObject
if (existingGroup.CanonicalParticle == null) { //If the existing one is not already compiled, then replace.
table.Insert(group.QualifiedName, group); //Update with redefined entry
return true;
}
}
else if (existingGroup.Redefined == group) { //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
return true;
}
return false;
}
private bool IsValidTypeRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) {
XmlSchemaType schemaType = item as XmlSchemaType;
XmlSchemaType existingType = existingObject as XmlSchemaType;
if (existingType == schemaType.Redefined) { //schemaType is the redefinition of existingObject
if (existingType.ElementDecl == null) { //If the existing one is not already compiled, then replace.
table.Insert(schemaType.QualifiedName, schemaType); //Update with redefined entry
return true;
}
}
else if (existingType.Redefined == schemaType) { //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
return true;
}
return false;
}
protected void SendValidationEvent(string code, XmlSchemaObject source) {
SendValidationEvent(new XmlSchemaException(code, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg, XmlSchemaObject source) {
SendValidationEvent(new XmlSchemaException(code, msg, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg1, string msg2, XmlSchemaObject source) {
SendValidationEvent(new XmlSchemaException(code, new string[] { msg1, msg2 }, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string[] args, Exception innerException, XmlSchemaObject source) {
SendValidationEvent(new XmlSchemaException(code, args, innerException, source.SourceUri, source.LineNumber, source.LinePosition, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg1, string msg2, string sourceUri, int lineNumber, int linePosition) {
SendValidationEvent(new XmlSchemaException(code, new string[] { msg1, msg2 }, sourceUri, lineNumber, linePosition), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, XmlSchemaObject source, XmlSeverityType severity) {
SendValidationEvent(new XmlSchemaException(code, source), severity);
}
protected void SendValidationEvent(XmlSchemaException e) {
SendValidationEvent(e, XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg, XmlSchemaObject source, XmlSeverityType severity) {
SendValidationEvent(new XmlSchemaException(code, msg, source), severity);
}
protected void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity) {
if (severity == XmlSeverityType.Error) {
errorCount ++;
}
if (eventHandler != null) {
eventHandler(null, new ValidationEventArgs(e, severity));
}
else if (severity == XmlSeverityType.Error) {
throw e;
}
}
protected void SendValidationEventNoThrow(XmlSchemaException e, XmlSeverityType severity) {
if (severity == XmlSeverityType.Error) {
errorCount ++;
}
if (eventHandler != null) {
eventHandler(null, new ValidationEventArgs(e, severity));
}
}
};
} // namespace System.Xml
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of Replication protected item operations for the Site
/// Recovery extension.
/// </summary>
public partial interface IReplicationProtectedItemOperations
{
/// <summary>
/// Apply recovery point for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Apply recovery point input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> ApplyRecoveryPointAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, ApplyRecoveryPointInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Apply recovery point for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Apply recovery point input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginApplyRecoveryPointAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, ApplyRecoveryPointInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute commit failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginCommitFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Disable Protection for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='input'>
/// Disable protection input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginDisableProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, DisableProtectionInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Enable Protection for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='input'>
/// Enable protection input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginEnableProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute planned failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Planned failover input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginPlannedFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, PlannedFailoverInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Purges Protection for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginPurgeProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Executes repair replication for the given Replication protected
/// item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginRepairReplicationAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute reprotect for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Reprotect input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginReprotectAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, ReverseReplicationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute Test failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Test failover input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginTestFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, TestFailoverInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute unplanned failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Unplanned failover input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginUnplannedFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, UnplannedFailoverInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Update mobility service for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Update mobility service input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginUpdateMobilityServiceAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateMobilityServiceRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Updates the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Updation input
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginUpdateProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateReplicationProtectedItemInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute commit failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> CommitFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Disable Protection for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='input'>
/// Disable protection input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> DisableProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, DisableProtectionInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Enable Protection for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='input'>
/// Enable protection input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> EnableProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Get the replication protected object by Id.
/// </summary>
/// <param name='fabricName'>
/// Fabric unique name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container unique name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the fabric object
/// </returns>
Task<ReplicationProtectedItemResponse> GetAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetApplyRecoveryPointStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetCommitFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> GetDisableStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetEnableStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetPlannedFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> GetPurgeStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetRepairReplicationStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetReprotectStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetTestFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetUnplannedFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetUpdateMobilityServiceStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Service response for replication protected items operation.
/// </returns>
Task<ReplicationProtectedItemOperationResponse> GetUpdateProtectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Get the replication protected object by Id.
/// </summary>
/// <param name='fabricName'>
/// Fabric unique name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list replicated protected items.
/// </returns>
Task<ReplicationProtectedItemListResponse> ListAsync(string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Enumerate all replication protected items under vault.
/// </summary>
/// <param name='skipToken'>
/// Continuation Token.
/// </param>
/// <param name='parameters'>
/// Protected items query parameter.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list replicated protected items.
/// </returns>
Task<ReplicationProtectedItemListResponse> ListAllAsync(string skipToken, ProtectedItemsQueryParameter parameters, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Get subsequent page data for replication protected items under
/// vault.
/// </summary>
/// <param name='nextLink'>
/// The url to the next protected items page.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list replicated protected items.
/// </returns>
Task<ReplicationProtectedItemListResponse> ListAllNextAsync(string nextLink, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Gets list of recovery azure vm sizes for a replication protected
/// item.
/// </summary>
/// <param name='fabricName'>
/// Fabric unique name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container unique name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list of recovery azure vm sizes.
/// </returns>
Task<TargetComputeSizeResponse> ListTargetComputeSizesAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute planned failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Planned failover input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> PlannedFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, PlannedFailoverInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Purge Protection for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item unique name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> PurgeProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Executes repair replication for the given Replication protected
/// item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> RepairReplicationAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute reprotect for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Reprotect input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> ReprotectAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, ReverseReplicationInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute Test failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Test failover input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> TestFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, TestFailoverInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Execute unplanned failover for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Unplanned failover input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> UnplannedFailoverAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, UnplannedFailoverInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Update mobility service for the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Update mobility service input.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> UpdateMobilityServiceAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateMobilityServiceRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Updates the given Replication protected item.
/// </summary>
/// <param name='fabricName'>
/// Fabric name.
/// </param>
/// <param name='protectionContainerName'>
/// Protection container name.
/// </param>
/// <param name='replicationProtectedItemName'>
/// Replication protected item name.
/// </param>
/// <param name='input'>
/// Updation input
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> UpdateProtectionAsync(string fabricName, string protectionContainerName, string replicationProtectedItemName, UpdateReplicationProtectedItemInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
}
}
| |
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL)
#region License
/*
* WebSocketFrame.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Chris Swiedler
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace WebSocketSharp
{
internal class WebSocketFrame : IEnumerable<byte>
{
#region Private Fields
private byte[] _extPayloadLength;
private Fin _fin;
private Mask _mask;
private byte[] _maskingKey;
private Opcode _opcode;
private PayloadData _payloadData;
private byte _payloadLength;
private Rsv _rsv1;
private Rsv _rsv2;
private Rsv _rsv3;
#endregion
#region Internal Fields
/// <summary>
/// Represents the ping frame without the payload data as an array of <see cref="byte"/>.
/// </summary>
/// <remarks>
/// The value of this field is created from a non masked frame, so it can only be used to
/// send a ping from a server.
/// </remarks>
internal static readonly byte[] EmptyPingBytes;
#endregion
#region Static Constructor
static WebSocketFrame ()
{
EmptyPingBytes = CreatePingFrame (false).ToArray ();
}
#endregion
#region Private Constructors
private WebSocketFrame ()
{
}
#endregion
#region Internal Constructors
internal WebSocketFrame (Opcode opcode, PayloadData payloadData, bool mask)
: this (Fin.Final, opcode, payloadData, false, mask)
{
}
internal WebSocketFrame (Fin fin, Opcode opcode, byte[] data, bool compressed, bool mask)
: this (fin, opcode, new PayloadData (data), compressed, mask)
{
}
internal WebSocketFrame (
Fin fin, Opcode opcode, PayloadData payloadData, bool compressed, bool mask)
{
_fin = fin;
_rsv1 = opcode.IsData () && compressed ? Rsv.On : Rsv.Off;
_rsv2 = Rsv.Off;
_rsv3 = Rsv.Off;
_opcode = opcode;
var len = payloadData.Length;
if (len < 126) {
_payloadLength = (byte) len;
_extPayloadLength = WebSocket.EmptyBytes;
}
else if (len < 0x010000) {
_payloadLength = (byte) 126;
_extPayloadLength = ((ushort) len).InternalToByteArray (ByteOrder.Big);
}
else {
_payloadLength = (byte) 127;
_extPayloadLength = len.InternalToByteArray (ByteOrder.Big);
}
if (mask) {
_mask = Mask.On;
_maskingKey = createMaskingKey ();
payloadData.Mask (_maskingKey);
}
else {
_mask = Mask.Off;
_maskingKey = WebSocket.EmptyBytes;
}
_payloadData = payloadData;
}
#endregion
#region Internal Properties
internal int ExtendedPayloadLengthCount {
get {
return _payloadLength < 126 ? 0 : (_payloadLength == 126 ? 2 : 8);
}
}
internal ulong FullPayloadLength {
get {
return _payloadLength < 126
? _payloadLength
: _payloadLength == 126
? _extPayloadLength.ToUInt16 (ByteOrder.Big)
: _extPayloadLength.ToUInt64 (ByteOrder.Big);
}
}
#endregion
#region Public Properties
public byte[] ExtendedPayloadLength {
get {
return _extPayloadLength;
}
}
public Fin Fin {
get {
return _fin;
}
}
public bool IsBinary {
get {
return _opcode == Opcode.Binary;
}
}
public bool IsClose {
get {
return _opcode == Opcode.Close;
}
}
public bool IsCompressed {
get {
return _rsv1 == Rsv.On;
}
}
public bool IsContinuation {
get {
return _opcode == Opcode.Cont;
}
}
public bool IsControl {
get {
return _opcode >= Opcode.Close;
}
}
public bool IsData {
get {
return _opcode == Opcode.Text || _opcode == Opcode.Binary;
}
}
public bool IsFinal {
get {
return _fin == Fin.Final;
}
}
public bool IsFragment {
get {
return _fin == Fin.More || _opcode == Opcode.Cont;
}
}
public bool IsMasked {
get {
return _mask == Mask.On;
}
}
public bool IsPing {
get {
return _opcode == Opcode.Ping;
}
}
public bool IsPong {
get {
return _opcode == Opcode.Pong;
}
}
public bool IsText {
get {
return _opcode == Opcode.Text;
}
}
public ulong Length {
get {
return 2 + (ulong) (_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length;
}
}
public Mask Mask {
get {
return _mask;
}
}
public byte[] MaskingKey {
get {
return _maskingKey;
}
}
public Opcode Opcode {
get {
return _opcode;
}
}
public PayloadData PayloadData {
get {
return _payloadData;
}
}
public byte PayloadLength {
get {
return _payloadLength;
}
}
public Rsv Rsv1 {
get {
return _rsv1;
}
}
public Rsv Rsv2 {
get {
return _rsv2;
}
}
public Rsv Rsv3 {
get {
return _rsv3;
}
}
#endregion
#region Private Methods
private static byte[] createMaskingKey ()
{
var key = new byte[4];
WebSocket.RandomNumber.GetBytes (key);
return key;
}
private static string dump (WebSocketFrame frame)
{
var len = frame.Length;
var cnt = (long) (len / 4);
var rem = (int) (len % 4);
int cntDigit;
string cntFmt;
if (cnt < 10000) {
cntDigit = 4;
cntFmt = "{0,4}";
}
else if (cnt < 0x010000) {
cntDigit = 4;
cntFmt = "{0,4:X}";
}
else if (cnt < 0x0100000000) {
cntDigit = 8;
cntFmt = "{0,8:X}";
}
else {
cntDigit = 16;
cntFmt = "{0,16:X}";
}
var spFmt = String.Format ("{{0,{0}}}", cntDigit);
var headerFmt = String.Format (@"
{0} 01234567 89ABCDEF 01234567 89ABCDEF
{0}+--------+--------+--------+--------+\n", spFmt);
var lineFmt = String.Format ("{0}|{{1,8}} {{2,8}} {{3,8}} {{4,8}}|\n", cntFmt);
var footerFmt = String.Format ("{0}+--------+--------+--------+--------+", spFmt);
var output = new StringBuilder (64);
Func<Action<string, string, string, string>> linePrinter = () => {
long lineCnt = 0;
return (arg1, arg2, arg3, arg4) =>
output.AppendFormat (lineFmt, ++lineCnt, arg1, arg2, arg3, arg4);
};
var printLine = linePrinter ();
output.AppendFormat (headerFmt, String.Empty);
var bytes = frame.ToArray ();
for (long i = 0; i <= cnt; i++) {
var j = i * 4;
if (i < cnt) {
printLine (
Convert.ToString (bytes[j], 2).PadLeft (8, '0'),
Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0'),
Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0'),
Convert.ToString (bytes[j + 3], 2).PadLeft (8, '0'));
continue;
}
if (rem > 0)
printLine (
Convert.ToString (bytes[j], 2).PadLeft (8, '0'),
rem >= 2 ? Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0') : String.Empty,
rem == 3 ? Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0') : String.Empty,
String.Empty);
}
output.AppendFormat (footerFmt, String.Empty);
return output.ToString ();
}
private static string print (WebSocketFrame frame)
{
// Payload Length
var payloadLen = frame._payloadLength;
// Extended Payload Length
var extPayloadLen = payloadLen > 125 ? frame.FullPayloadLength.ToString () : String.Empty;
// Masking Key
var maskingKey = BitConverter.ToString (frame._maskingKey);
// Payload Data
var payload = payloadLen == 0
? String.Empty
: payloadLen > 125
? "---"
: frame.IsText && !(frame.IsFragment || frame.IsMasked || frame.IsCompressed)
? frame._payloadData.ApplicationData.UTF8Decode ()
: frame._payloadData.ToString ();
var fmt = @"
FIN: {0}
RSV1: {1}
RSV2: {2}
RSV3: {3}
Opcode: {4}
MASK: {5}
Payload Length: {6}
Extended Payload Length: {7}
Masking Key: {8}
Payload Data: {9}";
return String.Format (
fmt,
frame._fin,
frame._rsv1,
frame._rsv2,
frame._rsv3,
frame._opcode,
frame._mask,
payloadLen,
extPayloadLen,
maskingKey,
payload);
}
private static WebSocketFrame processHeader (byte[] header)
{
if (header.Length != 2)
throw new WebSocketException ("The header of a frame cannot be read from the stream.");
// FIN
var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More;
// RSV1
var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off;
// RSV2
var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off;
// RSV3
var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off;
// Opcode
var opcode = (byte) (header[0] & 0x0f);
// MASK
var mask = (header[1] & 0x80) == 0x80 ? Mask.On : Mask.Off;
// Payload Length
var payloadLen = (byte) (header[1] & 0x7f);
var err = !opcode.IsSupported ()
? "An unsupported opcode."
: !opcode.IsData () && rsv1 == Rsv.On
? "A non data frame is compressed."
: opcode.IsControl () && fin == Fin.More
? "A control frame is fragmented."
: opcode.IsControl () && payloadLen > 125
? "A control frame has a long payload length."
: null;
if (err != null)
throw new WebSocketException (CloseStatusCode.ProtocolError, err);
var frame = new WebSocketFrame ();
frame._fin = fin;
frame._rsv1 = rsv1;
frame._rsv2 = rsv2;
frame._rsv3 = rsv3;
frame._opcode = (Opcode) opcode;
frame._mask = mask;
frame._payloadLength = payloadLen;
return frame;
}
private static WebSocketFrame readExtendedPayloadLength (Stream stream, WebSocketFrame frame)
{
var len = frame.ExtendedPayloadLengthCount;
if (len == 0) {
frame._extPayloadLength = WebSocket.EmptyBytes;
return frame;
}
var bytes = stream.ReadBytes (len);
if (bytes.Length != len)
throw new WebSocketException (
"The extended payload length of a frame cannot be read from the stream.");
frame._extPayloadLength = bytes;
return frame;
}
private static void readExtendedPayloadLengthAsync (
Stream stream,
WebSocketFrame frame,
Action<WebSocketFrame> completed,
Action<Exception> error)
{
var len = frame.ExtendedPayloadLengthCount;
if (len == 0) {
frame._extPayloadLength = WebSocket.EmptyBytes;
completed (frame);
return;
}
stream.ReadBytesAsync (
len,
bytes => {
if (bytes.Length != len)
throw new WebSocketException (
"The extended payload length of a frame cannot be read from the stream.");
frame._extPayloadLength = bytes;
completed (frame);
},
error);
}
private static WebSocketFrame readHeader (Stream stream)
{
return processHeader (stream.ReadBytes (2));
}
private static void readHeaderAsync (
Stream stream, Action<WebSocketFrame> completed, Action<Exception> error)
{
stream.ReadBytesAsync (2, bytes => completed (processHeader (bytes)), error);
}
private static WebSocketFrame readMaskingKey (Stream stream, WebSocketFrame frame)
{
var len = frame.IsMasked ? 4 : 0;
if (len == 0) {
frame._maskingKey = WebSocket.EmptyBytes;
return frame;
}
var bytes = stream.ReadBytes (len);
if (bytes.Length != len)
throw new WebSocketException ("The masking key of a frame cannot be read from the stream.");
frame._maskingKey = bytes;
return frame;
}
private static void readMaskingKeyAsync (
Stream stream,
WebSocketFrame frame,
Action<WebSocketFrame> completed,
Action<Exception> error)
{
var len = frame.IsMasked ? 4 : 0;
if (len == 0) {
frame._maskingKey = WebSocket.EmptyBytes;
completed (frame);
return;
}
stream.ReadBytesAsync (
len,
bytes => {
if (bytes.Length != len)
throw new WebSocketException (
"The masking key of a frame cannot be read from the stream.");
frame._maskingKey = bytes;
completed (frame);
},
error);
}
private static WebSocketFrame readPayloadData (Stream stream, WebSocketFrame frame)
{
var len = frame.FullPayloadLength;
if (len == 0) {
frame._payloadData = PayloadData.Empty;
return frame;
}
if (len > PayloadData.MaxLength)
throw new WebSocketException (CloseStatusCode.TooBig, "A frame has a long payload length.");
var llen = (long) len;
var bytes = frame._payloadLength < 127
? stream.ReadBytes ((int) len)
: stream.ReadBytes (llen, 1024);
if (bytes.LongLength != llen)
throw new WebSocketException (
"The payload data of a frame cannot be read from the stream.");
frame._payloadData = new PayloadData (bytes, llen);
return frame;
}
private static void readPayloadDataAsync (
Stream stream,
WebSocketFrame frame,
Action<WebSocketFrame> completed,
Action<Exception> error)
{
var len = frame.FullPayloadLength;
if (len == 0) {
frame._payloadData = PayloadData.Empty;
completed (frame);
return;
}
if (len > PayloadData.MaxLength)
throw new WebSocketException (CloseStatusCode.TooBig, "A frame has a long payload length.");
var llen = (long) len;
Action<byte[]> compl = bytes => {
if (bytes.LongLength != llen)
throw new WebSocketException (
"The payload data of a frame cannot be read from the stream.");
frame._payloadData = new PayloadData (bytes, llen);
completed (frame);
};
if (frame._payloadLength < 127) {
stream.ReadBytesAsync ((int) len, compl, error);
return;
}
stream.ReadBytesAsync (llen, 1024, compl, error);
}
#endregion
#region Internal Methods
internal static WebSocketFrame CreateCloseFrame (PayloadData payloadData, bool mask)
{
return new WebSocketFrame (Fin.Final, Opcode.Close, payloadData, false, mask);
}
internal static WebSocketFrame CreatePingFrame (bool mask)
{
return new WebSocketFrame (Fin.Final, Opcode.Ping, PayloadData.Empty, false, mask);
}
internal static WebSocketFrame CreatePingFrame (byte[] data, bool mask)
{
return new WebSocketFrame (Fin.Final, Opcode.Ping, new PayloadData (data), false, mask);
}
internal static WebSocketFrame ReadFrame (Stream stream, bool unmask)
{
var frame = readHeader (stream);
readExtendedPayloadLength (stream, frame);
readMaskingKey (stream, frame);
readPayloadData (stream, frame);
if (unmask)
frame.Unmask ();
return frame;
}
internal static void ReadFrameAsync (
Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error)
{
readHeaderAsync (
stream,
frame =>
readExtendedPayloadLengthAsync (
stream,
frame,
frame1 =>
readMaskingKeyAsync (
stream,
frame1,
frame2 =>
readPayloadDataAsync (
stream,
frame2,
frame3 => {
if (unmask)
frame3.Unmask ();
completed (frame3);
},
error),
error),
error),
error);
}
internal void Unmask ()
{
if (_mask == Mask.Off)
return;
_mask = Mask.Off;
_payloadData.Mask (_maskingKey);
_maskingKey = WebSocket.EmptyBytes;
}
#endregion
#region Public Methods
public IEnumerator<byte> GetEnumerator ()
{
foreach (var b in ToArray ())
yield return b;
}
public void Print (bool dumped)
{
Console.WriteLine (dumped ? dump (this) : print (this));
}
public string PrintToString (bool dumped)
{
return dumped ? dump (this) : print (this);
}
public byte[] ToArray ()
{
using (var buff = new MemoryStream ()) {
var header = (int) _fin;
header = (header << 1) + (int) _rsv1;
header = (header << 1) + (int) _rsv2;
header = (header << 1) + (int) _rsv3;
header = (header << 4) + (int) _opcode;
header = (header << 1) + (int) _mask;
header = (header << 7) + (int) _payloadLength;
buff.Write (((ushort) header).InternalToByteArray (ByteOrder.Big), 0, 2);
if (_payloadLength > 125)
buff.Write (_extPayloadLength, 0, _payloadLength == 126 ? 2 : 8);
if (_mask == Mask.On)
buff.Write (_maskingKey, 0, 4);
if (_payloadLength > 0) {
var bytes = _payloadData.ToArray ();
if (_payloadLength < 127)
buff.Write (bytes, 0, bytes.Length);
else
buff.WriteBytes (bytes, 1024);
}
buff.Close ();
return buff.ToArray ();
}
}
public override string ToString ()
{
return BitConverter.ToString (ToArray ());
}
#endregion
#region Explicit Interface Implementations
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
}
}
#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.
/*============================================================
**
** Purpose: Unsafe code that uses pointers should use
** SafePointer to fix subtle lifetime problems with the
** underlying resource.
**
===========================================================*/
// Design points:
// *) Avoid handle-recycling problems (including ones triggered via
// resurrection attacks) for all accesses via pointers. This requires tying
// together the lifetime of the unmanaged resource with the code that reads
// from that resource, in a package that uses synchronization to enforce
// the correct semantics during finalization. We're using SafeHandle's
// ref count as a gate on whether the pointer can be dereferenced because that
// controls the lifetime of the resource.
//
// *) Keep the penalties for using this class small, both in terms of space
// and time. Having multiple threads reading from a memory mapped file
// will already require 2 additional interlocked operations. If we add in
// a "current position" concept, that requires additional space in memory and
// synchronization. Since the position in memory is often (but not always)
// something that can be stored on the stack, we can save some memory by
// excluding it from this object. However, avoiding the need for
// synchronization is a more significant win. This design allows multiple
// threads to read and write memory simultaneously without locks (as long as
// you don't write to a region of memory that overlaps with what another
// thread is accessing).
//
// *) Space-wise, we use the following memory, including SafeHandle's fields:
// Object Header MT* handle int bool bool <2 pad bytes> length
// On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes.
// (We can safe 4 bytes on x86 only by shrinking SafeHandle)
//
// *) Wrapping a SafeHandle would have been a nice solution, but without an
// ordering between critical finalizable objects, it would have required
// changes to each SafeHandle subclass to opt in to being usable from a
// SafeBuffer (or some clever exposure of SafeHandle's state fields and a
// way of forcing ReleaseHandle to run even after the SafeHandle has been
// finalized with a ref count > 1). We can use less memory and create fewer
// objects by simply inserting a SafeBuffer into the class hierarchy.
//
// *) In an ideal world, we could get marshaling support for SafeBuffer that
// would allow us to annotate a P/Invoke declaration, saying this parameter
// specifies the length of the buffer, and the units of that length are X.
// P/Invoke would then pass that size parameter to SafeBuffer.
// [DllImport(...)]
// static extern SafeMemoryHandle AllocCharBuffer(int numChars);
// If we could put an attribute on the SafeMemoryHandle saying numChars is
// the element length, and it must be multiplied by 2 to get to the byte
// length, we can simplify the usage model for SafeBuffer.
//
// *) This class could benefit from a constraint saying T is a value type
// containing no GC references.
// Implementation notes:
// *) The Initialize method must be called before you use any instance of
// a SafeBuffer. To avoid race conditions when storing SafeBuffers in statics,
// you either need to take a lock when publishing the SafeBuffer, or you
// need to create a local, initialize the SafeBuffer, then assign to the
// static variable (perhaps using Interlocked.CompareExchange). Of course,
// assignments in a static class constructor are under a lock implicitly.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.Runtime.InteropServices
{
public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
// Steal UIntPtr.MaxValue as our uninitialized value.
private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ?
((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue);
private UIntPtr _numBytes;
protected SafeBuffer(bool ownsHandle) : base(ownsHandle)
{
_numBytes = Uninitialized;
}
/// <summary>
/// Specifies the size of the region of memory, in bytes. Must be
/// called before using the SafeBuffer.
/// </summary>
/// <param name="numBytes">Number of valid bytes in memory.</param>
[CLSCompliant(false)]
public void Initialize(ulong numBytes)
{
if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace);
if (numBytes >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax);
_numBytes = (UIntPtr)numBytes;
}
/// <summary>
/// Specifies the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
public void Initialize(uint numElements, uint sizeOfEachElement)
{
if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
_numBytes = checked((UIntPtr)(numElements * sizeOfEachElement));
}
/// <summary>
/// Specifies the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
public void Initialize<T>(uint numElements) where T : struct
{
Initialize(numElements, Marshal.AlignedSizeOf<T>());
}
// Callers should ensure that they check whether the pointer ref param
// is null when AcquirePointer returns. If it is not null, they must
// call ReleasePointer in a CER. This method calls DangerousAddRef
// & exposes the pointer. Unlike Read, it does not alter the "current
// position" of the pointer. Here's how to use it:
//
// byte* pointer = null;
// RuntimeHelpers.PrepareConstrainedRegions();
// try {
// safeBuffer.AcquirePointer(ref pointer);
// // Use pointer here, with your own bounds checking
// }
// finally {
// if (pointer != null)
// safeBuffer.ReleasePointer();
// }
//
// Note: If you cast this byte* to a T*, you have to worry about
// whether your pointer is aligned. Additionally, you must take
// responsibility for all bounds checking with this pointer.
/// <summary>
/// Obtain the pointer from a SafeBuffer for a block of code,
/// with the express responsibility for bounds checking and calling
/// ReleasePointer later within a CER to ensure the pointer can be
/// freed later. This method either completes successfully or
/// throws an exception and returns with pointer set to null.
/// </summary>
/// <param name="pointer">A byte*, passed by reference, to receive
/// the pointer from within the SafeBuffer. You must set
/// pointer to null before calling this method.</param>
[CLSCompliant(false)]
public void AcquirePointer(ref byte* pointer)
{
if (_numBytes == Uninitialized)
throw NotInitialized();
pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
bool junk = false;
DangerousAddRef(ref junk);
pointer = (byte*)handle;
}
public void ReleasePointer()
{
if (_numBytes == Uninitialized)
throw NotInitialized();
DangerousRelease();
}
/// <summary>
/// Read a value type from memory at the given offset. This is
/// equivalent to: return *(T*)(bytePtr + byteOffset);
/// </summary>
/// <typeparam name="T">The value type to read</typeparam>
/// <param name="byteOffset">Where to start reading from memory. You
/// may have to consider alignment.</param>
/// <returns>An instance of T read from memory.</returns>
[CLSCompliant(false)]
public T Read<T>(ulong byteOffset) where T : struct
{
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);
// return *(T*) (_ptr + byteOffset);
T value;
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
GenericPtrToStructure<T>(ptr, out value, sizeofT);
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
return value;
}
[CLSCompliant(false)]
public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
if (array == null)
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
uint alignedSizeofT = Marshal.AlignedSizeOf<T>();
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
for (int i = 0; i < count; i++)
unsafe { GenericPtrToStructure<T>(ptr + alignedSizeofT * i, out array[i + index], sizeofT); }
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
/// <summary>
/// Write a value type to memory at the given offset. This is
/// equivalent to: *(T*)(bytePtr + byteOffset) = value;
/// </summary>
/// <typeparam name="T">The type of the value type to write to memory.</typeparam>
/// <param name="byteOffset">The location in memory to write to. You
/// may have to consider alignment.</param>
/// <param name="value">The value type to write to memory.</param>
[CLSCompliant(false)]
public void Write<T>(ulong byteOffset, T value) where T : struct
{
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);
// *((T*) (_ptr + byteOffset)) = value;
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
GenericStructureToPtr(ref value, ptr, sizeofT);
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
[CLSCompliant(false)]
public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
if (array == null)
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
uint alignedSizeofT = Marshal.AlignedSizeOf<T>();
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
for (int i = 0; i < count; i++)
unsafe { GenericStructureToPtr(ref array[i + index], ptr + alignedSizeofT * i, sizeofT); }
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
/// <summary>
/// Returns the number of bytes in the memory region.
/// </summary>
[CLSCompliant(false)]
public ulong ByteLength
{
get
{
if (_numBytes == Uninitialized)
throw NotInitialized();
return (ulong)_numBytes;
}
}
/* No indexer. The perf would be misleadingly bad. People should use
* AcquirePointer and ReleasePointer instead. */
private void SpaceCheck(byte* ptr, ulong sizeInBytes)
{
if ((ulong)_numBytes < sizeInBytes)
NotEnoughRoom();
if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes)
NotEnoughRoom();
}
private static void NotEnoughRoom()
{
throw new ArgumentException(SR.Arg_BufferTooSmall);
}
private static InvalidOperationException NotInitialized()
{
return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize);
}
// FCALL limitations mean we can't have generic FCALL methods. However, we can pass
// TypedReferences to FCALL methods.
internal static void GenericPtrToStructure<T>(byte* ptr, out T structure, uint sizeofT) where T : struct
{
structure = default(T); // Dummy assignment to silence the compiler
PtrToStructureNative(ptr, __makeref(structure), sizeofT);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void PtrToStructureNative(byte* ptr, /*out T*/ TypedReference structure, uint sizeofT);
internal static void GenericStructureToPtr<T>(ref T structure, byte* ptr, uint sizeofT) where T : struct
{
StructureToPtrNative(__makeref(structure), ptr, sizeofT);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void StructureToPtrNative(/*ref T*/ TypedReference structure, byte* ptr, uint sizeofT);
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
using Eto.Mac.Drawing;
using System.Linq;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
using nnint = System.nint;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
using nnint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
using nnint = System.Int32;
#endif
#endif
namespace Eto.Mac.Forms.Controls
{
public class NumericUpDownHandler : MacView<NSView, NumericUpDown, NumericUpDown.ICallback>, NumericUpDown.IHandler
{
readonly NSTextField text;
readonly NSStepper stepper;
Size? naturalSize;
public override NSView ContainerControl { get { return Control; } }
public override NSView FocusControl { get { return text; } }
public NSTextField TextField { get { return text; } }
public NSStepper Stepper { get { return stepper; } }
public class EtoTextField : NSTextField, IMacControl
{
public WeakReference WeakHandler { get; set; }
}
class EtoNumericUpDownView : NSView, IMacControl
{
public WeakReference WeakHandler { get; set; }
public override void SetFrameSize(CGSize newSize)
{
base.SetFrameSize(newSize);
var views = Subviews;
var text = views[0];
var splitter = views[1];
var offset = (newSize.Height - text.Frame.Height) / 2;
text.SetFrameOrigin(new CGPoint(0, offset));
text.SetFrameSize(new CGSize((float)(newSize.Width - splitter.Frame.Width), (float)text.Frame.Height));
offset = (newSize.Height - splitter.Frame.Height) / 2;
splitter.SetFrameOrigin(new CGPoint(newSize.Width - splitter.Frame.Width, offset));
}
}
class EtoStepper : NSStepper
{
public override bool AcceptsFirstResponder()
{
return false;
}
}
public override object EventObject
{
get { return text; }
}
public static NSNumberFormatter DefaultFormatter = new NSNumberFormatter
{
NumberStyle = NSNumberFormatterStyle.Decimal,
Lenient = true,
UsesGroupingSeparator = false,
MinimumFractionDigits = 0,
MaximumFractionDigits = 0
};
public NumericUpDownHandler()
{
this.Control = new EtoNumericUpDownView
{
WeakHandler = new WeakReference(this),
AutoresizesSubviews = false
};
text = new EtoTextField
{
WeakHandler = new WeakReference(this),
Bezeled = true,
Editable = true,
Formatter = DefaultFormatter
};
text.Changed += HandleTextChanged;
stepper = new EtoStepper();
stepper.Activated += HandleStepperActivated;
stepper.MinValue = double.NegativeInfinity;
stepper.MaxValue = double.PositiveInfinity;
text.DoubleValue = stepper.DoubleValue = 0;
Control.AddSubview(text);
Control.AddSubview(stepper);
}
static void HandleStepperActivated(object sender, EventArgs e)
{
var handler = GetHandler(((NSView)sender).Superview) as NumericUpDownHandler;
if (handler != null)
{
var val = handler.stepper.DoubleValue;
if (Math.Abs(val) < 1E-10)
{
handler.text.IntValue = 0;
}
else
{
handler.text.DoubleValue = handler.stepper.DoubleValue;
}
handler.Callback.OnValueChanged(handler.Widget, EventArgs.Empty);
}
}
static void HandleTextChanged(object sender, EventArgs e)
{
var handler = GetHandler(((NSView)((NSNotification)sender).Object).Superview) as NumericUpDownHandler;
if (handler != null)
{
var formatter = (NSNumberFormatter)handler.text.Formatter;
var str = handler.GetStringValue();
var number = formatter.NumberFromString(str);
if (number != null && number.DoubleValue >= handler.MinValue && number.DoubleValue <= handler.MaxValue)
{
handler.stepper.DoubleValue = number.DoubleValue;
handler.Callback.OnValueChanged(handler.Widget, EventArgs.Empty);
}
}
}
string GetStringValue()
{
var currentEditor = text.CurrentEditor;
if (currentEditor != null)
return currentEditor.Value;
return text.StringValue;
}
protected override void Initialize()
{
base.Initialize();
var size = GetNaturalSize(Size.MaxValue);
Control.Frame = new CGRect(0, 0, size.Width, size.Height);
HandleEvent(Eto.Forms.Control.KeyDownEvent);
Widget.LostFocus += (sender, e) =>
{
var value = text.DoubleValue;
var newValue = Math.Max(MinValue, Math.Min(MaxValue, text.DoubleValue));
if (Math.Abs(value - newValue) > double.Epsilon || string.IsNullOrEmpty(text.StringValue))
{
text.DoubleValue = newValue;
Callback.OnValueChanged(Widget, EventArgs.Empty);
}
};
Widget.TextInput += (sender, e) =>
{
var formatter = (NSNumberFormatter)text.Formatter;
if (e.Text == ".")
{
var str = GetStringValue();
e.Cancel = str.Contains(formatter.DecimalSeparator);
var editor = text.CurrentEditor;
if (editor != null && editor.SelectedRange.Length > 0)
{
var sub = str.Substring((int)editor.SelectedRange.Location, (int)editor.SelectedRange.Length);
e.Cancel &= !sub.Contains(formatter.DecimalSeparator);
}
}
else
e.Cancel = !e.Text.All(r =>
{
if (Char.IsDigit(r))
return true;
var str = r.ToString();
return
(formatter.MaximumFractionDigits > 0 && str == formatter.DecimalSeparator)
|| (formatter.UsesGroupingSeparator && str == formatter.GroupingSeparator)
|| (MinValue < 0 && (str == formatter.NegativePrefix || str == formatter.NegativeSuffix))
|| (MaxValue > 0 && (str == formatter.PositivePrefix || str == formatter.PositiveSuffix));
});
};
}
public override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Handled)
return;
if (e.KeyData == Keys.Down)
{
var val = Value;
var newval = Math.Max(val - Increment, MinValue);
if (newval < val)
{
Value = newval;
}
e.Handled = true;
}
else if (e.KeyData == Keys.Up)
{
var val = Value;
var newval = Math.Min(val + Increment, MaxValue);
if (newval > val)
{
Value = newval;
}
e.Handled = true;
}
}
protected override SizeF GetNaturalSize(SizeF availableSize)
{
if (naturalSize == null)
{
text.SizeToFit();
stepper.SizeToFit();
var naturalHeight = Math.Max(text.Frame.Height, stepper.Frame.Height);
naturalSize = new Size(80, (int)naturalHeight);
}
return naturalSize.Value;
}
public bool ReadOnly
{
get { return text.Enabled; }
set
{
text.Enabled = value;
stepper.Enabled = value;
}
}
public double Value
{
get
{
var str = GetStringValue();
var val = ((NSNumberFormatter)text.Formatter).NumberFromString(str);
return val != null ? Math.Round(Math.Max(MinValue, Math.Min(MaxValue, val.DoubleValue)), DecimalPlaces) : 0;
}
set
{
SetValue(value, Value);
}
}
void SetValue(double value, double oldValue)
{
var val = Math.Max(MinValue, Math.Min(MaxValue, value));
if (Math.Abs(oldValue - val) > double.Epsilon)
{
if (Math.Abs(val) < 1E-10)
{
stepper.IntValue = text.IntValue = 0;
}
else
{
stepper.DoubleValue = text.DoubleValue = val;
}
Callback.OnValueChanged(Widget, EventArgs.Empty);
}
}
public double MinValue
{
get { return stepper.MinValue; }
set
{
var oldValue = Value;
stepper.MinValue = value;
SetValue(Value, oldValue);
}
}
public double MaxValue
{
get { return stepper.MaxValue; }
set
{
var oldValue = Value;
stepper.MaxValue = value;
SetValue(Value, oldValue);
}
}
public override bool Enabled
{
get { return stepper.Enabled; }
set
{
stepper.Enabled = value;
text.Enabled = value;
}
}
static readonly object Font_Key = new object();
public Font Font
{
get { return Widget.Properties.Create(Font_Key, () =>text.Font.ToEto()); }
set
{
Widget.Properties.Set(Font_Key, value, () =>
{
text.Font = value.ToNSFont();
text.SizeToFit();
LayoutIfNeeded();
});
}
}
public double Increment
{
get { return stepper.Increment; }
set { stepper.Increment = value; }
}
static readonly object DecimalPlaces_Key = new object();
public int DecimalPlaces
{
get { return Widget.Properties.Get<int>(DecimalPlaces_Key); }
set
{
Widget.Properties.Set(DecimalPlaces_Key, value, () =>
{
var formatter = new NSNumberFormatter
{
NumberStyle = NSNumberFormatterStyle.Decimal,
Lenient = true,
UsesGroupingSeparator = false,
MinimumFractionDigits = (nnint)value,
MaximumFractionDigits = (nnint)value
};
text.Formatter = formatter;
});
}
}
public Color TextColor
{
get { return text.TextColor.ToEto(); }
set { text.TextColor = value.ToNSUI(); }
}
protected override void SetBackgroundColor(Color? color)
{
if (color != null)
text.BackgroundColor = color.Value.ToNSUI();
}
static readonly object CustomFieldEditorKey = new object();
public override NSObject CustomFieldEditor { get { return Widget.Properties.Get<NSObject>(CustomFieldEditorKey); } }
public void SetCustomFieldEditor()
{
if (CustomFieldEditor != null)
return;
Widget.Properties[CustomFieldEditorKey] = new CustomTextFieldEditor
{
WeakHandler = new WeakReference(this)
};
}
static readonly IntPtr selResignFirstResponder = Selector.GetHandle("resignFirstResponder");
static readonly IntPtr selInsertText = Selector.GetHandle("insertText:");
public override void AttachEvent(string id)
{
switch (id)
{
case Eto.Forms.Control.TextInputEvent:
SetCustomFieldEditor();
AddMethod(selInsertText, new Action<IntPtr, IntPtr, IntPtr>(TriggerTextInput), "v@:@", CustomFieldEditor);
break;
case Eto.Forms.Control.LostFocusEvent:
SetCustomFieldEditor();
// lost focus is on the custom field editor, not on the control itself (it loses focus immediately due to the field editor)
AddMethod(selResignFirstResponder, new Func<IntPtr, IntPtr, bool>(TriggerLostFocus), "B@:", CustomFieldEditor);
break;
default:
base.AttachEvent(id);
break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using AsmResolver.Collections;
using AsmResolver.DotNet.Collections;
using AsmResolver.PE.DotNet.Metadata;
using AsmResolver.PE.DotNet.Metadata.Strings;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet.Serialized
{
/// <summary>
/// Represents a lazily initialized implementation of <see cref="TypeDefinition"/> that is read from a
/// .NET metadata image.
/// </summary>
public class SerializedTypeDefinition : TypeDefinition
{
private readonly ModuleReaderContext _context;
private readonly TypeDefinitionRow _row;
/// <summary>
/// Creates a type definition from a type metadata row.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="token">The token to initialize the type for.</param>
/// <param name="row">The metadata table row to base the type definition on.</param>
public SerializedTypeDefinition(ModuleReaderContext context, MetadataToken token, in TypeDefinitionRow row)
: base(token)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_row = row;
Attributes = row.Attributes;
((IOwnedCollectionElement<ModuleDefinition>) this).Owner = context.ParentModule;
}
/// <inheritdoc />
protected override Utf8String? GetNamespace()
{
return _context.Metadata.TryGetStream<StringsStream>(out var stringsStream)
? stringsStream.GetStringByIndex(_row.Namespace)
: null;
}
/// <inheritdoc />
protected override Utf8String? GetName()
{
return _context.Metadata.TryGetStream<StringsStream>(out var stringsStream)
? stringsStream.GetStringByIndex(_row.Name)
: null;
}
/// <inheritdoc />
protected override ITypeDefOrRef? GetBaseType()
{
if (_row.Extends == 0)
return null;
var token = _context.Metadata
.GetStream<TablesStream>()
.GetIndexEncoder(CodedIndex.TypeDefOrRef)
.DecodeIndex(_row.Extends);
return (ITypeDefOrRef) _context.ParentModule.LookupMember(token);
}
/// <inheritdoc />
protected override IList<TypeDefinition> GetNestedTypes()
{
var result = new OwnedCollection<TypeDefinition, TypeDefinition>(this);
var rids = _context.ParentModule.GetNestedTypeRids(MetadataToken.Rid);
foreach (uint rid in rids)
{
var nestedType = (TypeDefinition) _context.ParentModule.LookupMember(new MetadataToken(TableIndex.TypeDef, rid));
result.Add(nestedType);
}
return result;
}
/// <inheritdoc />
protected override TypeDefinition? GetDeclaringType()
{
uint parentTypeRid = _context.ParentModule.GetParentTypeRid(MetadataToken.Rid);
return _context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.TypeDef, parentTypeRid), out var member)
? member as TypeDefinition
: null;
}
/// <inheritdoc />
protected override IList<FieldDefinition> GetFields() =>
CreateMemberCollection<FieldDefinition>(_context.ParentModule.GetFieldRange(MetadataToken.Rid));
/// <inheritdoc />
protected override IList<MethodDefinition> GetMethods() =>
CreateMemberCollection<MethodDefinition>(_context.ParentModule.GetMethodRange(MetadataToken.Rid));
/// <inheritdoc />
protected override IList<PropertyDefinition> GetProperties() =>
CreateMemberCollection<PropertyDefinition>(_context.ParentModule.GetPropertyRange(MetadataToken.Rid));
/// <inheritdoc />
protected override IList<EventDefinition> GetEvents() =>
CreateMemberCollection<EventDefinition>(_context.ParentModule.GetEventRange(MetadataToken.Rid));
private IList<TMember> CreateMemberCollection<TMember>(MetadataRange range)
where TMember : class, IMetadataMember, IOwnedCollectionElement<TypeDefinition>
{
var result = new OwnedCollection<TypeDefinition, TMember>(this);
foreach (var token in range)
result.Add((TMember) _context.ParentModule.LookupMember(token));
return result;
}
/// <inheritdoc />
protected override IList<CustomAttribute> GetCustomAttributes() =>
_context.ParentModule.GetCustomAttributeCollection(this);
/// <inheritdoc />
protected override IList<SecurityDeclaration> GetSecurityDeclarations() =>
_context.ParentModule.GetSecurityDeclarationCollection(this);
/// <inheritdoc />
protected override IList<GenericParameter> GetGenericParameters()
{
var result = new OwnedCollection<IHasGenericParameters, GenericParameter>(this);
foreach (uint rid in _context.ParentModule.GetGenericParameters(MetadataToken))
{
if (_context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.GenericParam, rid), out var member)
&& member is GenericParameter genericParameter)
{
result.Add(genericParameter);
}
}
return result;
}
/// <inheritdoc />
protected override IList<InterfaceImplementation> GetInterfaces()
{
var result = new OwnedCollection<TypeDefinition, InterfaceImplementation>(this);
var rids = _context.ParentModule.GetInterfaceImplementationRids(MetadataToken);
foreach (uint rid in rids)
{
if (_context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.InterfaceImpl, rid), out var member)
&& member is InterfaceImplementation type)
{
result.Add(type);
}
}
return result;
}
/// <inheritdoc />
protected override IList<MethodImplementation> GetMethodImplementations()
{
var result = new List<MethodImplementation>();
var tablesStream = _context.Metadata.GetStream<TablesStream>();
var table = tablesStream.GetTable<MethodImplementationRow>(TableIndex.MethodImpl);
var encoder = tablesStream.GetIndexEncoder(CodedIndex.MethodDefOrRef);
var rids = _context.ParentModule.GetMethodImplementationRids(MetadataToken);
foreach (uint rid in rids)
{
var row = table.GetByRid(rid);
_context.ParentModule.TryLookupMember(encoder.DecodeIndex(row.MethodBody), out var body);
_context.ParentModule.TryLookupMember(encoder.DecodeIndex(row.MethodDeclaration), out var declaration);
result.Add(new MethodImplementation(
declaration as IMethodDefOrRef,
body as IMethodDefOrRef));
}
return result;
}
/// <inheritdoc />
protected override ClassLayout? GetClassLayout()
{
uint rid = _context.ParentModule.GetClassLayoutRid(MetadataToken);
if (_context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.ClassLayout, rid), out var member)
&& member is ClassLayout layout)
{
layout.Parent = this;
return layout;
}
return null;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using SIL.PlatformUtilities;
using SIL.Scripture;
using SIL.Extensions;
namespace SIL.Windows.Forms.Scripture
{
/// <summary>
/// Control that allows the specifying of a book, chapter and verse
/// in the same style as Paratext.
/// </summary>
public partial class VerseControl : UserControl
{
#region Fields and Constructors
private const FontStyle searchTextStyle = FontStyle.Bold;
const int AbbreviationLength = 3; // length of book abbreviation
BookSet booksPresentSet = new BookSet();
string abbreviations = "";
string searchText = "";
bool allowVerseSegments = true; //Allow LXX style lettered verse segments
bool showEmptyBooks = true;
VerseRef curRef;
float abbreviationWidth = -1.0f; //starting width of book abbreviation, <0 signifies to recalculate
readonly BookListItem[] allBooks;
Font emptyBooksFont = SystemFonts.DefaultFont;
Color emptyBooksColor = SystemColors.GrayText;
bool advanceToEnd;
/// <summary>Function that can be set to allow the control to get localized names for the books.</summary>
public Func<string, string> GetLocalizedBookName = Canon.BookIdToEnglishName;
// change events
/// <summary>Fired when the reference is changed</summary>
public event PropertyChangedEventHandler VerseRefChanged;
/// <summary>Fired when the books listed in the control change</summary>
public event PropertyChangedEventHandler BooksPresentChanged;
/// <summary>Fired when the versification is changed</summary>
public event PropertyChangedEventHandler VersificationChanged;
/// <summary>Fired when an invalid book is entered</summary>
public event EventHandler InvalidBookEntered;
/// <summary>Fired when any part of the reference is invalid</summary>
public event EventHandler InvalidReferenceEntered;
/// <summary>Fired when any textbox for the reference gets focus</summary>
public event EventHandler TextBoxGotFocus;
// Used to temporarily ignore changes in the index of the book control
// when it is being updated internally
bool isUpdating;
public VerseControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
if (Platform.IsLinux)
{
// Set a smaller font on Linux. (Stops 'J''s being clipped)
uiBook.Font = new Font("Segoe UI", 8F, FontStyle.Regular, GraphicsUnit.Point, 0);
// Also increase the ItemHeight as to stop clipping of items in the drop down menu..
uiBook.ItemHeight += 2;
}
// Create reference and set to English versification
curRef = new VerseRef(ScrVers.English);
// Add books...
allBooks = new BookListItem[Canon.LastBook];
InitializeBooks(); //...to internal data structure
PopulateBooks(); //...and to combobox list
uiBook.GotFocus += control_GotFocus;
uiChapter.GotFocus += control_GotFocus;
uiVerse.GotFocus += control_GotFocus;
// Cause Drop down list to be initally populated.
// (stop intial click on Combo box drop down beinging ignored on mono)
// TODO: fix mono bug where dropdown isn't shown if list is empty even
// if dropdown event handlers populate list.
if (Platform.IsMono)
uiBook.BeforeMouseDown += (sender, e) =>
{
if (uiBook.Items.Count == 0) PopulateBooks();
};
}
#endregion
#region Helpers and Initializers
void InitializeBooks()
{
int i = 0;
StringBuilder abbrevs = new StringBuilder();
foreach (string abbrev in Canon.AllBookIds)
{
abbrevs.Append(abbrev);
abbrevs.Append(",");
BookListItem item = new BookListItem(abbrev);
item.isPresent = booksPresentSet.IsSelected(i + Canon.FirstBook);
allBooks[i] = item;
i++;
}
abbreviations = abbrevs.ToString();
RelocalizeBooks();
}
private void RelocalizeBooks()
{
foreach (BookListItem item in allBooks)
{
item.Name = GetLocalizedBookName(item.Abbreviation);
item.BaseName = item.Name.ToUpperInvariant().RemoveDiacritics();
}
}
void PopulateBooks()
{
Unfilter();
}
#endregion
#region Properties
[Browsable(true)]
public bool AllowVerseSegments
{
get { return allowVerseSegments; }
set
{
if (allowVerseSegments == value)
return; //no op
//FUTURE: if (!value) //turning off segments, remove segment portion, fire event if change ref
allowVerseSegments = value;
}
}
bool VerseSegmentsAvailable
{
get { return curRef.Versification != null && curRef.Versification.HasVerseSegments; }
}
/// <summary>
/// Gets or sets the current verse reference
/// NOTES ON VERSE SEGMENT HANDLING:
/// April 2009. We're adding segmented verse handling late in the PT7 development cycle. PT-1876.
/// The goal is to give the functionality to SLT users while minimizing chance of breakage elsewhere.
/// So, even though the right place for some of this logic is probably in VerseRef, for PT7 we'll keep it
/// here and offer this extra property that segment-aware tools can check.
///
/// Basic design:
/// 1. VerseControl now has a property AllowVerseSegments that turns on segment aware behavior.
/// 2. Phase 1 implementation: allow setting a segmented verse ref to the control and inputting
/// segments in the verse field. VerseRef property may now return segmented verses.
/// 3. Phase 2: allow prev/next verse to be segment aware. Support in LXX edit window.
/// </summary>
[Browsable(false), ReadOnly(true)]
public VerseRef VerseRef
{
get
{
// FB 21930 partially entered data could be in control, so need to call AcceptData before
// returning verse
try
{
// In tests, the handle may not be created. Attempting to check for updated data can cause
// a SendMessage, which can result in a hang.
if (IsHandleCreated && !InvokeRequired)
AcceptData();
}
catch (Exception)
{
// ignore errors at this point
}
// old way, before segmented references allowed
// return new VerseRef(curRef).Simplify();
return new VerseRef(curRef).UnBridge();
}
set
{
// We really can't use Valid here because it checks for maximum book number
// and that is depenedent on the versification and when the versification of
// the control and the text are different we can end up ignoring values
// that are in fact ok. So we just check for empty references and bail out
// if we get one.
if (value.BookNum < 1 || value.ChapterNum < 1 || value.VerseNum < 0)
{
Trace.TraceWarning("Invalid VerseRef passed to VerseControl: " + value);
// Ignore it for now (see PT-1310)
return;
}
curRef.CopyFrom(value);
if (!allowVerseSegments)
curRef.Simplify();
if (advanceToEnd)
AdvanceToLastSegment(curRef);
UpdateControls();
}
}
[Browsable(false)]
private string BookAbbreviation
{
get { return curRef.Book; }
}
[Browsable(false), ReadOnly(true)]
public ScrVers Versification
{
set
{
if (curRef.Versification == value)
return;
curRef.Versification = value;
OnVersificationChanged(new PropertyChangedEventArgs("Versification"));
}
}
[Browsable(false), ReadOnly(true)]
public BookSet BooksPresentSet
{
set
{
booksPresentSet = value;
OnBooksPresentChanged(new PropertyChangedEventArgs("BooksPresent"));
}
}
public Font EmptyBooksFont
{
get { return emptyBooksFont; }
set
{
if (Equals(value, emptyBooksFont))
return;
emptyBooksFont = value ?? SystemFonts.DefaultFont;
abbreviationWidth = -1.0f;
}
}
public Color EmptyBooksColor
{
get { return emptyBooksColor; }
set { emptyBooksColor = value; }
}
public bool ShowEmptyBooks
{
get { return showEmptyBooks; }
set
{
if (showEmptyBooks == value) return;
showEmptyBooks = value;
PopulateBooks();
}
}
/// <summary>
/// When using a verse control to indicate the end of a range, chosing
/// a new books should go to the last verse of the last chapter. Chosing
/// a new chapter should go to the last verse of that chapter.
/// </summary>
public bool AdvanceToEnd
{
get { return advanceToEnd; }
set { advanceToEnd = value; }
}
#endregion
#region Internal Updating Methods
/// <summary>
/// (Call whenever reference has been changed internally.) Update contents of controls.
/// </summary>
void UpdateControls()
{
try
{
isUpdating = true;
uiBook.Text = curRef.Book;
// does Book=0 have any meaning now? With new VerseRef class, how access intro material?
uiChapter.Text = curRef.Chapter;
uiVerse.Text = allowVerseSegments && VerseSegmentsAvailable ? curRef.UnBridge().Verse : curRef.VerseNum.ToString();
}
finally
{
isUpdating = false;
}
}
/// <summary>
/// Call whenever controls have changed to keep internal reference in sync with UI.
/// </summary>
void UpdateReference()
{
UpdateControls(); // Many controls change themselves by changing internal reference. Nice and clean.
OnVerseRefChanged(new PropertyChangedEventArgs("VerseRef"));
}
#endregion
#region API Methods
/// <summary>
/// Move cursor to book field and select all text within it.
/// </summary>
public void GotoBookField()
{
uiBook.Focus();
uiBook.SelectAll();
}
/// <summary>
/// Tries to move to Chapter 1 verse 1 of the previous book.
/// </summary>
/// <returns>true if the move was possible</returns>
public void PrevBook()
{
bool result = (showEmptyBooks) ? curRef.PreviousBook() : curRef.PreviousBook(booksPresentSet);
if (result)
UpdateReference();
}
public void NextBook()
{
bool result = (showEmptyBooks) ? curRef.NextBook() : curRef.NextBook(booksPresentSet);
if (result)
UpdateReference();
}
public void PrevChapter()
{
bool result = (showEmptyBooks) ? curRef.PreviousChapter() : curRef.PreviousChapter(booksPresentSet);
if (result)
UpdateReference();
}
public void NextChapter()
{
bool result = (showEmptyBooks) ? curRef.NextChapter() : curRef.NextChapter(booksPresentSet);
if (result)
UpdateReference();
}
public void PrevVerse()
{
bool result = (showEmptyBooks) ? curRef.PreviousVerse() : curRef.PreviousVerse(booksPresentSet);
if (result)
UpdateReference();
}
public void NextVerse()
{
bool result = (showEmptyBooks) ? curRef.NextVerse() : curRef.NextVerse(booksPresentSet);
if (result)
UpdateReference();
}
#endregion
#region Control Event Methods
/// <summary>
/// Fires a VerseRefChangedEvent
/// </summary>
private void OnVerseRefChanged(PropertyChangedEventArgs e)
{
if (VerseRefChanged != null)
VerseRefChanged(this, e);
}
private void OnBooksPresentChanged(PropertyChangedEventArgs e)
{
InitializeBooks();
if (BooksPresentChanged != null)
BooksPresentChanged(this, e);
}
private void OnVersificationChanged(PropertyChangedEventArgs e)
{
if (VersificationChanged != null)
VersificationChanged(this, e);
}
private void OnInvalidBook(EventArgs e)
{
if (InvalidBookEntered != null)
InvalidBookEntered(this, e);
}
private void OnInvalidReference()
{
if (InvalidReferenceEntered != null)
InvalidReferenceEntered(this, EventArgs.Empty);
}
private void OnTextBoxGotFocus()
{
if (TextBoxGotFocus != null)
TextBoxGotFocus(this, EventArgs.Empty);
}
#endregion
#region Book Owner Draw
void uiBook_FontChanged(object sender, EventArgs e)
{
abbreviationWidth = -1.0f; //signal to recalculate default width for book
}
//move to events section after debugging nov2007
void uiBook_DropDown(object sender, EventArgs e)
{
uiBook.SelectAll();
Unfilter();
}
void uiBook_DrawItem(object sender, DrawItemEventArgs e)
{
// Get the data
if (e.Index < 0)
return;
BookListItem book = uiBook.Items[e.Index] as BookListItem;
if (book == null)
return;
string[] parts = book.PartsFound(searchText);
// Get the drawing tools
Font theFont = GetBookFont(book);
Color theColor = book.isPresent ? e.ForeColor : emptyBooksColor;
// Calculate field widths if necessary
CalcFieldWidths(e.Graphics);
// Draw ListBox Item
using (Font searchFont = new Font(theFont, searchTextStyle))
{
e.DrawBackground();
e.DrawFocusRectangle();
DrawBookParts(parts, e.Graphics, e.Bounds, theColor, searchFont, theFont);
}
}
Font GetBookFont(BookListItem book)
{
return book.isPresent ? Font : emptyBooksFont;
}
void CalcFieldWidths(Graphics g)
{
const string measureText = "GEN";
if (abbreviationWidth >= 1f)
return;
// UserControl does not have UseCompatibleTextRendering.
var normalWidth = TextRenderer.MeasureText(g, measureText, Font).Width;
var notPresentWidth = TextRenderer.MeasureText(g, measureText, emptyBooksFont).Width;
abbreviationWidth = Math.Max(normalWidth, notPresentWidth) * 2.2f;
}
void DrawBookParts(string[] parts, Graphics gr, Rectangle bounds, Color theColor, Font font1, Font font2)
{
Font theFont = font1;
for (int i = 0; i < parts.Length; i++)
{
string theText = parts[i];
if (i == 2)
bounds.X = (int)abbreviationWidth; // tab over to name column
if (theText != "")
{
// UserControl does not have UseCompatibleTextRendering.
var size = TextRenderer.MeasureText(gr, theText, theFont, bounds.Size, TextFormatFlags.NoPadding|TextFormatFlags.WordBreak);
TextRenderer.DrawText(gr, theText, theFont, bounds, theColor, TextFormatFlags.NoPadding|TextFormatFlags.WordBreak);
bounds.X += size.Width;
bounds.Width -= size.Width;
}
theFont = Equals(theFont, font1) ? font2 : font1; // flip-flop font
}
}
#endregion
#region Autosuggest
private void Filter()
{
isUpdating = true;
//Debug.Print(string.Format("While filtering, filter = '{0}'.", searchText));
int selectionStart = uiBook.SelectionStart;
int selectionLength = uiBook.SelectionLength;
// Using Items.AddRange instead of Items.Add for performance reasons on mono.
List<BookListItem> tempList = new List<BookListItem>();
foreach (BookListItem book in allBooks)
{
if (book.PassesFilter(searchText, showEmptyBooks))
tempList.Add(book);
}
var currentItems = uiBook.Items.Cast<BookListItem>();
// Only update list if we need too. (Impoves display of Dropdown list on Linux)
if (tempList.Except(currentItems, new BookListItemComparer()).Any() || currentItems.Except(tempList, new BookListItemComparer()).Any())
{
uiBook.BeginUpdate();
uiBook.Items.Clear();
uiBook.Items.AddRange(tempList.ToArray());
//ensure correct list selection?
uiBook.EndUpdate();
uiBook.Refresh();
// TODO: fix mono bug where Refresh doesn't invalidate and redraw dropdown list box.
// The following is a work around to force mono to redraw the list box.
if (Platform.IsMono && uiBook.DroppedDown)
{
FieldInfo listBoxControlField = typeof(ComboBox).GetField("listbox_ctrl", BindingFlags.Instance | BindingFlags.NonPublic);
Control listBoxControl = (Control)listBoxControlField.GetValue(uiBook);
MethodInfo setTopItemMethod = listBoxControl.GetType().GetMethod("SetTopItem", BindingFlags.Instance | BindingFlags.Public);
setTopItemMethod.Invoke(listBoxControl, new object[] { 0 });
}
}
uiBook.Select(selectionStart, selectionLength);
isUpdating = false;
}
private void Unfilter()
{
searchText = "";
Filter(); //removes books not present if hidden
}
void uiBook_TextUpdate(object sender, EventArgs e)
{
if (isUpdating) return;
if (searchText != uiBook.Text)
{
searchText = uiBook.Text;
//Debug.Print(String.Format("In TextUpdate, books filter now = '{0}'.", searchText));
Filter();
}
uiChapter.Text = "1";
uiVerse.Text = "1";
}
#endregion
#region Book Events
/// <summary>
/// Enter key updates scripture ref.
/// </summary>
/// <param name="e">Event args received by event handler.</param>
bool AcceptOnEnter(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
uiBook.DroppedDown = false;
Unfilter();
try
{
AcceptData();
OnVerseRefChanged(new PropertyChangedEventArgs("VerseRef"));
return true;
}
catch
{
}
}
return false;
}
/// <summary>
/// Call to accept data currently in the verse controls and set the current
/// reference based on it.
/// </summary>
public void AcceptData()
{
curRef = new VerseRef(uiBook.Text + " " + uiChapter.Text + ":" + uiVerse.Text, curRef.Versification);
// Prevent going past last chapter/verse
if (curRef.ChapterNum > curRef.LastChapter)
curRef.ChapterNum = curRef.LastChapter;
if (curRef.VerseNum > curRef.LastVerse)
curRef.VerseNum = curRef.LastVerse;
UpdateControls();
}
/// <summary>
/// Updates the current verse ref with using the current text in the control. Will display a
/// warning if the text cannot be parsed.
/// </summary>
/// <returns>true if a warning was displayed</returns>
private bool AcceptDataWithWarning()
{
try
{
AcceptData();
return false;
}
catch (VerseRefException)
{
OnInvalidReference();
}
return true;
}
bool JumpOnSpace(KeyPressEventArgs e, Control nextField)
{
const string jumpCharacters = " :.";
if (e.KeyChar == 13)
{
// Enter
e.Handled = true; // Bell rings if we don't do this.
}
else if (e.KeyChar == 27)
{
// Escape
uiBook.DroppedDown = false;
uiBook.Text = BookAbbreviation;
uiBook.SelectAll();
}
else if (jumpCharacters.Contains(e.KeyChar.ToString()))
{
e.Handled = true;
nextField.Focus();
return true;
}
return false;
}
void uiBook_SelectionChangeCommitted(object sender, EventArgs e)
{
if (isUpdating)
return;
try
{
if (uiBook.SelectedItem == null)
return;
}
catch (ArgumentOutOfRangeException)
{
return;
}
ScrVers versif = ScrVers.English;
if (!curRef.IsDefault)
versif = curRef.Versification;
VerseRef = new VerseRef(((BookListItem)uiBook.SelectedItem).Abbreviation + " 1:1", versif);
if (advanceToEnd)
AdvanceToLastChapterLastVerse();
// Save book (as focus stealing can blank this control)
string book = uiBook.Text;
OnVerseRefChanged(new PropertyChangedEventArgs("VerseRef"));
uiBook.Text = book;
}
void uiBook_Enter(object sender, EventArgs e)
{
// BeginInvoke helps Linux - otherwise clicking
// Text in book combo doesn't select all.
BeginInvoke(new Action(() =>
{
uiBook.SelectAll();
Unfilter();
}));
}
void uiBook_KeyDown(object sender, KeyEventArgs e)
{
// Don't select all On Linux on Enter as combo text remains selected
// when focus moved to the TextForm.
if (IsBook())
if (AcceptOnEnter(e) && !Platform.IsLinux)
uiBook.SelectAll();
}
/// <summary>
/// Check whether it's okay to accept book field.
/// </summary>
/// <returns>True if current book field uniquely identifies a book.</returns>
bool IsBook()
{
bool result = false;
try
{
string validAbbreviations = abbreviations; // "GEN.EXO.LEV.NUM.DEU...REV";
string text = uiBook.Text;
if (text.Length >= AbbreviationLength && validAbbreviations.Contains(text.Substring(0, 3)))
result = true;
}
catch (ArgumentException)
{
}
if (!result)
OnInvalidBook(EventArgs.Empty);
return result;
}
bool IsBookChar(char c)
{
try
{
// True if character should be accepted
if (c == 8)
return true; //allow backspace
if (uiBook.Text.Length >= AbbreviationLength && uiBook.SelectionLength == 0)
return false;
if (Char.IsLetterOrDigit(c))
return true;
}
catch (ArgumentException)
{
}
return false;
}
void uiBook_KeyPress(object sender, KeyPressEventArgs e)
{
// FUTURE: accept menu and system key shortcuts (right now masks Alt-F4 for instance
e.KeyChar = Char.ToUpperInvariant(e.KeyChar); // force book names uppercase
if (IsBook()) // Only allow movement to next field if book ok
if (JumpOnSpace(e, uiChapter))
{
if (advanceToEnd)
AdvanceToLastChapterLastVerse();
return;
}
if (uiBook.Items.Count == 1 && e.KeyChar == ' ') // Only allow movement to next field if book is only choice
{
uiBook.Text = ((BookListItem)uiBook.Items[0]).Abbreviation;
uiBook.DroppedDown = false;
e.Handled = true;
if (advanceToEnd)
AdvanceToLastChapterLastVerse();
uiChapter.Focus();
return;
}
if (!IsBookChar(e.KeyChar))
{
//Don't allow typing if too long or not alphanumeric
e.Handled = true;
return;
}
if (uiBook.Items.Count != 0)
uiBook.DroppedDown = true;
}
void AdvanceToLastChapterLastVerse()
{
VerseRef vref = new VerseRef(uiBook.Text + " 1:1");
vref.Versification = curRef.Versification;
vref.ChapterNum = vref.LastChapter;
vref.VerseNum = vref.LastVerse;
AdvanceToLastSegment(vref);
uiChapter.Text = vref.Chapter;
uiVerse.Text = vref.Verse;
curRef.CopyFrom(vref);
}
private static void AdvanceToLastSegment(VerseRef vref)
{
string[] segments = vref.GetSegments(null);
if (segments != null && segments.Length > 0)
vref.Verse += segments[segments.Length - 1];
}
void AdvanceToLastVerse()
{
VerseRef vref = new VerseRef(uiBook.Text + " " + uiChapter.Text + ":1");
vref.Versification = curRef.Versification;
vref.VerseNum = vref.LastVerse;
AdvanceToLastSegment(vref);
uiVerse.Text = vref.Verse;
curRef.CopyFrom(vref);
}
void Revert()
{
// revert book to previous value
UpdateControls();
}
void uiBook_Leave(object sender, EventArgs e)
{
Unfilter();
if (!IsBook())
Revert();
}
/// <summary>
/// Leave events don't arrive reliability on Linux.
/// So we listen for the LostFocus event too.
/// </summary>
private void uiBook_LostFocus(object sender, EventArgs e)
{
if (Platform.IsWindows)
return;
uiBook_Leave(sender, e);
}
#endregion
#region Navigation Events (Chapter and Verse Event Handling)
void uiChapterPrev_Click(object sender, EventArgs e)
{
if (AcceptDataWithWarning())
return;
PrevChapter();
if (advanceToEnd)
AdvanceToLastVerse();
}
void uiChapterNext_Click(object sender, EventArgs e)
{
if (AcceptDataWithWarning())
return;
NextChapter();
if (advanceToEnd)
AdvanceToLastVerse();
}
void uiChapter_Enter(object sender, EventArgs e)
{
uiChapter.SelectAll();
}
void uiChapter_KeyDown(object sender, KeyEventArgs e)
{
if (AcceptOnEnter(e))
{
uiChapter.SelectAll();
if (advanceToEnd)
AdvanceToLastVerse();
}
}
void uiChapter_KeyPress(object sender, KeyPressEventArgs e)
{
if (!OkChapterInput(uiChapter, e, uiVerse))
e.Handled = true;
//if (JumpOnSpace(e, uiVerse)) return;
//if (uiChapter.SelectionLength > 0) return; //allow overtype
//if (!OkNNN( e.KeyChar, uiChapter.Text)) e.Handled = true; //swallow key if not valid for chapter
}
void control_GotFocus(object sender, EventArgs e)
{
OnTextBoxGotFocus();
}
/// <summary>
/// Returns false if we ought to ignore the keypress because it will do bad things to the verse ref
/// </summary>
/// <param name="textbox"></param>
/// <param name="e"></param>
/// <param name="nextField"></param>
/// <returns></returns>
bool OkChapterInput(TextBox textbox, KeyPressEventArgs e, Control nextField)
{
char c = e.KeyChar;
if (JumpOnSpace(e, nextField))
return true; // handle jump on space behavior
if (c == 8)
return true; //always allow backspace
//TODO: segmented verses allow letters as last char of verse
if (!Char.IsDigit(c))
return false; //expect digits from here on out
if (textbox.SelectionLength > 0)
return true; //allow overtype
if (textbox.Text.Length >= 3)
return false; // limit to 3 digits for ch and vs
return true;
}
void uiVersePrev_Click(object sender, EventArgs e)
{
if (AcceptDataWithWarning())
return;
PrevVerse();
}
void uiVerseNext_Click(object sender, EventArgs e)
{
if (AcceptDataWithWarning())
return;
NextVerse();
}
void uiVerse_Enter(object sender, EventArgs e)
{
uiVerse.SelectAll();
}
void uiVerse_KeyDown(object sender, KeyEventArgs e)
{
if (AcceptOnEnter(e)) uiVerse.SelectAll();
}
void uiVerse_KeyPress(object sender, KeyPressEventArgs e)
{
if (!OkVerseInput(uiVerse, e, uiBook))
e.Handled = true; //swallow key if not valid for verse
}
bool OkVerseInput(TextBox textbox, KeyPressEventArgs e, Control nextField)
{
char c = e.KeyChar;
if (JumpOnSpace(e, nextField))
return true; // handle jump on space behavior
if (c == 8)
return true; //always allow backspace
if (allowVerseSegments && VerseSegmentsAvailable)
{
if (!Char.IsLetterOrDigit(c))
return false;
}
else if (!Char.IsDigit(c))
return false;
if (textbox.SelectionLength > 0)
return true; //allow overtype
if (textbox.Text.Length >= 3)
return false; // limit to 3 digits for ch and vs
if (textbox.Text.Length > 0)
{
if (Char.IsLetter(textbox.Text[textbox.Text.Length - 1]))
return false; //no typing if last char is a letter
}
else if (Char.IsLetter(c))
return false; //can't start with letter
return true;
}
#endregion
#region BookListItem
/// <summary>
/// Holds book information in a way that supports the verse control.
/// </summary>
private sealed class BookListItem
{
// Instance Fields
public readonly string Abbreviation; // standard 3-letter all caps abbreviation
public string Name; // localized name
public string BaseName; // upper-case localized name without diacritics
public bool isPresent; // true if book has data
public override string ToString()
{
return Abbreviation;
}
public BookListItem(string abbreviation)
{
Abbreviation = abbreviation;
}
/// <summary>
/// Split book description and name into 4 parts (2 each):
/// The first of each pair including any text that matches the current search string
/// (What the user has typed into the book control).
///
/// Example:
/// Current Book: Genesis
/// Current Search Text: GE (the user has typed the first two letters of the book into the text box)
/// Returns: {"GE", "N", "Ge", "nesis"}
///
/// Purpose:
/// To simplify displaying highlight search text in the list of books.
/// </summary>
/// <param name="searchText">0-3 letters indicating current letters we ar searching for among books</param>
/// <returns>String[4] = {Abbreviation Found Part, Abbreviation Rest, Name </returns>
public string[] PartsFound(string searchText)
{
string[] result = { "", "", "", "" };
result[1] = Abbreviation; // default to nothing found, so [0] = "" and whole abbreviation is in [1]
result[3] = Name;
int len = searchText.Length;
if (len < 1)
return result;
if (Abbreviation.StartsWith(searchText, StringComparison.Ordinal))
{
// break out matching initial letters
result[0] = Abbreviation.Substring(0, len);
result[1] = Abbreviation.Substring(len);
}
if (BaseName.StartsWith(searchText, StringComparison.Ordinal))
{
//Note the subtle swap: we test on baseName, but we return the name with diacritics.
//Therefore, the names have to be fully composed.
result[2] = Name.Substring(0, len);
result[3] = Name.Substring(len);
}
return result;
}
public bool PassesFilter(string startsWith, bool showEmptyBooks)
{
if (!showEmptyBooks && !isPresent)
return false;
if (startsWith == "")
return true; //everything passes a blank filter
if (Abbreviation.StartsWith(startsWith, StringComparison.Ordinal))
return true;
if (BaseName.StartsWith(startsWith, StringComparison.Ordinal))
return true;
return false;
}
}
#endregion
#region BookListItemComparer
class BookListItemComparer : IEqualityComparer<BookListItem>
{
#region IEqualityComparer[BookListItem] implementation
public bool Equals(BookListItem x, BookListItem y)
{
return (x.Abbreviation == y.Abbreviation && x.BaseName == y.BaseName);
}
public int GetHashCode(BookListItem obj)
{
return obj.BaseName.GetHashCode();
}
#endregion
}
#endregion
void uiChapter_MouseDown(object sender, MouseEventArgs e)
{
uiChapter.SelectAll();
}
void uiVerse_MouseDown(object sender, MouseEventArgs e)
{
uiVerse.SelectAll();
}
}
}
| |
// 3D Projective Geometric Algebra
// Written by a generator written by enki.
using System;
using System.Text;
using static SPA.SPACETIME; // static variable acces
namespace SPA
{
public class SPACETIME
{
// just for debug and print output, the basis names
public static string[] _basis = new[] { "1","e1","e2","e3","e4","e12","e13","e14","e23","e24","e34","e123","e124","e134","e234","e1234" };
private float[] _mVec = new float[16];
/// <summary>
/// Ctor
/// </summary>
/// <param name="f"></param>
/// <param name="idx"></param>
public SPACETIME(float f = 0f, int idx = 0)
{
_mVec[idx] = f;
}
#region Array Access
public float this[int idx]
{
get { return _mVec[idx]; }
set { _mVec[idx] = value; }
}
#endregion
#region Overloaded Operators
/// <summary>
/// SPACETIME.Reverse : res = ~a
/// Reverse the order of the basis blades.
/// </summary>
public static SPACETIME operator ~ (SPACETIME a)
{
SPACETIME res = new SPACETIME();
res[0]=a[0];
res[1]=a[1];
res[2]=a[2];
res[3]=a[3];
res[4]=a[4];
res[5]=-a[5];
res[6]=-a[6];
res[7]=-a[7];
res[8]=-a[8];
res[9]=-a[9];
res[10]=-a[10];
res[11]=-a[11];
res[12]=-a[12];
res[13]=-a[13];
res[14]=-a[14];
res[15]=a[15];
return res;
}
/// <summary>
/// SPACETIME.Dual : res = !a
/// Poincare duality operator.
/// </summary>
public static SPACETIME operator ! (SPACETIME a)
{
SPACETIME res = new SPACETIME();
res[0]=-a[15];
res[1]=a[14];
res[2]=-a[13];
res[3]=a[12];
res[4]=a[11];
res[5]=a[10];
res[6]=-a[9];
res[7]=-a[8];
res[8]=a[7];
res[9]=a[6];
res[10]=-a[5];
res[11]=-a[4];
res[12]=-a[3];
res[13]=a[2];
res[14]=-a[1];
res[15]=a[0];
return res;
}
/// <summary>
/// SPACETIME.Conjugate : res = a.Conjugate()
/// Clifford Conjugation
/// </summary>
public SPACETIME Conjugate ()
{
SPACETIME res = new SPACETIME();
res[0]=this[0];
res[1]=-this[1];
res[2]=-this[2];
res[3]=-this[3];
res[4]=-this[4];
res[5]=-this[5];
res[6]=-this[6];
res[7]=-this[7];
res[8]=-this[8];
res[9]=-this[9];
res[10]=-this[10];
res[11]=this[11];
res[12]=this[12];
res[13]=this[13];
res[14]=this[14];
res[15]=this[15];
return res;
}
/// <summary>
/// SPACETIME.Involute : res = a.Involute()
/// Main involution
/// </summary>
public SPACETIME Involute ()
{
SPACETIME res = new SPACETIME();
res[0]=this[0];
res[1]=-this[1];
res[2]=-this[2];
res[3]=-this[3];
res[4]=-this[4];
res[5]=this[5];
res[6]=this[6];
res[7]=this[7];
res[8]=this[8];
res[9]=this[9];
res[10]=this[10];
res[11]=-this[11];
res[12]=-this[12];
res[13]=-this[13];
res[14]=-this[14];
res[15]=this[15];
return res;
}
/// <summary>
/// SPACETIME.Mul : res = a * b
/// The geometric product.
/// </summary>
public static SPACETIME operator * (SPACETIME a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]-b[4]*a[4]-b[5]*a[5]-b[6]*a[6]+b[7]*a[7]-b[8]*a[8]+b[9]*a[9]+b[10]*a[10]-b[11]*a[11]+b[12]*a[12]+b[13]*a[13]+b[14]*a[14]-b[15]*a[15];
res[1]=b[1]*a[0]+b[0]*a[1]-b[5]*a[2]-b[6]*a[3]+b[7]*a[4]+b[2]*a[5]+b[3]*a[6]-b[4]*a[7]-b[11]*a[8]+b[12]*a[9]+b[13]*a[10]-b[8]*a[11]+b[9]*a[12]+b[10]*a[13]-b[15]*a[14]+b[14]*a[15];
res[2]=b[2]*a[0]+b[5]*a[1]+b[0]*a[2]-b[8]*a[3]+b[9]*a[4]-b[1]*a[5]+b[11]*a[6]-b[12]*a[7]+b[3]*a[8]-b[4]*a[9]+b[14]*a[10]+b[6]*a[11]-b[7]*a[12]+b[15]*a[13]+b[10]*a[14]-b[13]*a[15];
res[3]=b[3]*a[0]+b[6]*a[1]+b[8]*a[2]+b[0]*a[3]+b[10]*a[4]-b[11]*a[5]-b[1]*a[6]-b[13]*a[7]-b[2]*a[8]-b[14]*a[9]-b[4]*a[10]-b[5]*a[11]-b[15]*a[12]-b[7]*a[13]-b[9]*a[14]+b[12]*a[15];
res[4]=b[4]*a[0]+b[7]*a[1]+b[9]*a[2]+b[10]*a[3]+b[0]*a[4]-b[12]*a[5]-b[13]*a[6]-b[1]*a[7]-b[14]*a[8]-b[2]*a[9]-b[3]*a[10]-b[15]*a[11]-b[5]*a[12]-b[6]*a[13]-b[8]*a[14]+b[11]*a[15];
res[5]=b[5]*a[0]+b[2]*a[1]-b[1]*a[2]+b[11]*a[3]-b[12]*a[4]+b[0]*a[5]-b[8]*a[6]+b[9]*a[7]+b[6]*a[8]-b[7]*a[9]+b[15]*a[10]+b[3]*a[11]-b[4]*a[12]+b[14]*a[13]-b[13]*a[14]+b[10]*a[15];
res[6]=b[6]*a[0]+b[3]*a[1]-b[11]*a[2]-b[1]*a[3]-b[13]*a[4]+b[8]*a[5]+b[0]*a[6]+b[10]*a[7]-b[5]*a[8]-b[15]*a[9]-b[7]*a[10]-b[2]*a[11]-b[14]*a[12]-b[4]*a[13]+b[12]*a[14]-b[9]*a[15];
res[7]=b[7]*a[0]+b[4]*a[1]-b[12]*a[2]-b[13]*a[3]-b[1]*a[4]+b[9]*a[5]+b[10]*a[6]+b[0]*a[7]-b[15]*a[8]-b[5]*a[9]-b[6]*a[10]-b[14]*a[11]-b[2]*a[12]-b[3]*a[13]+b[11]*a[14]-b[8]*a[15];
res[8]=b[8]*a[0]+b[11]*a[1]+b[3]*a[2]-b[2]*a[3]-b[14]*a[4]-b[6]*a[5]+b[5]*a[6]+b[15]*a[7]+b[0]*a[8]+b[10]*a[9]-b[9]*a[10]+b[1]*a[11]+b[13]*a[12]-b[12]*a[13]-b[4]*a[14]+b[7]*a[15];
res[9]=b[9]*a[0]+b[12]*a[1]+b[4]*a[2]-b[14]*a[3]-b[2]*a[4]-b[7]*a[5]+b[15]*a[6]+b[5]*a[7]+b[10]*a[8]+b[0]*a[9]-b[8]*a[10]+b[13]*a[11]+b[1]*a[12]-b[11]*a[13]-b[3]*a[14]+b[6]*a[15];
res[10]=b[10]*a[0]+b[13]*a[1]+b[14]*a[2]+b[4]*a[3]-b[3]*a[4]-b[15]*a[5]-b[7]*a[6]+b[6]*a[7]-b[9]*a[8]+b[8]*a[9]+b[0]*a[10]-b[12]*a[11]+b[11]*a[12]+b[1]*a[13]+b[2]*a[14]-b[5]*a[15];
res[11]=b[11]*a[0]+b[8]*a[1]-b[6]*a[2]+b[5]*a[3]+b[15]*a[4]+b[3]*a[5]-b[2]*a[6]-b[14]*a[7]+b[1]*a[8]+b[13]*a[9]-b[12]*a[10]+b[0]*a[11]+b[10]*a[12]-b[9]*a[13]+b[7]*a[14]-b[4]*a[15];
res[12]=b[12]*a[0]+b[9]*a[1]-b[7]*a[2]+b[15]*a[3]+b[5]*a[4]+b[4]*a[5]-b[14]*a[6]-b[2]*a[7]+b[13]*a[8]+b[1]*a[9]-b[11]*a[10]+b[10]*a[11]+b[0]*a[12]-b[8]*a[13]+b[6]*a[14]-b[3]*a[15];
res[13]=b[13]*a[0]+b[10]*a[1]-b[15]*a[2]-b[7]*a[3]+b[6]*a[4]+b[14]*a[5]+b[4]*a[6]-b[3]*a[7]-b[12]*a[8]+b[11]*a[9]+b[1]*a[10]-b[9]*a[11]+b[8]*a[12]+b[0]*a[13]-b[5]*a[14]+b[2]*a[15];
res[14]=b[14]*a[0]+b[15]*a[1]+b[10]*a[2]-b[9]*a[3]+b[8]*a[4]-b[13]*a[5]+b[12]*a[6]-b[11]*a[7]+b[4]*a[8]-b[3]*a[9]+b[2]*a[10]+b[7]*a[11]-b[6]*a[12]+b[5]*a[13]+b[0]*a[14]-b[1]*a[15];
res[15]=b[15]*a[0]+b[14]*a[1]-b[13]*a[2]+b[12]*a[3]-b[11]*a[4]+b[10]*a[5]-b[9]*a[6]+b[8]*a[7]+b[7]*a[8]-b[6]*a[9]+b[5]*a[10]+b[4]*a[11]-b[3]*a[12]+b[2]*a[13]-b[1]*a[14]+b[0]*a[15];
return res;
}
/// <summary>
/// SPACETIME.Wedge : res = a ^ b
/// The outer product. (MEET)
/// </summary>
public static SPACETIME operator ^ (SPACETIME a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0]=b[0]*a[0];
res[1]=b[1]*a[0]+b[0]*a[1];
res[2]=b[2]*a[0]+b[0]*a[2];
res[3]=b[3]*a[0]+b[0]*a[3];
res[4]=b[4]*a[0]+b[0]*a[4];
res[5]=b[5]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[5];
res[6]=b[6]*a[0]+b[3]*a[1]-b[1]*a[3]+b[0]*a[6];
res[7]=b[7]*a[0]+b[4]*a[1]-b[1]*a[4]+b[0]*a[7];
res[8]=b[8]*a[0]+b[3]*a[2]-b[2]*a[3]+b[0]*a[8];
res[9]=b[9]*a[0]+b[4]*a[2]-b[2]*a[4]+b[0]*a[9];
res[10]=b[10]*a[0]+b[4]*a[3]-b[3]*a[4]+b[0]*a[10];
res[11]=b[11]*a[0]+b[8]*a[1]-b[6]*a[2]+b[5]*a[3]+b[3]*a[5]-b[2]*a[6]+b[1]*a[8]+b[0]*a[11];
res[12]=b[12]*a[0]+b[9]*a[1]-b[7]*a[2]+b[5]*a[4]+b[4]*a[5]-b[2]*a[7]+b[1]*a[9]+b[0]*a[12];
res[13]=b[13]*a[0]+b[10]*a[1]-b[7]*a[3]+b[6]*a[4]+b[4]*a[6]-b[3]*a[7]+b[1]*a[10]+b[0]*a[13];
res[14]=b[14]*a[0]+b[10]*a[2]-b[9]*a[3]+b[8]*a[4]+b[4]*a[8]-b[3]*a[9]+b[2]*a[10]+b[0]*a[14];
res[15]=b[15]*a[0]+b[14]*a[1]-b[13]*a[2]+b[12]*a[3]-b[11]*a[4]+b[10]*a[5]-b[9]*a[6]+b[8]*a[7]+b[7]*a[8]-b[6]*a[9]+b[5]*a[10]+b[4]*a[11]-b[3]*a[12]+b[2]*a[13]-b[1]*a[14]+b[0]*a[15];
return res;
}
/// <summary>
/// SPACETIME.Vee : res = a & b
/// The regressive product. (JOIN)
/// </summary>
public static SPACETIME operator & (SPACETIME a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[15]=1*(a[15]*b[15]);
res[14]=-1*(a[14]*-1*b[15]+a[15]*b[14]*-1);
res[13]=1*(a[13]*b[15]+a[15]*b[13]);
res[12]=-1*(a[12]*-1*b[15]+a[15]*b[12]*-1);
res[11]=1*(a[11]*b[15]+a[15]*b[11]);
res[10]=1*(a[10]*b[15]+a[13]*b[14]*-1-a[14]*-1*b[13]+a[15]*b[10]);
res[9]=-1*(a[9]*-1*b[15]+a[12]*-1*b[14]*-1-a[14]*-1*b[12]*-1+a[15]*b[9]*-1);
res[8]=1*(a[8]*b[15]+a[11]*b[14]*-1-a[14]*-1*b[11]+a[15]*b[8]);
res[7]=1*(a[7]*b[15]+a[12]*-1*b[13]-a[13]*b[12]*-1+a[15]*b[7]);
res[6]=-1*(a[6]*-1*b[15]+a[11]*b[13]-a[13]*b[11]+a[15]*b[6]*-1);
res[5]=1*(a[5]*b[15]+a[11]*b[12]*-1-a[12]*-1*b[11]+a[15]*b[5]);
res[4]=-1*(a[4]*-1*b[15]+a[7]*b[14]*-1-a[9]*-1*b[13]+a[10]*b[12]*-1+a[12]*-1*b[10]-a[13]*b[9]*-1+a[14]*-1*b[7]+a[15]*b[4]*-1);
res[3]=1*(a[3]*b[15]+a[6]*-1*b[14]*-1-a[8]*b[13]+a[10]*b[11]+a[11]*b[10]-a[13]*b[8]+a[14]*-1*b[6]*-1+a[15]*b[3]);
res[2]=-1*(a[2]*-1*b[15]+a[5]*b[14]*-1-a[8]*b[12]*-1+a[9]*-1*b[11]+a[11]*b[9]*-1-a[12]*-1*b[8]+a[14]*-1*b[5]+a[15]*b[2]*-1);
res[1]=1*(a[1]*b[15]+a[5]*b[13]-a[6]*-1*b[12]*-1+a[7]*b[11]+a[11]*b[7]-a[12]*-1*b[6]*-1+a[13]*b[5]+a[15]*b[1]);
res[0]=1*(a[0]*b[15]+a[1]*b[14]*-1-a[2]*-1*b[13]+a[3]*b[12]*-1-a[4]*-1*b[11]+a[5]*b[10]-a[6]*-1*b[9]*-1+a[7]*b[8]+a[8]*b[7]-a[9]*-1*b[6]*-1+a[10]*b[5]+a[11]*b[4]*-1-a[12]*-1*b[3]+a[13]*b[2]*-1-a[14]*-1*b[1]+a[15]*b[0]);
return res;
}
/// <summary>
/// SPACETIME.Dot : res = a | b
/// The inner product.
/// </summary>
public static SPACETIME operator | (SPACETIME a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]-b[4]*a[4]-b[5]*a[5]-b[6]*a[6]+b[7]*a[7]-b[8]*a[8]+b[9]*a[9]+b[10]*a[10]-b[11]*a[11]+b[12]*a[12]+b[13]*a[13]+b[14]*a[14]-b[15]*a[15];
res[1]=b[1]*a[0]+b[0]*a[1]-b[5]*a[2]-b[6]*a[3]+b[7]*a[4]+b[2]*a[5]+b[3]*a[6]-b[4]*a[7]-b[11]*a[8]+b[12]*a[9]+b[13]*a[10]-b[8]*a[11]+b[9]*a[12]+b[10]*a[13]-b[15]*a[14]+b[14]*a[15];
res[2]=b[2]*a[0]+b[5]*a[1]+b[0]*a[2]-b[8]*a[3]+b[9]*a[4]-b[1]*a[5]+b[11]*a[6]-b[12]*a[7]+b[3]*a[8]-b[4]*a[9]+b[14]*a[10]+b[6]*a[11]-b[7]*a[12]+b[15]*a[13]+b[10]*a[14]-b[13]*a[15];
res[3]=b[3]*a[0]+b[6]*a[1]+b[8]*a[2]+b[0]*a[3]+b[10]*a[4]-b[11]*a[5]-b[1]*a[6]-b[13]*a[7]-b[2]*a[8]-b[14]*a[9]-b[4]*a[10]-b[5]*a[11]-b[15]*a[12]-b[7]*a[13]-b[9]*a[14]+b[12]*a[15];
res[4]=b[4]*a[0]+b[7]*a[1]+b[9]*a[2]+b[10]*a[3]+b[0]*a[4]-b[12]*a[5]-b[13]*a[6]-b[1]*a[7]-b[14]*a[8]-b[2]*a[9]-b[3]*a[10]-b[15]*a[11]-b[5]*a[12]-b[6]*a[13]-b[8]*a[14]+b[11]*a[15];
res[5]=b[5]*a[0]+b[11]*a[3]-b[12]*a[4]+b[0]*a[5]+b[15]*a[10]+b[3]*a[11]-b[4]*a[12]+b[10]*a[15];
res[6]=b[6]*a[0]-b[11]*a[2]-b[13]*a[4]+b[0]*a[6]-b[15]*a[9]-b[2]*a[11]-b[4]*a[13]-b[9]*a[15];
res[7]=b[7]*a[0]-b[12]*a[2]-b[13]*a[3]+b[0]*a[7]-b[15]*a[8]-b[2]*a[12]-b[3]*a[13]-b[8]*a[15];
res[8]=b[8]*a[0]+b[11]*a[1]-b[14]*a[4]+b[15]*a[7]+b[0]*a[8]+b[1]*a[11]-b[4]*a[14]+b[7]*a[15];
res[9]=b[9]*a[0]+b[12]*a[1]-b[14]*a[3]+b[15]*a[6]+b[0]*a[9]+b[1]*a[12]-b[3]*a[14]+b[6]*a[15];
res[10]=b[10]*a[0]+b[13]*a[1]+b[14]*a[2]-b[15]*a[5]+b[0]*a[10]+b[1]*a[13]+b[2]*a[14]-b[5]*a[15];
res[11]=b[11]*a[0]+b[15]*a[4]+b[0]*a[11]-b[4]*a[15];
res[12]=b[12]*a[0]+b[15]*a[3]+b[0]*a[12]-b[3]*a[15];
res[13]=b[13]*a[0]-b[15]*a[2]+b[0]*a[13]+b[2]*a[15];
res[14]=b[14]*a[0]+b[15]*a[1]+b[0]*a[14]-b[1]*a[15];
res[15]=b[15]*a[0]+b[0]*a[15];
return res;
}
/// <summary>
/// SPACETIME.Add : res = a + b
/// Multivector addition
/// </summary>
public static SPACETIME operator + (SPACETIME a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0] = a[0]+b[0];
res[1] = a[1]+b[1];
res[2] = a[2]+b[2];
res[3] = a[3]+b[3];
res[4] = a[4]+b[4];
res[5] = a[5]+b[5];
res[6] = a[6]+b[6];
res[7] = a[7]+b[7];
res[8] = a[8]+b[8];
res[9] = a[9]+b[9];
res[10] = a[10]+b[10];
res[11] = a[11]+b[11];
res[12] = a[12]+b[12];
res[13] = a[13]+b[13];
res[14] = a[14]+b[14];
res[15] = a[15]+b[15];
return res;
}
/// <summary>
/// SPACETIME.Sub : res = a - b
/// Multivector subtraction
/// </summary>
public static SPACETIME operator - (SPACETIME a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0] = a[0]-b[0];
res[1] = a[1]-b[1];
res[2] = a[2]-b[2];
res[3] = a[3]-b[3];
res[4] = a[4]-b[4];
res[5] = a[5]-b[5];
res[6] = a[6]-b[6];
res[7] = a[7]-b[7];
res[8] = a[8]-b[8];
res[9] = a[9]-b[9];
res[10] = a[10]-b[10];
res[11] = a[11]-b[11];
res[12] = a[12]-b[12];
res[13] = a[13]-b[13];
res[14] = a[14]-b[14];
res[15] = a[15]-b[15];
return res;
}
/// <summary>
/// SPACETIME.smul : res = a * b
/// scalar/multivector multiplication
/// </summary>
public static SPACETIME operator * (float a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0] = a*b[0];
res[1] = a*b[1];
res[2] = a*b[2];
res[3] = a*b[3];
res[4] = a*b[4];
res[5] = a*b[5];
res[6] = a*b[6];
res[7] = a*b[7];
res[8] = a*b[8];
res[9] = a*b[9];
res[10] = a*b[10];
res[11] = a*b[11];
res[12] = a*b[12];
res[13] = a*b[13];
res[14] = a*b[14];
res[15] = a*b[15];
return res;
}
/// <summary>
/// SPACETIME.muls : res = a * b
/// multivector/scalar multiplication
/// </summary>
public static SPACETIME operator * (SPACETIME a, float b)
{
SPACETIME res = new SPACETIME();
res[0] = a[0]*b;
res[1] = a[1]*b;
res[2] = a[2]*b;
res[3] = a[3]*b;
res[4] = a[4]*b;
res[5] = a[5]*b;
res[6] = a[6]*b;
res[7] = a[7]*b;
res[8] = a[8]*b;
res[9] = a[9]*b;
res[10] = a[10]*b;
res[11] = a[11]*b;
res[12] = a[12]*b;
res[13] = a[13]*b;
res[14] = a[14]*b;
res[15] = a[15]*b;
return res;
}
/// <summary>
/// SPACETIME.sadd : res = a + b
/// scalar/multivector addition
/// </summary>
public static SPACETIME operator + (float a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0] = a+b[0];
res[1] = b[1];
res[2] = b[2];
res[3] = b[3];
res[4] = b[4];
res[5] = b[5];
res[6] = b[6];
res[7] = b[7];
res[8] = b[8];
res[9] = b[9];
res[10] = b[10];
res[11] = b[11];
res[12] = b[12];
res[13] = b[13];
res[14] = b[14];
res[15] = b[15];
return res;
}
/// <summary>
/// SPACETIME.adds : res = a + b
/// multivector/scalar addition
/// </summary>
public static SPACETIME operator + (SPACETIME a, float b)
{
SPACETIME res = new SPACETIME();
res[0] = a[0]+b;
res[1] = a[1];
res[2] = a[2];
res[3] = a[3];
res[4] = a[4];
res[5] = a[5];
res[6] = a[6];
res[7] = a[7];
res[8] = a[8];
res[9] = a[9];
res[10] = a[10];
res[11] = a[11];
res[12] = a[12];
res[13] = a[13];
res[14] = a[14];
res[15] = a[15];
return res;
}
/// <summary>
/// SPACETIME.ssub : res = a - b
/// scalar/multivector subtraction
/// </summary>
public static SPACETIME operator - (float a, SPACETIME b)
{
SPACETIME res = new SPACETIME();
res[0] = a-b[0];
res[1] = -b[1];
res[2] = -b[2];
res[3] = -b[3];
res[4] = -b[4];
res[5] = -b[5];
res[6] = -b[6];
res[7] = -b[7];
res[8] = -b[8];
res[9] = -b[9];
res[10] = -b[10];
res[11] = -b[11];
res[12] = -b[12];
res[13] = -b[13];
res[14] = -b[14];
res[15] = -b[15];
return res;
}
/// <summary>
/// SPACETIME.subs : res = a - b
/// multivector/scalar subtraction
/// </summary>
public static SPACETIME operator - (SPACETIME a, float b)
{
SPACETIME res = new SPACETIME();
res[0] = a[0]-b;
res[1] = a[1];
res[2] = a[2];
res[3] = a[3];
res[4] = a[4];
res[5] = a[5];
res[6] = a[6];
res[7] = a[7];
res[8] = a[8];
res[9] = a[9];
res[10] = a[10];
res[11] = a[11];
res[12] = a[12];
res[13] = a[13];
res[14] = a[14];
res[15] = a[15];
return res;
}
#endregion
/// <summary>
/// SPACETIME.norm()
/// Calculate the Euclidean norm. (strict positive).
/// </summary>
public float norm() { return (float) Math.Sqrt(Math.Abs((this*this.Conjugate())[0]));}
/// <summary>
/// SPACETIME.inorm()
/// Calculate the Ideal norm. (signed)
/// </summary>
public float inorm() { return this[1]!=0.0f?this[1]:this[15]!=0.0f?this[15]:(!this).norm();}
/// <summary>
/// SPACETIME.normalized()
/// Returns a normalized (Euclidean) element.
/// </summary>
public SPACETIME normalized() { return this*(1/norm()); }
// The basis blades
public static SPACETIME e1 = new SPACETIME(1f, 1);
public static SPACETIME e2 = new SPACETIME(1f, 2);
public static SPACETIME e3 = new SPACETIME(1f, 3);
public static SPACETIME e4 = new SPACETIME(1f, 4);
public static SPACETIME e12 = new SPACETIME(1f, 5);
public static SPACETIME e13 = new SPACETIME(1f, 6);
public static SPACETIME e14 = new SPACETIME(1f, 7);
public static SPACETIME e23 = new SPACETIME(1f, 8);
public static SPACETIME e24 = new SPACETIME(1f, 9);
public static SPACETIME e34 = new SPACETIME(1f, 10);
public static SPACETIME e123 = new SPACETIME(1f, 11);
public static SPACETIME e124 = new SPACETIME(1f, 12);
public static SPACETIME e134 = new SPACETIME(1f, 13);
public static SPACETIME e234 = new SPACETIME(1f, 14);
public static SPACETIME e1234 = new SPACETIME(1f, 15);
/// string cast
public override string ToString()
{
var sb = new StringBuilder();
var n=0;
for (int i = 0; i < 16; ++i)
if (_mVec[i] != 0.0f) {
sb.Append($"{_mVec[i]}{(i == 0 ? string.Empty : _basis[i])} + ");
n++;
}
if (n==0) sb.Append("0");
return sb.ToString().TrimEnd(' ', '+');
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("e1*e1 : "+e1*e1);
Console.WriteLine("pss : "+e1234);
Console.WriteLine("pss*pss : "+e1234*e1234);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using NUnit.Framework.Api;
using NUnit.Framework.Internal;
using NUnit.TestUtilities;
using NUnit.TestData.ExpectedExceptionData;
#if !NETCF
using System.Runtime.Serialization;
#endif
namespace NUnit.Framework.Attributes
{
/// <summary>
///
/// </summary>
[TestFixture]
public class ExpectedExceptionTests
{
[Test, ExpectedException]
public void CanExpectUnspecifiedException()
{
throw new ArgumentException();
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void TestSucceedsWithSpecifiedExceptionType()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(ExpectedException=typeof(ArgumentException))]
public void TestSucceedsWithSpecifiedExceptionTypeAsNamedParameter()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException("System.ArgumentException")]
public void TestSucceedsWithSpecifiedExceptionName()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(ExpectedExceptionName="System.ArgumentException")]
public void TestSucceedsWithSpecifiedExceptionNameAsNamedParameter()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(typeof(ArgumentException),ExpectedMessage="argument exception")]
public void TestSucceedsWithSpecifiedExceptionTypeAndMessage()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage="argument exception", MatchType=MessageMatch.Exact)]
public void TestSucceedsWithSpecifiedExceptionTypeAndExactMatch()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(typeof(ArgumentException),ExpectedMessage="invalid", MatchType=MessageMatch.Contains)]
public void TestSucceedsWithSpecifiedExceptionTypeAndContainsMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
[ExpectedException(typeof(ArgumentException),ExpectedMessage="exception$", MatchType=MessageMatch.Regex)]
public void TestSucceedsWithSpecifiedExceptionTypeAndRegexMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "argument invalid", MatchType = MessageMatch.StartsWith)]
public void TestSucceedsWithSpecifiedExceptionTypeAndStartsWithMatch()
{
throw new ArgumentException("argument invalid exception");
}
// [Test]
// [ExpectedException("System.ArgumentException", "argument exception")]
// public void TestSucceedsWithSpecifiedExceptionNameAndMessage_OldFormat()
// {
// throw new ArgumentException("argument exception");
// }
[Test]
[ExpectedException("System.ArgumentException", ExpectedMessage = "argument exception")]
public void TestSucceedsWithSpecifiedExceptionNameAndMessage_NewFormat()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException("System.ArgumentException",ExpectedMessage="argument exception",MatchType=MessageMatch.Exact)]
public void TestSucceedsWithSpecifiedExceptionNameAndExactMatch()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException("System.ArgumentException",ExpectedMessage="invalid", MatchType=MessageMatch.Contains)]
public void TestSucceedsWhenSpecifiedExceptionNameAndContainsMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
[ExpectedException("System.ArgumentException",ExpectedMessage="exception$", MatchType=MessageMatch.Regex)]
public void TestSucceedsWhenSpecifiedExceptionNameAndRegexMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
public void TestFailsWhenBaseExceptionIsThrown()
{
Type fixtureType = typeof(BaseException);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "BaseExceptionTest" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "BaseExceptionTest should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.Exception"));
}
[Test]
public void TestFailsWhenDerivedExceptionIsThrown()
{
Type fixtureType = typeof(DerivedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "DerivedExceptionTest");
Assert.IsTrue(result.ResultState == ResultState.Failure, "DerivedExceptionTest should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.Exception" + Env.NewLine +
" but was: System.ArgumentException"));
}
[Test]
public void TestMismatchedExceptionType()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionType");
Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionType should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionTypeAsNamedParameter()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionTypeAsNamedParameter");
Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionType should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionTypeWithUserMessage()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "MismatchedExceptionTypeWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.That(result.Message, Is.StringStarting(
"custom message" + Env.NewLine +
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionName()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "MismatchedExceptionName" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionName should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionNameWithUserMessage()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionNameWithUserMessage");
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.That(result.Message, Is.StringStarting(
"custom message" + Env.NewLine +
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionMessage()
{
Type fixtureType = typeof(TestThrowsExceptionWithWrongMessage);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestThrow" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "TestThrow should have failed");
Assert.AreEqual(
"The exception message text was incorrect" + Env.NewLine +
"Expected: not the message" + Env.NewLine +
" but was: the message",
result.Message);
}
[Test]
public void TestMismatchedExceptionMessageWithUserMessage()
{
Type fixtureType = typeof(TestThrowsExceptionWithWrongMessage);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestThrowWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "TestThrow should have failed");
Assert.AreEqual(
"custom message" + Env.NewLine +
"The exception message text was incorrect" + Env.NewLine +
"Expected: not the message" + Env.NewLine +
" but was: the message",
result.Message);
}
[Test]
public void TestUnspecifiedExceptionNotThrown()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowUnspecifiedException" );
Assert.AreEqual(ResultState.Failure, result.ResultState);
Assert.AreEqual("An Exception was expected", result.Message);
}
[Test]
public void TestUnspecifiedExceptionNotThrownWithUserMessage()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "TestDoesNotThrowUnspecifiedExceptionWithUserMessage");
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("custom message" + Env.NewLine + "An Exception was expected", result.Message);
}
[Test]
public void TestExceptionTypeNotThrown()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionType" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("System.ArgumentException was expected", result.Message);
}
[Test]
public void TestExceptionTypeNotThrownWithUserMessage()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionTypeWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("custom message" + Env.NewLine + "System.ArgumentException was expected", result.Message);
}
[Test]
public void TestExceptionNameNotThrown()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionName" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("System.ArgumentException was expected", result.Message);
}
[Test]
public void TestExceptionNameNotThrownWithUserMessage()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionNameWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("custom message" + Env.NewLine + "System.ArgumentException was expected", result.Message);
}
[Test]
public void MethodThrowsException()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionFixture ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void MethodThrowsRightExceptionMessage()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionWithRightMessage ) );
Assert.AreEqual(true, result.ResultState == ResultState.Success);
}
[Test]
public void MethodThrowsArgumentOutOfRange()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsArgumentOutOfRangeException ) );
Assert.AreEqual(true, result.ResultState == ResultState.Success);
}
[Test]
public void MethodThrowsWrongExceptionMessage()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionWithWrongMessage ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void SetUpThrowsSameException()
{
TestResult result = TestBuilder.RunTestFixture( typeof( SetUpExceptionTests ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void TearDownThrowsSameException()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TearDownExceptionTests ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void AssertFailBeforeException()
{
TestResult suiteResult = TestBuilder.RunTestFixture( typeof (TestAssertsBeforeThrowingException) );
Assert.AreEqual( ResultState.Failure, suiteResult.ResultState );
TestResult result = (TestResult)suiteResult.Children[0];
Assert.AreEqual( "private message", result.Message );
}
internal class MyAppException : System.Exception
{
public MyAppException (string message) : base(message)
{}
public MyAppException(string message, Exception inner) :
base(message, inner)
{}
#if !NETCF && !SILVERLIGHT
protected MyAppException(SerializationInfo info,
StreamingContext context) : base(info,context)
{}
#endif
}
[Test]
[ExpectedException(typeof(MyAppException))]
public void ThrowingMyAppException()
{
throw new MyAppException("my app");
}
[Test]
[ExpectedException(typeof(MyAppException), ExpectedMessage="my app")]
public void ThrowingMyAppExceptionWithMessage()
{
throw new MyAppException("my app");
}
[Test]
[ExpectedException(typeof(NUnitException))]
public void ThrowNUnitException()
{
throw new NUnitException("Nunit exception");
}
[Test]
public void ExceptionHandlerIsCalledWhenExceptionMatches_AlternateHandler()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase( fixture, "ThrowsArgumentException_AlternateHandler" );
Assert.IsFalse(fixture.HandlerCalled, "Base Handler should not be called" );
Assert.IsTrue(fixture.AlternateHandlerCalled, "Alternate Handler should be called" );
}
[Test]
public void ExceptionHandlerIsCalledWhenExceptionMatches()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase( fixture, "ThrowsArgumentException" );
Assert.IsTrue(fixture.HandlerCalled, "Base Handler should be called");
Assert.IsFalse(fixture.AlternateHandlerCalled, "Alternate Handler should not be called");
}
[Test]
public void ExceptionHandlerIsNotCalledWhenExceptionDoesNotMatch()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase( fixture, "ThrowsCustomException" );
Assert.IsFalse( fixture.HandlerCalled, "Base Handler should not be called" );
Assert.IsFalse( fixture.AlternateHandlerCalled, "Alternate Handler should not be called" );
}
[Test]
public void ExceptionHandlerIsNotCalledWhenExceptionDoesNotMatch_AlternateHandler()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase(fixture, "ThrowsCustomException_AlternateHandler");
Assert.IsFalse(fixture.HandlerCalled, "Base Handler should not be called");
Assert.IsFalse(fixture.AlternateHandlerCalled, "Alternate Handler should not be called");
}
[Test]
public void TestIsNotRunnableWhenAlternateHandlerIsNotFound()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
Test test = TestBuilder.MakeTestCase( fixture, "MethodWithBadHandler" );
Assert.AreEqual( RunState.NotRunnable, test.RunState );
Assert.AreEqual(
"The specified exception handler DeliberatelyMissingHandler was not found",
test.Properties.Get(PropertyNames.SkipReason) );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
namespace Internal.TypeSystem
{
// Additional extensions to MethodDesc related to interop
partial class MethodDesc
{
/// <summary>
/// Gets a value indicating whether this method is a (native unmanaged) platform invoke.
/// Use <see cref="GetPInvokeMethodMetadata"/> to retrieve the platform invoke detail information.
/// </summary>
public virtual bool IsPInvoke
{
get
{
return false;
}
}
/// <summary>
/// If <see cref="IsPInvoke"/> is true, retrieves the metadata related to the platform invoke.
/// </summary>
public virtual PInvokeMetadata GetPInvokeMethodMetadata()
{
return default(PInvokeMetadata);
}
/// <summary>
/// Retrieves the metadata related to the parameters of the method.
/// </summary>
public virtual ParameterMetadata[] GetParameterMetadata()
{
return Array.Empty<ParameterMetadata>();
}
}
[Flags]
public enum ParameterMetadataAttributes
{
None = 0,
In = 1,
Out = 2,
Optional = 16,
HasDefault = 4096,
HasFieldMarshal = 8192
}
public struct ParameterMetadata
{
private readonly ParameterMetadataAttributes _attributes;
public readonly MarshalAsDescriptor MarshalAsDescriptor;
/// <summary>
/// Gets a 1-based index of the parameter within the signature the metadata refers to.
/// Index 0 is the return value.
/// </summary>
public readonly int Index;
public bool In { get { return (_attributes & ParameterMetadataAttributes.In) == ParameterMetadataAttributes.In; } }
public bool Out { get { return (_attributes & ParameterMetadataAttributes.Out) == ParameterMetadataAttributes.Out; } }
public bool Return { get { return Index == 0; } }
public bool Optional { get { return (_attributes & ParameterMetadataAttributes.Optional) == ParameterMetadataAttributes.Optional; } }
public bool HasDefault { get { return (_attributes & ParameterMetadataAttributes.HasDefault) == ParameterMetadataAttributes.HasDefault; } }
public bool HasFieldMarshal { get { return (_attributes & ParameterMetadataAttributes.HasFieldMarshal) == ParameterMetadataAttributes.HasFieldMarshal; } }
public ParameterMetadata(int index, ParameterMetadataAttributes attributes, MarshalAsDescriptor marshalAsDescriptor)
{
Index = index;
_attributes = attributes;
MarshalAsDescriptor = marshalAsDescriptor;
}
}
[Flags]
public enum PInvokeAttributes : short
{
None = 0,
ExactSpelling = 1,
CharSetAnsi = 2,
CharSetUnicode = 4,
CharSetAuto = 6,
CharSetMask = 6,
BestFitMappingEnable = 16,
BestFitMappingDisable = 32,
BestFitMappingMask = 48,
SetLastError = 64,
CallingConventionWinApi = 256,
CallingConventionCDecl = 512,
CallingConventionStdCall = 768,
CallingConventionThisCall = 1024,
CallingConventionFastCall = 1280,
CallingConventionMask = 1792,
ThrowOnUnmappableCharEnable = 4096,
ThrowOnUnmappableCharDisable = 8192,
ThrowOnUnmappableCharMask = 12288
}
public struct PInvokeFlags
{
private PInvokeAttributes _attributes;
public PInvokeAttributes Attributes
{
get
{
return _attributes;
}
}
public PInvokeFlags(PInvokeAttributes attributes)
{
_attributes = attributes;
}
public CharSet CharSet
{
get
{
PInvokeAttributes mask = _attributes & PInvokeAttributes.CharSetMask;
// ECMA-335 II.10.1.5 - Default value is Ansi.
CharSet charset = CharSet.Ansi;
if (mask == PInvokeAttributes.CharSetUnicode || mask == PInvokeAttributes.CharSetAuto)
{
charset = CharSet.Unicode;
}
return charset;
}
set
{
// clear the charset bits;
_attributes &= ~(PInvokeAttributes.CharSetMask);
if (value == CharSet.Unicode || (short)value == 4) // CharSet.Auto has value 4, but not in the enum
{
_attributes |= PInvokeAttributes.CharSetUnicode;
}
else
{
_attributes |= PInvokeAttributes.CharSetAnsi;
}
}
}
public MethodSignatureFlags UnmanagedCallingConvention
{
get
{
switch (_attributes & PInvokeAttributes.CallingConventionMask)
{
case PInvokeAttributes.CallingConventionWinApi:
return MethodSignatureFlags.UnmanagedCallingConventionStdCall; // TODO: CDecl for varargs
case PInvokeAttributes.CallingConventionCDecl:
return MethodSignatureFlags.UnmanagedCallingConventionCdecl;
case PInvokeAttributes.CallingConventionStdCall:
return MethodSignatureFlags.UnmanagedCallingConventionStdCall;
case PInvokeAttributes.CallingConventionThisCall:
return MethodSignatureFlags.UnmanagedCallingConventionThisCall;
case PInvokeAttributes.None:
return MethodSignatureFlags.None;
default:
throw new BadImageFormatException();
}
}
set
{
_attributes &= ~(PInvokeAttributes.CallingConventionMask);
switch (value)
{
case MethodSignatureFlags.UnmanagedCallingConventionStdCall:
_attributes |= PInvokeAttributes.CallingConventionStdCall;
break;
case MethodSignatureFlags.UnmanagedCallingConventionCdecl:
_attributes |= PInvokeAttributes.CallingConventionCDecl;
break;
case MethodSignatureFlags.UnmanagedCallingConventionThisCall:
_attributes |= PInvokeAttributes.CallingConventionThisCall;
break;
default:
System.Diagnostics.Debug.Assert(false, "Unexpected Unmanaged Calling Convention.");
break;
}
}
}
public bool SetLastError
{
get
{
return (_attributes & PInvokeAttributes.SetLastError) == PInvokeAttributes.SetLastError;
}
set
{
if (value)
{
_attributes |= PInvokeAttributes.SetLastError;
}
else
{
_attributes &= ~(PInvokeAttributes.SetLastError);
}
}
}
public bool ExactSpelling
{
get
{
return (_attributes & PInvokeAttributes.ExactSpelling) == PInvokeAttributes.ExactSpelling;
}
set
{
if (value)
{
_attributes |= PInvokeAttributes.ExactSpelling;
}
else
{
_attributes &= ~(PInvokeAttributes.ExactSpelling);
}
}
}
public bool BestFitMapping
{
get
{
PInvokeAttributes mask = _attributes & PInvokeAttributes.BestFitMappingMask;
if (mask == PInvokeAttributes.BestFitMappingDisable)
{
return false;
}
// default value is true
return true;
}
set
{
_attributes &= ~(PInvokeAttributes.BestFitMappingMask);
if (value)
{
_attributes |= PInvokeAttributes.BestFitMappingEnable;
}
else
{
_attributes |= PInvokeAttributes.BestFitMappingDisable;
}
}
}
public bool ThrowOnUnmappableChar
{
get
{
PInvokeAttributes mask = _attributes & PInvokeAttributes.ThrowOnUnmappableCharMask;
if (mask == PInvokeAttributes.ThrowOnUnmappableCharEnable)
{
return true;
}
// default value is false
return false;
}
set
{
_attributes &= ~(PInvokeAttributes.ThrowOnUnmappableCharMask);
if (value)
{
_attributes |= PInvokeAttributes.ThrowOnUnmappableCharEnable;
}
else
{
_attributes |= PInvokeAttributes.ThrowOnUnmappableCharDisable;
}
}
}
}
/// <summary>
/// Represents details about a pinvokeimpl method import.
/// </summary>
public struct PInvokeMetadata
{
public readonly string Name;
public readonly string Module;
public readonly PInvokeFlags Flags;
public PInvokeMetadata(string module, string entrypoint, PInvokeAttributes attributes)
{
Name = entrypoint;
Module = module;
Flags = new PInvokeFlags(attributes);
}
public PInvokeMetadata(string module, string entrypoint, PInvokeFlags flags)
{
Name = entrypoint;
Module = module;
Flags = flags;
}
}
partial class InstantiatedMethod
{
public override ParameterMetadata[] GetParameterMetadata()
{
return _methodDef.GetParameterMetadata();
}
}
partial class MethodForInstantiatedType
{
public override ParameterMetadata[] GetParameterMetadata()
{
return _typicalMethodDef.GetParameterMetadata();
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
namespace ChatSharp
{
/// <summary>
/// A user connected to IRC.
/// </summary>
public class IrcUser : IEquatable<IrcUser>
{
internal IrcUser()
{
Channels = new ChannelCollection();
ChannelModes = new Dictionary<IrcChannel, List<char?>>();
Account = "*";
}
/// <summary>
/// Constructs an IrcUser given a hostmask or nick.
/// </summary>
public IrcUser(string host) : this()
{
if (!host.Contains("@") && !host.Contains("!"))
Nick = host;
else
{
string[] mask = host.Split('@', '!');
Nick = mask[0];
User = mask[1];
if (mask.Length <= 2)
{
Hostname = "";
}
else
{
Hostname = mask[2];
}
}
}
/// <summary>
/// Constructs an IrcUser given a nick and user.
/// </summary>
public IrcUser(string nick, string user) : this()
{
Nick = nick;
User = user;
RealName = User;
Mode = string.Empty;
}
/// <summary>
/// Constructs an IRC user given a nick, user, and password.
/// </summary>
public IrcUser(string nick, string user, string password) : this(nick, user)
{
Password = password;
}
/// <summary>
/// Constructs an IRC user given a nick, user, password, and real name.
/// </summary>
public IrcUser(string nick, string user, string password, string realName) : this(nick, user, password)
{
RealName = realName;
}
/// <summary>
/// The user's nick.
/// </summary>
public string Nick { get; internal set; }
/// <summary>
/// The user's user (an IRC construct, a string that identifies your username).
/// </summary>
public string User { get; internal set; }
/// <summary>
/// The user's password. Will not be set on anyone but your own user.
/// </summary>
public string Password { get; internal set; }
/// <summary>
/// The user's mode.
/// </summary>
/// <value>The mode.</value>
public string Mode { get; internal set; }
/// <summary>
/// The user's real name.
/// </summary>
/// <value>The name of the real.</value>
public string RealName { get; internal set; }
/// <summary>
/// The user's hostname.
/// </summary>
public string Hostname { get; internal set; }
/// <summary>
/// Channels this user is present in. Note that this only includes channels you are
/// also present in, even after a successful WHOIS.
/// </summary>
/// <value>The channels.</value>
public ChannelCollection Channels { get; set; }
/// <summary>
/// The user's account. If 0 or *, the user is not logged in.
/// Otherwise, the user is logged in with services.
/// </summary>
public string Account { get; set; }
internal Dictionary<IrcChannel, List<char?>> ChannelModes { get; set; }
/// <summary>
/// This user's hostmask (nick!user@host).
/// </summary>
public string Hostmask
{
get
{
return Nick + "!" + User + "@" + Hostname;
}
}
/// <summary>
/// Returns true if the user matches the given mask. Can be used to check if a ban applies
/// to this user, for example.
/// </summary>
public bool Match(string mask)
{
if (mask.Contains("!") && mask.Contains("@"))
{
if (mask.Contains('$'))
mask = mask.Remove(mask.IndexOf('$')); // Extra fluff on some networks
var parts = mask.Split('!', '@');
if (Match(parts[0], Nick) && Match(parts[1], User) && Match(parts[2], Hostname))
return true;
}
return false;
}
/// <summary>
/// Checks if the given hostmask matches the given mask.
/// </summary>
public static bool Match(string mask, string value)
{
if (value == null)
value = string.Empty;
int i = 0;
int j = 0;
for (; j < value.Length && i < mask.Length; j++)
{
if (mask[i] == '?')
i++;
else if (mask[i] == '*')
{
i++;
if (i >= mask.Length)
return true;
while (++j < value.Length && value[j] != mask[i]) ;
if (j-- == value.Length)
return false;
}
else
{
if (char.ToUpper(mask[i]) != char.ToUpper(value[j]))
return false;
i++;
}
}
return i == mask.Length && j == value.Length;
}
/// <summary>
/// True if this user is equal to another (compares hostmasks).
/// </summary>
public bool Equals(IrcUser other)
{
return other.Hostmask == Hostmask;
}
/// <summary>
/// True if this user is equal to another (compares hostmasks).
/// </summary>
public override bool Equals(object obj)
{
if (obj is IrcUser)
return Equals((IrcUser)obj);
return false;
}
/// <summary>
/// Returns the hash code of the user's hostmask.
/// </summary>
public override int GetHashCode()
{
return Hostmask.GetHashCode();
}
/// <summary>
/// Returns the user's hostmask.
/// </summary>
public override string ToString()
{
return Hostmask;
}
}
}
| |
// dnlib: See LICENSE.txt for more info
namespace dnlib.DotNet.Emit {
/// <summary>
/// A CIL opcode. If the high byte is 0 or if it's <see cref="UNKNOWN1"/>, it's a 1-byte opcode,
/// else it's a two-byte opcode and the highest byte is the first byte of the opcode.
/// </summary>
public enum Code : ushort {
#pragma warning disable 1591 // disable XML doc warning
UNKNOWN1 = 0x0100,
UNKNOWN2 = 0x0101,
Add = 0x0058,
Add_Ovf = 0x00D6,
Add_Ovf_Un = 0x00D7,
And = 0x005F,
Arglist = 0xFE00,
Beq = 0x003B,
Beq_S = 0x002E,
Bge = 0x003C,
Bge_S = 0x002F,
Bge_Un = 0x0041,
Bge_Un_S = 0x0034,
Bgt = 0x003D,
Bgt_S = 0x0030,
Bgt_Un = 0x0042,
Bgt_Un_S = 0x0035,
Ble = 0x003E,
Ble_S = 0x0031,
Ble_Un = 0x0043,
Ble_Un_S = 0x0036,
Blt = 0x003F,
Blt_S = 0x0032,
Blt_Un = 0x0044,
Blt_Un_S = 0x0037,
Bne_Un = 0x0040,
Bne_Un_S = 0x0033,
Box = 0x008C,
Br = 0x0038,
Br_S = 0x002B,
Break = 0x0001,
Brfalse = 0x0039,
Brfalse_S = 0x002C,
Brtrue = 0x003A,
Brtrue_S = 0x002D,
Call = 0x0028,
Calli = 0x0029,
Callvirt = 0x006F,
Castclass = 0x0074,
Ceq = 0xFE01,
Cgt = 0xFE02,
Cgt_Un = 0xFE03,
Ckfinite = 0x00C3,
Clt = 0xFE04,
Clt_Un = 0xFE05,
Constrained = 0xFE16,
Conv_I = 0x00D3,
Conv_I1 = 0x0067,
Conv_I2 = 0x0068,
Conv_I4 = 0x0069,
Conv_I8 = 0x006A,
Conv_Ovf_I = 0x00D4,
Conv_Ovf_I_Un = 0x008A,
Conv_Ovf_I1 = 0x00B3,
Conv_Ovf_I1_Un = 0x0082,
Conv_Ovf_I2 = 0x00B5,
Conv_Ovf_I2_Un = 0x0083,
Conv_Ovf_I4 = 0x00B7,
Conv_Ovf_I4_Un = 0x0084,
Conv_Ovf_I8 = 0x00B9,
Conv_Ovf_I8_Un = 0x0085,
Conv_Ovf_U = 0x00D5,
Conv_Ovf_U_Un = 0x008B,
Conv_Ovf_U1 = 0x00B4,
Conv_Ovf_U1_Un = 0x0086,
Conv_Ovf_U2 = 0x00B6,
Conv_Ovf_U2_Un = 0x0087,
Conv_Ovf_U4 = 0x00B8,
Conv_Ovf_U4_Un = 0x0088,
Conv_Ovf_U8 = 0x00BA,
Conv_Ovf_U8_Un = 0x0089,
Conv_R_Un = 0x0076,
Conv_R4 = 0x006B,
Conv_R8 = 0x006C,
Conv_U = 0x00E0,
Conv_U1 = 0x00D2,
Conv_U2 = 0x00D1,
Conv_U4 = 0x006D,
Conv_U8 = 0x006E,
Cpblk = 0xFE17,
Cpobj = 0x0070,
Div = 0x005B,
Div_Un = 0x005C,
Dup = 0x0025,
Endfilter = 0xFE11,
Endfinally = 0x00DC,
Initblk = 0xFE18,
Initobj = 0xFE15,
Isinst = 0x0075,
Jmp = 0x0027,
Ldarg = 0xFE09,
Ldarg_0 = 0x0002,
Ldarg_1 = 0x0003,
Ldarg_2 = 0x0004,
Ldarg_3 = 0x0005,
Ldarg_S = 0x000E,
Ldarga = 0xFE0A,
Ldarga_S = 0x000F,
Ldc_I4 = 0x0020,
Ldc_I4_0 = 0x0016,
Ldc_I4_1 = 0x0017,
Ldc_I4_2 = 0x0018,
Ldc_I4_3 = 0x0019,
Ldc_I4_4 = 0x001A,
Ldc_I4_5 = 0x001B,
Ldc_I4_6 = 0x001C,
Ldc_I4_7 = 0x001D,
Ldc_I4_8 = 0x001E,
Ldc_I4_M1 = 0x0015,
Ldc_I4_S = 0x001F,
Ldc_I8 = 0x0021,
Ldc_R4 = 0x0022,
Ldc_R8 = 0x0023,
Ldelem = 0x00A3,
Ldelem_I = 0x0097,
Ldelem_I1 = 0x0090,
Ldelem_I2 = 0x0092,
Ldelem_I4 = 0x0094,
Ldelem_I8 = 0x0096,
Ldelem_R4 = 0x0098,
Ldelem_R8 = 0x0099,
Ldelem_Ref = 0x009A,
Ldelem_U1 = 0x0091,
Ldelem_U2 = 0x0093,
Ldelem_U4 = 0x0095,
Ldelema = 0x008F,
Ldfld = 0x007B,
Ldflda = 0x007C,
Ldftn = 0xFE06,
Ldind_I = 0x004D,
Ldind_I1 = 0x0046,
Ldind_I2 = 0x0048,
Ldind_I4 = 0x004A,
Ldind_I8 = 0x004C,
Ldind_R4 = 0x004E,
Ldind_R8 = 0x004F,
Ldind_Ref = 0x0050,
Ldind_U1 = 0x0047,
Ldind_U2 = 0x0049,
Ldind_U4 = 0x004B,
Ldlen = 0x008E,
Ldloc = 0xFE0C,
Ldloc_0 = 0x0006,
Ldloc_1 = 0x0007,
Ldloc_2 = 0x0008,
Ldloc_3 = 0x0009,
Ldloc_S = 0x0011,
Ldloca = 0xFE0D,
Ldloca_S = 0x0012,
Ldnull = 0x0014,
Ldobj = 0x0071,
Ldsfld = 0x007E,
Ldsflda = 0x007F,
Ldstr = 0x0072,
Ldtoken = 0x00D0,
Ldvirtftn = 0xFE07,
Leave = 0x00DD,
Leave_S = 0x00DE,
Localloc = 0xFE0F,
Mkrefany = 0x00C6,
Mul = 0x005A,
Mul_Ovf = 0x00D8,
Mul_Ovf_Un = 0x00D9,
Neg = 0x0065,
Newarr = 0x008D,
Newobj = 0x0073,
No = 0xFE19,
Nop = 0x0000,
Not = 0x0066,
Or = 0x0060,
Pop = 0x0026,
Prefix1 = 0x00FE,
Prefix2 = 0x00FD,
Prefix3 = 0x00FC,
Prefix4 = 0x00FB,
Prefix5 = 0x00FA,
Prefix6 = 0x00F9,
Prefix7 = 0x00F8,
Prefixref = 0x00FF,
Readonly = 0xFE1E,
Refanytype = 0xFE1D,
Refanyval = 0x00C2,
Rem = 0x005D,
Rem_Un = 0x005E,
Ret = 0x002A,
Rethrow = 0xFE1A,
Shl = 0x0062,
Shr = 0x0063,
Shr_Un = 0x0064,
Sizeof = 0xFE1C,
Starg = 0xFE0B,
Starg_S = 0x0010,
Stelem = 0x00A4,
Stelem_I = 0x009B,
Stelem_I1 = 0x009C,
Stelem_I2 = 0x009D,
Stelem_I4 = 0x009E,
Stelem_I8 = 0x009F,
Stelem_R4 = 0x00A0,
Stelem_R8 = 0x00A1,
Stelem_Ref = 0x00A2,
Stfld = 0x007D,
Stind_I = 0x00DF,
Stind_I1 = 0x0052,
Stind_I2 = 0x0053,
Stind_I4 = 0x0054,
Stind_I8 = 0x0055,
Stind_R4 = 0x0056,
Stind_R8 = 0x0057,
Stind_Ref = 0x0051,
Stloc = 0xFE0E,
Stloc_0 = 0x000A,
Stloc_1 = 0x000B,
Stloc_2 = 0x000C,
Stloc_3 = 0x000D,
Stloc_S = 0x0013,
Stobj = 0x0081,
Stsfld = 0x0080,
Sub = 0x0059,
Sub_Ovf = 0x00DA,
Sub_Ovf_Un = 0x00DB,
Switch = 0x0045,
Tailcall = 0xFE14,
Throw = 0x007A,
Unaligned = 0xFE12,
Unbox = 0x0079,
Unbox_Any = 0x00A5,
Volatile = 0xFE13,
Xor = 0x0061,
#pragma warning restore
}
public static partial class Extensions {
/// <summary>
/// Determines whether a <see cref="Code"/> is experimental
/// </summary>
/// <param name="code">The code</param>
/// <returns><c>true</c> if the <see cref="Code"/> is experimental; otherwise, <c>false</c></returns>
public static bool IsExperimental(this Code code) {
byte hi = (byte)((ushort)code >> 8);
return hi >= 0xF0 && hi <= 0xFB;
}
/// <summary>
/// Converts a <see cref="Code"/> to an <see cref="OpCode"/>
/// </summary>
/// <param name="code">The code</param>
/// <returns>A <see cref="OpCode"/> or <c>null</c> if it's invalid</returns>
public static OpCode ToOpCode(this Code code) {
byte hi = (byte)((ushort)code >> 8);
byte lo = (byte)code;
if (hi == 0)
return OpCodes.OneByteOpCodes[lo];
if (hi == 0xFE)
return OpCodes.TwoByteOpCodes[lo];
if (code == Code.UNKNOWN1)
return OpCodes.UNKNOWN1;
if (code == Code.UNKNOWN2)
return OpCodes.UNKNOWN2;
return null;
}
/// <summary>
/// Converts a <see cref="Code"/> to an <see cref="OpCode"/>, using a module context to look
/// up potential experimental opcodes
/// </summary>
/// <param name="code">The code</param>
/// <param name="context">The module context</param>
/// <returns>A <see cref="OpCode"/> or <c>null</c> if it's invalid</returns>
public static OpCode ToOpCode(this Code code, ModuleContext context) {
byte hi = (byte)((ushort)code >> 8);
byte lo = (byte)code;
if (hi == 0)
return OpCodes.OneByteOpCodes[lo];
if (hi == 0xFE)
return OpCodes.TwoByteOpCodes[lo];
if (context.GetExperimentalOpCode(hi, lo) is OpCode op)
return op;
if (code == Code.UNKNOWN1)
return OpCodes.UNKNOWN1;
if (code == Code.UNKNOWN2)
return OpCodes.UNKNOWN2;
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Builders;
using Microsoft.Data.Entity.Relational.Migrations;
using Microsoft.Data.Entity.Relational.Migrations.Builders;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using Microsoft.Data.Entity.Relational.Migrations.Operations;
using ReferenceWebsite.Models;
namespace ReferenceWebsite.Migrations
{
public partial class CreateIdentitySchema : Migration
{
public override void Up(MigrationBuilder migration)
{
migration.CreateTable(
name: "AspNetUsers",
columns: table => new
{
AccessFailedCount = table.Column(type: "int", nullable: false),
ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true),
Email = table.Column(type: "nvarchar(max)", nullable: true),
EmailConfirmed = table.Column(type: "bit", nullable: false),
Id = table.Column(type: "nvarchar(450)", nullable: true),
LockoutEnabled = table.Column(type: "bit", nullable: false),
LockoutEnd = table.Column(type: "datetimeoffset", nullable: true),
NormalizedEmail = table.Column(type: "nvarchar(max)", nullable: true),
NormalizedUserName = table.Column(type: "nvarchar(max)", nullable: true),
PasswordHash = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumber = table.Column(type: "nvarchar(max)", nullable: true),
PhoneNumberConfirmed = table.Column(type: "bit", nullable: false),
SecurityStamp = table.Column(type: "nvarchar(max)", nullable: true),
TwoFactorEnabled = table.Column(type: "bit", nullable: false),
UserName = table.Column(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migration.CreateTable(
name: "AspNetRoles",
columns: table => new
{
ConcurrencyStamp = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "nvarchar(450)", nullable: true),
Name = table.Column(type: "nvarchar(max)", nullable: true),
NormalizedName = table.Column(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migration.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
ClaimType = table.Column(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGeneration", "Identity"),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column(type: "nvarchar(450)", nullable: true),
ProviderDisplayName = table.Column(type: "nvarchar(max)", nullable: true),
ProviderKey = table.Column(type: "nvarchar(450)", nullable: true),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
ClaimType = table.Column(type: "nvarchar(max)", nullable: true),
ClaimValue = table.Column(type: "nvarchar(max)", nullable: true),
Id = table.Column(type: "int", nullable: false)
.Annotation("SqlServer:ValueGeneration", "Identity"),
RoleId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
columns: x => x.RoleId,
referencedTable: "AspNetRoles",
referencedColumn: "Id");
});
migration.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
RoleId = table.Column(type: "nvarchar(450)", nullable: true),
UserId = table.Column(type: "nvarchar(450)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
columns: x => x.RoleId,
referencedTable: "AspNetRoles",
referencedColumn: "Id");
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
columns: x => x.UserId,
referencedTable: "AspNetUsers",
referencedColumn: "Id");
});
}
public override void Down(MigrationBuilder migration)
{
migration.DropTable("AspNetUserRoles");
migration.DropTable("AspNetRoleClaims");
migration.DropTable("AspNetUserLogins");
migration.DropTable("AspNetUserClaims");
migration.DropTable("AspNetRoles");
migration.DropTable("AspNetUsers");
}
}
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta4"; }
}
public override IModel Target
{
get
{
var builder = new BasicModelBuilder()
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("ReferenceWebsite.Models.ApplicationUser", b =>
{
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 2);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 3);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 1);
b.Property<int>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2)
.Annotation("SqlServer:ValueGeneration", "Default");
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("ReferenceWebsite.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("ReferenceWebsite.Models.ApplicationUser", "UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]", b =>
{
b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId");
b.ForeignKey("ReferenceWebsite.Models.ApplicationUser", "UserId");
});
return builder.Model;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Collections.Generic;
using System.Security.Cryptography;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph {
public class AssetGraphController {
private List<NodeException> m_nodeExceptions;
private AssetReferenceStreamManager m_streamManager;
private Model.ConfigGraph m_targetGraph;
private PerformGraph[] m_performGraph;
private Model.NodeData m_currentNode;
private int gIndex;
private BuildTarget m_lastTarget;
private bool m_isBuilding;
public bool IsAnyIssueFound {
get {
return m_nodeExceptions.Count > 0;
}
}
public Model.NodeData CurrentNode {
get {
return m_currentNode;
}
}
public List<NodeException> Issues {
get {
return m_nodeExceptions;
}
}
public AssetReferenceStreamManager StreamManager {
get {
return m_streamManager;
}
}
public Model.ConfigGraph TargetGraph {
get {
return m_targetGraph;
}
}
public BuildTarget ActiveTarget {
get {
return m_lastTarget;
}
set {
Perform(value, false, false, false, null);
}
}
public AssetGraphController(Model.ConfigGraph graph) {
m_targetGraph = graph;
m_nodeExceptions = new List<NodeException>();
m_streamManager = new AssetReferenceStreamManager(m_targetGraph);
m_performGraph = new PerformGraph[] {
new PerformGraph(m_streamManager),
new PerformGraph(m_streamManager)
};
gIndex = 0;
m_currentNode = null;
}
/**
* Execute Run operations using current graph
*/
public bool Perform (
BuildTarget target,
bool isBuild,
bool logIssues,
bool forceVisitAll,
Action<Model.NodeData, string, float> updateHandler)
{
if (m_targetGraph == null) {
LogUtility.Logger.LogError (LogUtility.kTag, "Attempted to execute invalid graph (null)");
return false;
}
AssetGraphPostprocessor.Postprocessor.PushController (this);
LogUtility.Logger.Log(LogType.Log, (isBuild) ? "---Build BEGIN---" : "---Setup BEGIN---");
m_isBuilding = true;
if(isBuild) {
AssetBundleBuildReport.ClearReports();
}
foreach(var e in m_nodeExceptions) {
var errorNode = m_targetGraph.Nodes.Find(n => n.Id == e.NodeId);
// errorNode may not be found if user delete it on graph
if(errorNode != null) {
LogUtility.Logger.LogFormat(LogType.Log, "[Perform] {0} is marked to revisit due to last error", errorNode.Name);
errorNode.NeedsRevisit = true;
}
}
m_nodeExceptions.Clear();
m_lastTarget = target;
try {
PerformGraph oldGraph = m_performGraph[gIndex];
gIndex = (gIndex+1) %2;
PerformGraph newGraph = m_performGraph[gIndex];
newGraph.BuildGraphFromSaveData(m_targetGraph, target, oldGraph);
PerformGraph.Perform performFunc =
(Model.NodeData data,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output outputFunc) =>
{
DoNodeOperation(target, data, incoming, connectionsToOutput, outputFunc, isBuild, updateHandler);
};
newGraph.VisitAll(performFunc, forceVisitAll);
if(isBuild && m_nodeExceptions.Count == 0) {
Postprocess();
}
}
catch (NodeException e) {
m_nodeExceptions.Add(e);
}
// Minimize impact of errors happened during node operation
catch (Exception e) {
LogUtility.Logger.LogException(e);
}
m_isBuilding = false;
LogUtility.Logger.Log(LogType.Log, (isBuild) ? "---Build END---" : "---Setup END---");
if (logIssues) {
LogIssues ();
}
AssetGraphPostprocessor.Postprocessor.PopController ();
return true;
}
public void Validate (
NodeGUI node,
BuildTarget target)
{
m_nodeExceptions.RemoveAll(e => e.NodeId == node.Data.Id);
try {
LogUtility.Logger.LogFormat(LogType.Log, "[validate] {0} validate", node.Name);
m_isBuilding = true;
AssetGraphPostprocessor.Postprocessor.PushController (this);
DoNodeOperation(target, node.Data, null, null,
(Model.ConnectionData dst, Dictionary<string, List<AssetReference>> outputGroupAsset) => {},
false, null);
AssetGraphPostprocessor.Postprocessor.PopController();
if(!IsAnyIssueFound) {
LogUtility.Logger.LogFormat(LogType.Log, "[Perform] {0} ", node.Name);
Perform(target, false, false, false, null);
}
m_isBuilding = false;
} catch (NodeException e) {
m_nodeExceptions.Add(e);
}
}
private void LogIssues() {
var r = AssetProcessEventRecord.GetRecord();
foreach (var e in m_nodeExceptions) {
r.LogError (e);
}
}
/**
Perform Run or Setup from parent of given terminal node recursively.
*/
private void DoNodeOperation (
BuildTarget target,
Model.NodeData currentNodeData,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output outputFunc,
bool isActualRun,
Action<Model.NodeData, string, float> updateHandler)
{
try {
m_currentNode = currentNodeData;
if (updateHandler != null) {
updateHandler(currentNodeData, "Starting...", 0f);
}
if(isActualRun) {
currentNodeData.Operation.Object.Build(target, currentNodeData, incoming, connectionsToOutput, outputFunc, updateHandler);
}
else {
currentNodeData.Operation.Object.Prepare(target, currentNodeData, incoming, connectionsToOutput, outputFunc);
}
if (updateHandler != null) {
updateHandler(currentNodeData, "Completed.", 1f);
}
} catch (NodeException e) {
m_nodeExceptions.Add(e);
}
// Minimize impact of errors happened during node operation
catch (Exception e) {
m_nodeExceptions.Add(new NodeException(string.Format("{0}:{1}", e.GetType().ToString(), e.Message), "See Console for detail.", currentNodeData));
LogUtility.Logger.LogException(e);
}
m_currentNode = null;
}
private void Postprocess ()
{
var postprocessType = typeof(IPostprocess);
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
var ppTypes = assembly.GetTypes().Select(v => v).Where(v => v != postprocessType && postprocessType.IsAssignableFrom(v)).ToList();
foreach (var t in ppTypes) {
var postprocessScriptInstance = assembly.CreateInstance(t.FullName);
if (postprocessScriptInstance == null) {
throw new AssetGraphException("Postprocess " + t.Name + " failed to run (failed to create instance from assembly).");
}
var postprocessInstance = (IPostprocess)postprocessScriptInstance;
postprocessInstance.DoPostprocess(AssetBundleBuildReport.BuildReports, AssetBundleBuildReport.ExportReports);
}
}
}
public void OnAssetsReimported(AssetPostprocessorContext ctx) {
// ignore asset reimport event during build
if(m_isBuilding) {
return;
}
if(m_targetGraph.Nodes == null) {
return;
}
bool isAnyNodeAffected = false;
foreach(var n in m_targetGraph.Nodes) {
bool affected = n.Operation.Object.OnAssetsReimported(n, m_streamManager, m_lastTarget, ctx, false);
if(affected) {
n.NeedsRevisit = true;
}
isAnyNodeAffected |= affected;
}
if(isAnyNodeAffected) {
Perform(m_lastTarget, false, false, false, null);
}
}
}
}
| |
//
// 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.LayoutRenderers
{
using System;
using System.Collections.Generic;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Internal;
using Xunit;
using NLog.Config;
public class ExceptionTests : NLogTestBase
{
private ILogger logger = LogManager.GetLogger("NLog.UnitTests.LayoutRenderer.ExceptionTests");
private const string ExceptionDataFormat = "{0}: {1}";
[Fact]
public void ExceptionWithStackTrace_ObsoleteMethodTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", "Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionWithStackTraceTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(CustomArgumentException).Name);
}
/// <summary>
/// Just wrrite exception, no message argument.
/// </summary>
[Fact]
public void ExceptionWithoutMessageParam()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "I don't like nullref exception!";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex);
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionWithoutStackTrace_ObsoleteMethodTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", "");
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug7", "");
AssertDebugLastMessage("debug8", "Test exception*" + typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void ExceptionWithoutStackTraceTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", "");
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug7", "");
AssertDebugLastMessage("debug8", "Test exception*" + typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void ExceptionNewLineSeparatorTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=message,shorttype:separator= }' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(CustomArgumentException).Name);
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingLogMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Log(LogLevel.Error, ex, "msg");
AssertDebugLastMessage("debug1", "ERROR*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Log(LogLevel.Error, ex, () => "msg func");
AssertDebugLastMessage("debug1", "ERROR*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingTraceMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Trace(ex, "msg");
AssertDebugLastMessage("debug1", "TRACE*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Trace(ex, () => "msg func");
AssertDebugLastMessage("debug1", "TRACE*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingDebugMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Debug(ex, "msg");
AssertDebugLastMessage("debug1", "DEBUG*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Debug(ex, () => "msg func");
AssertDebugLastMessage("debug1", "DEBUG*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingInfoMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Info(ex, "msg");
AssertDebugLastMessage("debug1", "INFO*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Info(ex, () => "msg func");
AssertDebugLastMessage("debug1", "INFO*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingWarnMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Warn(ex, "msg");
AssertDebugLastMessage("debug1", "WARN*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Warn(ex, () => "msg func");
AssertDebugLastMessage("debug1", "WARN*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingErrorMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ERROR*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Error(ex, () => "msg func");
AssertDebugLastMessage("debug1", "ERROR*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingFatalMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Fatal(ex, "msg");
AssertDebugLastMessage("debug1", "FATAL*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Fatal(ex, () => "msg func");
AssertDebugLastMessage("debug1", "FATAL*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void InnerExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
}
[Fact]
public void InnerExceptionTest_Serialize()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=@}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
var lastMessage1 = GetDebugLastMessage("debug1");
Assert.StartsWith("{\"Message\":\"Wrapper2\"", lastMessage1);
Assert.Contains("\"InnerException\":{\"Message\":\"Wrapper1\"", lastMessage1);
Assert.Contains("\"ParamName\":\"exceptionMessage\"", lastMessage1);
Assert.Contains("1Really_Bad_Boy_", lastMessage1);
#pragma warning restore 0618
logger.Error(ex, "msg");
var lastMessage2 = GetDebugLastMessage("debug1");
Assert.StartsWith("{\"Message\":\"Wrapper2\"", lastMessage2);
Assert.Contains("\"InnerException\":{\"Message\":\"Wrapper1\"", lastMessage2);
Assert.Contains("\"ParamName\":\"exceptionMessage\"", lastMessage2);
Assert.Contains("1Really_Bad_Boy_", lastMessage1);
}
[Fact]
public void CustomInnerException_ObsoleteMethodTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1");
AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void CustomInnerExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1");
AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var ex = new ExceptionWithBrokenMessagePropertyException();
var exRecorded = Record.Exception(() => logger.Error(ex, "msg"));
Assert.Null(exRecorded);
}
[Fact]
public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception_serialize()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=@}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var ex = new ExceptionWithBrokenMessagePropertyException();
var exRecorded = Record.Exception(() => logger.Error(ex, "msg"));
Assert.Null(exRecorded);
}
#if NET3_5
[Fact(Skip = "NET3_5 not supporting AggregateException")]
#else
[Fact]
#endif
public void AggregateExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=5}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 1", new Exception("Test Inner 1")); },
System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default);
var task2 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 2", new Exception("Test Inner 2")); },
System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default);
var aggregateExceptionMessage = "nothing thrown!";
try
{
System.Threading.Tasks.Task.WaitAll(new[] { task1, task2 });
}
catch (AggregateException ex)
{
aggregateExceptionMessage = ex.ToString();
logger.Error(ex, "msg");
}
Assert.Contains("Test exception 1", aggregateExceptionMessage);
Assert.Contains("Test exception 2", aggregateExceptionMessage);
Assert.Contains("Test Inner 1", aggregateExceptionMessage);
Assert.Contains("Test Inner 2", aggregateExceptionMessage);
AssertDebugLastMessageContains("debug1", "AggregateException");
AssertDebugLastMessageContains("debug1", "One or more errors occurred");
AssertDebugLastMessageContains("debug1", "Test exception 1");
AssertDebugLastMessageContains("debug1", "Test exception 2");
AssertDebugLastMessageContains("debug1", "Test Inner 1");
AssertDebugLastMessageContains("debug1", "Test Inner 2");
}
private class ExceptionWithBrokenMessagePropertyException : NLogConfigurationException
{
public override string Message => throw new Exception("Exception from Message property");
}
private void SetConfigurationForExceptionUsingRootMethodTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${level:uppercase=true}*${message}*${exception:format=message,shorttype:separator=*}' />
</targets>
<rules>
<logger minlevel='Trace' writeTo='debug1' />
</rules>
</nlog>");
}
/// <summary>
/// Get an excption with stacktrace by genating a exception
/// </summary>
/// <param name="exceptionMessage"></param>
/// <returns></returns>
private Exception GetExceptionWithStackTrace(string exceptionMessage)
{
try
{
GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage);
return null;
}
catch (Exception exception)
{
return exception;
}
}
private Exception GetNestedExceptionWithStackTrace(string exceptionMessage)
{
try
{
try
{
try
{
GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage);
}
catch (Exception exception)
{
throw new InvalidOperationException("Wrapper1", exception);
}
}
catch (Exception exception)
{
throw new InvalidOperationException("Wrapper2", exception);
}
return null;
}
catch (Exception ex)
{
ex.Data["1Really.Bad-Boy!"] = "Hello World";
return ex;
}
}
private Exception GetExceptionWithoutStackTrace(string exceptionMessage)
{
return new CustomArgumentException(exceptionMessage, "exceptionMessage");
}
private class GenericClass<TA, TB, TC>
{
internal static List<GenericClass<TA, TB, TC>> Method1(string aaa, bool b, object o, int i, DateTime now, string exceptionMessage)
{
Method2(aaa, b, o, i, now, null, null, exceptionMessage);
return null;
}
internal static int Method2<T1, T2, T3>(T1 aaa, T2 b, T3 o, int i, DateTime now, Nullable<int> gfff, List<int>[] something, string exceptionMessage)
{
throw new CustomArgumentException(exceptionMessage, "exceptionMessage");
}
}
public class CustomArgumentException : InvalidOperationException
{
public CustomArgumentException(string message, string paramName)
:base(message)
{
ParamName = paramName;
StrangeProperty = "Strange World";
}
public string ParamName { get; }
public string StrangeProperty { private get; set; }
}
[Fact]
public void ExcpetionTestAPI()
{
var config = new LoggingConfiguration();
var debugTarget = new DebugTarget();
config.AddTarget("debug1", debugTarget);
debugTarget.Layout = @"${exception:format=shorttype,message:maxInnerExceptionLevel=3}";
var rule = new LoggingRule("*", LogLevel.Info, debugTarget);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]);
Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]);
}
[Fact]
public void InnerExceptionTestAPI()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3:innerFormat=message}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"Wrapper1" + EnvironmentHelper.NewLine +
"Test exception");
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"Wrapper1" + EnvironmentHelper.NewLine +
"Test exception");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]);
Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]);
Assert.Equal(ExceptionRenderingFormat.Message, elr.InnerFormats[0]);
}
[Fact]
public void CustomExceptionLayoutRendrerInnerExceptionTest()
{
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("exception-custom", typeof(CustomExceptionLayoutRendrer));
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as CustomExceptionLayoutRendrer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + "\r\ncustom-exception-renderer" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1" + "\r\ncustom-exception-renderer");
AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" + "\r\ncustom-exception-renderer" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1" + "\r\ncustom-exception-renderer " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue + "\r\ncustom-exception-renderer-data"));
}
[Fact]
public void ExceptionDataWithDifferentSeparators()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=data}' />
<target name='debug2' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=*}' />
<target name='debug3' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=## **}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1, debug2, debug3' />
</rules>
</nlog>");
const string defaultExceptionDataSeparator = ";";
const string exceptionMessage = "message for exception";
const string exceptionDataKey1 = "testkey1";
const string exceptionDataValue1 = "testvalue1";
const string exceptionDataKey2 = "testkey2";
const string exceptionDataValue2 = "testvalue2";
var target = (DebugTarget)LogManager.Configuration.AllTargets[0];
var exceptionLayoutRenderer = ((SimpleLayout)target.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.NotNull(exceptionLayoutRenderer);
Assert.Equal(defaultExceptionDataSeparator, exceptionLayoutRenderer.ExceptionDataSeparator);
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey1, exceptionDataValue1);
ex.Data.Add(exceptionDataKey2, exceptionDataValue2);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + defaultExceptionDataSeparator + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug2", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "*" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug3", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "## **" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
}
[Fact]
public void ExceptionDataWithNewLineSeparator()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=\r\n}' />
<target name='debug2' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=\r\n----DATA----\r\n}' />
<target name='debug3' type='Debug' layout='${exception:format=data:ExceptionDataSeparator= ----DATA---- }' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1, debug2, debug3' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
const string exceptionDataKey1 = "testkey1";
const string exceptionDataValue1 = "testvalue1";
const string exceptionDataKey2 = "testkey2";
const string exceptionDataValue2 = "testvalue2";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey1, exceptionDataValue1);
ex.Data.Add(exceptionDataKey2, exceptionDataValue2);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug2", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n----DATA----\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug3", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n----DATA----\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
}
[Fact]
public void ExceptionWithSeparatorForExistingRender()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=tostring,data:separator=\r\nXXX}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
const string exceptionDataKey1 = "testkey1";
const string exceptionDataValue1 = "testvalue1";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey1, exceptionDataValue1);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) + "\r\nXXX" + string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1));
}
[Fact]
public void ExceptionWithoutSeparatorForNoRender()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=tostring,data:separator=\r\nXXX}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage));
}
}
[LayoutRenderer("exception-custom")]
[ThreadAgnostic]
public class CustomExceptionLayoutRendrer : ExceptionLayoutRenderer
{
protected override void AppendMessage(System.Text.StringBuilder sb, Exception ex)
{
base.AppendMessage(sb, ex);
sb.Append("\r\ncustom-exception-renderer");
}
protected override void AppendData(System.Text.StringBuilder sb, Exception ex)
{
base.AppendData(sb, ex);
sb.Append("\r\ncustom-exception-renderer-data");
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Steamworks.Data;
namespace Steamworks
{
internal unsafe class ISteamMusicRemote : SteamInterface
{
internal ISteamMusicRemote( bool IsGameServer )
{
SetupInterface( IsGameServer );
}
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamMusicRemote_v001", CallingConvention = Platform.CC)]
internal static extern IntPtr SteamAPI_SteamMusicRemote_v001();
public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamMusicRemote_v001();
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_RegisterSteamMusicRemote", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _RegisterSteamMusicRemote( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName );
#endregion
internal bool RegisterSteamMusicRemote( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchName )
{
var returnValue = _RegisterSteamMusicRemote( Self, pchName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_DeregisterSteamMusicRemote", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _DeregisterSteamMusicRemote( IntPtr self );
#endregion
internal bool DeregisterSteamMusicRemote()
{
var returnValue = _DeregisterSteamMusicRemote( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_BIsCurrentMusicRemote", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _BIsCurrentMusicRemote( IntPtr self );
#endregion
internal bool BIsCurrentMusicRemote()
{
var returnValue = _BIsCurrentMusicRemote( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_BActivationSuccess", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _BActivationSuccess( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool BActivationSuccess( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _BActivationSuccess( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_SetDisplayName", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetDisplayName( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchDisplayName );
#endregion
internal bool SetDisplayName( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchDisplayName )
{
var returnValue = _SetDisplayName( Self, pchDisplayName );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_SetPNGIcon_64x64", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetPNGIcon_64x64( IntPtr self, IntPtr pvBuffer, uint cbBufferLength );
#endregion
internal bool SetPNGIcon_64x64( IntPtr pvBuffer, uint cbBufferLength )
{
var returnValue = _SetPNGIcon_64x64( Self, pvBuffer, cbBufferLength );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_EnablePlayPrevious", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _EnablePlayPrevious( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool EnablePlayPrevious( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _EnablePlayPrevious( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_EnablePlayNext", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _EnablePlayNext( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool EnablePlayNext( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _EnablePlayNext( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_EnableShuffled", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _EnableShuffled( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool EnableShuffled( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _EnableShuffled( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_EnableLooped", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _EnableLooped( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool EnableLooped( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _EnableLooped( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_EnableQueue", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _EnableQueue( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool EnableQueue( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _EnableQueue( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_EnablePlaylists", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _EnablePlaylists( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool EnablePlaylists( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _EnablePlaylists( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_UpdatePlaybackStatus", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdatePlaybackStatus( IntPtr self, MusicStatus nStatus );
#endregion
internal bool UpdatePlaybackStatus( MusicStatus nStatus )
{
var returnValue = _UpdatePlaybackStatus( Self, nStatus );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_UpdateShuffled", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateShuffled( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool UpdateShuffled( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _UpdateShuffled( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_UpdateLooped", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateLooped( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bValue );
#endregion
internal bool UpdateLooped( [MarshalAs( UnmanagedType.U1 )] bool bValue )
{
var returnValue = _UpdateLooped( Self, bValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_UpdateVolume", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateVolume( IntPtr self, float flValue );
#endregion
internal bool UpdateVolume( float flValue )
{
var returnValue = _UpdateVolume( Self, flValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_CurrentEntryWillChange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _CurrentEntryWillChange( IntPtr self );
#endregion
internal bool CurrentEntryWillChange()
{
var returnValue = _CurrentEntryWillChange( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_CurrentEntryIsAvailable", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _CurrentEntryIsAvailable( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bAvailable );
#endregion
internal bool CurrentEntryIsAvailable( [MarshalAs( UnmanagedType.U1 )] bool bAvailable )
{
var returnValue = _CurrentEntryIsAvailable( Self, bAvailable );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_UpdateCurrentEntryText", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateCurrentEntryText( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchText );
#endregion
internal bool UpdateCurrentEntryText( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchText )
{
var returnValue = _UpdateCurrentEntryText( Self, pchText );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_UpdateCurrentEntryElapsedSeconds", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateCurrentEntryElapsedSeconds( IntPtr self, int nValue );
#endregion
internal bool UpdateCurrentEntryElapsedSeconds( int nValue )
{
var returnValue = _UpdateCurrentEntryElapsedSeconds( Self, nValue );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_UpdateCurrentEntryCoverArt", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _UpdateCurrentEntryCoverArt( IntPtr self, IntPtr pvBuffer, uint cbBufferLength );
#endregion
internal bool UpdateCurrentEntryCoverArt( IntPtr pvBuffer, uint cbBufferLength )
{
var returnValue = _UpdateCurrentEntryCoverArt( Self, pvBuffer, cbBufferLength );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_CurrentEntryDidChange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _CurrentEntryDidChange( IntPtr self );
#endregion
internal bool CurrentEntryDidChange()
{
var returnValue = _CurrentEntryDidChange( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_QueueWillChange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _QueueWillChange( IntPtr self );
#endregion
internal bool QueueWillChange()
{
var returnValue = _QueueWillChange( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_ResetQueueEntries", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _ResetQueueEntries( IntPtr self );
#endregion
internal bool ResetQueueEntries()
{
var returnValue = _ResetQueueEntries( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_SetQueueEntry", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetQueueEntry( IntPtr self, int nID, int nPosition, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchEntryText );
#endregion
internal bool SetQueueEntry( int nID, int nPosition, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchEntryText )
{
var returnValue = _SetQueueEntry( Self, nID, nPosition, pchEntryText );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_SetCurrentQueueEntry", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetCurrentQueueEntry( IntPtr self, int nID );
#endregion
internal bool SetCurrentQueueEntry( int nID )
{
var returnValue = _SetCurrentQueueEntry( Self, nID );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_QueueDidChange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _QueueDidChange( IntPtr self );
#endregion
internal bool QueueDidChange()
{
var returnValue = _QueueDidChange( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_PlaylistWillChange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _PlaylistWillChange( IntPtr self );
#endregion
internal bool PlaylistWillChange()
{
var returnValue = _PlaylistWillChange( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_ResetPlaylistEntries", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _ResetPlaylistEntries( IntPtr self );
#endregion
internal bool ResetPlaylistEntries()
{
var returnValue = _ResetPlaylistEntries( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_SetPlaylistEntry", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetPlaylistEntry( IntPtr self, int nID, int nPosition, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchEntryText );
#endregion
internal bool SetPlaylistEntry( int nID, int nPosition, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchEntryText )
{
var returnValue = _SetPlaylistEntry( Self, nID, nPosition, pchEntryText );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_SetCurrentPlaylistEntry", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _SetCurrentPlaylistEntry( IntPtr self, int nID );
#endregion
internal bool SetCurrentPlaylistEntry( int nID )
{
var returnValue = _SetCurrentPlaylistEntry( Self, nID );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamMusicRemote_PlaylistDidChange", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _PlaylistDidChange( IntPtr self );
#endregion
internal bool PlaylistDidChange()
{
var returnValue = _PlaylistDidChange( Self );
return returnValue;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>ConversionValueRuleSet</c> resource.</summary>
public sealed partial class ConversionValueRuleSetName : gax::IResourceName, sys::IEquatable<ConversionValueRuleSetName>
{
/// <summary>The possible contents of <see cref="ConversionValueRuleSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
CustomerConversionValueRuleSet = 1,
}
private static gax::PathTemplate s_customerConversionValueRuleSet = new gax::PathTemplate("customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}");
/// <summary>Creates a <see cref="ConversionValueRuleSetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ConversionValueRuleSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ConversionValueRuleSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ConversionValueRuleSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ConversionValueRuleSetName"/> with the pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="ConversionValueRuleSetName"/> constructed from the provided ids.
/// </returns>
public static ConversionValueRuleSetName FromCustomerConversionValueRuleSet(string customerId, string conversionValueRuleSetId) =>
new ConversionValueRuleSetName(ResourceNameType.CustomerConversionValueRuleSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleSetId, nameof(conversionValueRuleSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </returns>
public static string Format(string customerId, string conversionValueRuleSetId) =>
FormatCustomerConversionValueRuleSet(customerId, conversionValueRuleSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="ConversionValueRuleSetName"/> with pattern
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>.
/// </returns>
public static string FormatCustomerConversionValueRuleSet(string customerId, string conversionValueRuleSetId) =>
s_customerConversionValueRuleSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleSetId, nameof(conversionValueRuleSetId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ConversionValueRuleSetName"/> if successful.</returns>
public static ConversionValueRuleSetName Parse(string conversionValueRuleSetName) =>
Parse(conversionValueRuleSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ConversionValueRuleSetName"/> if successful.</returns>
public static ConversionValueRuleSetName Parse(string conversionValueRuleSetName, bool allowUnparsed) =>
TryParse(conversionValueRuleSetName, allowUnparsed, out ConversionValueRuleSetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConversionValueRuleSetName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string conversionValueRuleSetName, out ConversionValueRuleSetName result) =>
TryParse(conversionValueRuleSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ConversionValueRuleSetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="conversionValueRuleSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ConversionValueRuleSetName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string conversionValueRuleSetName, bool allowUnparsed, out ConversionValueRuleSetName result)
{
gax::GaxPreconditions.CheckNotNull(conversionValueRuleSetName, nameof(conversionValueRuleSetName));
gax::TemplatedResourceName resourceName;
if (s_customerConversionValueRuleSet.TryParseName(conversionValueRuleSetName, out resourceName))
{
result = FromCustomerConversionValueRuleSet(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(conversionValueRuleSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ConversionValueRuleSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversionValueRuleSetId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ConversionValueRuleSetId = conversionValueRuleSetId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ConversionValueRuleSetName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/conversionValueRuleSets/{conversion_value_rule_set_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="conversionValueRuleSetId">
/// The <c>ConversionValueRuleSet</c> ID. Must not be <c>null</c> or empty.
/// </param>
public ConversionValueRuleSetName(string customerId, string conversionValueRuleSetId) : this(ResourceNameType.CustomerConversionValueRuleSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleSetId, nameof(conversionValueRuleSetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>ConversionValueRuleSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string ConversionValueRuleSetId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerConversionValueRuleSet: return s_customerConversionValueRuleSet.Expand(CustomerId, ConversionValueRuleSetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ConversionValueRuleSetName);
/// <inheritdoc/>
public bool Equals(ConversionValueRuleSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ConversionValueRuleSetName a, ConversionValueRuleSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ConversionValueRuleSetName a, ConversionValueRuleSetName b) => !(a == b);
}
public partial class ConversionValueRuleSet
{
/// <summary>
/// <see cref="ConversionValueRuleSetName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal ConversionValueRuleSetName ResourceNameAsConversionValueRuleSetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ConversionValueRuleSetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="ConversionValueRuleName"/>-typed view over the <see cref="ConversionValueRules"/> resource name
/// property.
/// </summary>
internal gax::ResourceNameList<ConversionValueRuleName> ConversionValueRulesAsConversionValueRuleNames
{
get => new gax::ResourceNameList<ConversionValueRuleName>(ConversionValueRules, s => string.IsNullOrEmpty(s) ? null : ConversionValueRuleName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="CustomerName"/>-typed view over the <see cref="OwnerCustomer"/> resource name property.
/// </summary>
internal CustomerName OwnerCustomerAsCustomerName
{
get => string.IsNullOrEmpty(OwnerCustomer) ? null : CustomerName.Parse(OwnerCustomer, allowUnparsed: true);
set => OwnerCustomer = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Test.Cryptography;
namespace System.Security.Cryptography.X509Certificates.Tests
{
internal static class TestData
{
public static byte[] MsCertificate = (
"308204ec308203d4a003020102021333000000b011af0a8bd03b9fdd00010000" +
"00b0300d06092a864886f70d01010505003079310b3009060355040613025553" +
"311330110603550408130a57617368696e67746f6e3110300e06035504071307" +
"5265646d6f6e64311e301c060355040a13154d6963726f736f667420436f7270" +
"6f726174696f6e312330210603550403131a4d6963726f736f667420436f6465" +
"205369676e696e6720504341301e170d3133303132343232333333395a170d31" +
"34303432343232333333395a308183310b300906035504061302555331133011" +
"0603550408130a57617368696e67746f6e3110300e060355040713075265646d" +
"6f6e64311e301c060355040a13154d6963726f736f667420436f72706f726174" +
"696f6e310d300b060355040b13044d4f5052311e301c060355040313154d6963" +
"726f736f667420436f72706f726174696f6e30820122300d06092a864886f70d" +
"01010105000382010f003082010a0282010100e8af5ca2200df8287cbc057b7f" +
"adeeeb76ac28533f3adb407db38e33e6573fa551153454a5cfb48ba93fa837e1" +
"2d50ed35164eef4d7adb137688b02cf0595ca9ebe1d72975e41b85279bf3f82d" +
"9e41362b0b40fbbe3bbab95c759316524bca33c537b0f3eb7ea8f541155c0865" +
"1d2137f02cba220b10b1109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5" +
"c90a21e2aae3013647fd2f826a8103f5a935dc94579dfb4bd40e82db388f12fe" +
"e3d67a748864e162c4252e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a6" +
"79b5b6dbcef9707b280184b82a29cfbfa90505e1e00f714dfdad5c238329ebc7" +
"c54ac8e82784d37ec6430b950005b14f6571c50203010001a38201603082015c" +
"30130603551d25040c300a06082b06010505070303301d0603551d0e04160414" +
"5971a65a334dda980780ff841ebe87f9723241f230510603551d11044a3048a4" +
"463044310d300b060355040b13044d4f5052313330310603550405132a333135" +
"39352b34666166306237312d616433372d346161332d613637312d3736626330" +
"35323334346164301f0603551d23041830168014cb11e8cad2b4165801c9372e" +
"331616b94c9a0a1f30560603551d1f044f304d304ba049a0478645687474703a" +
"2f2f63726c2e6d6963726f736f66742e636f6d2f706b692f63726c2f70726f64" +
"756374732f4d6963436f645369675043415f30382d33312d323031302e63726c" +
"305a06082b06010505070101044e304c304a06082b06010505073002863e6874" +
"74703a2f2f7777772e6d6963726f736f66742e636f6d2f706b692f6365727473" +
"2f4d6963436f645369675043415f30382d33312d323031302e637274300d0609" +
"2a864886f70d0101050500038201010031d76e2a12573381d59dc6ebf93ad444" +
"4d089eee5edf6a5bb779cf029cbc76689e90a19c0bc37fa28cf14dba9539fb0d" +
"e0e19bf45d240f1b8d88153a7cdbadceb3c96cba392c457d24115426300d0dff" +
"47ea0307e5e4665d2c7b9d1da910fa1cb074f24f696b9ea92484daed96a0df73" +
"a4ef6a1aac4b629ef17cc0147f48cd4db244f9f03c936d42d8e87ce617a09b68" +
"680928f90297ef1103ba6752adc1e9b373a6d263cd4ae23ee4f34efdffa1e0bb" +
"02133b5d20de553fa3ae9040313875285e04a9466de6f57a7940bd1fcde845d5" +
"aee25d3ef575c7e6666360ccd59a84878d2430f7ef34d0631db142674a0e4bbf" +
"3a0eefb6953aa738e4259208a6886682").HexToByteArray();
public static readonly byte[] MsCertificatePemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN CERTIFICATE-----
MIIE7DCCA9SgAwIBAgITMwAAALARrwqL0Duf3QABAAAAsDANBgkqhkiG9w0BAQUF
ADB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMH
UmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSMwIQYDVQQD
ExpNaWNyb3NvZnQgQ29kZSBTaWduaW5nIFBDQTAeFw0xMzAxMjQyMjMzMzlaFw0x
NDA0MjQyMjMzMzlaMIGDMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv
bjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0
aW9uMQ0wCwYDVQQLEwRNT1BSMR4wHAYDVQQDExVNaWNyb3NvZnQgQ29ycG9yYXRp
b24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDor1yiIA34KHy8BXt/
re7rdqwoUz8620B9s44z5lc/pVEVNFSlz7SLqT+oN+EtUO01Fk7vTXrbE3aIsCzw
WVyp6+HXKXXkG4Unm/P4LZ5BNisLQPu+O7q5XHWTFlJLyjPFN7Dz636o9UEVXAhl
HSE38Cy6IgsQsRCddyKFhHxPuRuQsPWj/ov0DJpOoPXJCiHiquMBNkf9L4JqgQP1
qTXclFed+0vUDoLbOI8S/uPWenSIZOFixCUuKq6dGB8OHrbCryS0DlC83hyTXEmm
ebW22875cHsoAYS4KinPv6kFBeHgD3FN/a1cI4Mp68fFSsjoJ4TTfsZDC5UABbFP
ZXHFAgMBAAGjggFgMIIBXDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQU
WXGmWjNN2pgHgP+EHr6H+XIyQfIwUQYDVR0RBEowSKRGMEQxDTALBgNVBAsTBE1P
UFIxMzAxBgNVBAUTKjMxNTk1KzRmYWYwYjcxLWFkMzctNGFhMy1hNjcxLTc2YmMw
NTIzNDRhZDAfBgNVHSMEGDAWgBTLEejK0rQWWAHJNy4zFha5TJoKHzBWBgNVHR8E
TzBNMEugSaBHhkVodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9k
dWN0cy9NaWNDb2RTaWdQQ0FfMDgtMzEtMjAxMC5jcmwwWgYIKwYBBQUHAQEETjBM
MEoGCCsGAQUFBzAChj5odHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRz
L01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEwLmNydDANBgkqhkiG9w0BAQUFAAOCAQEA
MdduKhJXM4HVncbr+TrURE0Inu5e32pbt3nPApy8dmiekKGcC8N/oozxTbqVOfsN
4OGb9F0kDxuNiBU6fNutzrPJbLo5LEV9JBFUJjANDf9H6gMH5eRmXSx7nR2pEPoc
sHTyT2lrnqkkhNrtlqDfc6TvahqsS2Ke8XzAFH9IzU2yRPnwPJNtQtjofOYXoJto
aAko+QKX7xEDumdSrcHps3Om0mPNSuI+5PNO/f+h4LsCEztdIN5VP6OukEAxOHUo
XgSpRm3m9Xp5QL0fzehF1a7iXT71dcfmZmNgzNWahIeNJDD37zTQYx2xQmdKDku/
Og7vtpU6pzjkJZIIpohmgg==
-----END CERTIFICATE-----
");
public const string PfxDataPassword = "12345";
public static readonly byte[] PfxData = (
"3082063A020103308205F606092A864886F70D010701A08205E7048205E33082" +
"05DF3082035806092A864886F70D010701A08203490482034530820341308203" +
"3D060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" +
"010C0103300E04085052002C7DA2C2A6020207D0048202907D485E3BFC6E6457" +
"C811394C145D0E8A18325646854E4FF0097BC5A98547F5AD616C8EFDA8505AA8" +
"7564ED4800A3139759497C60C6688B51F376ACAE906429C8771CB1428226B68A" +
"6297207BCC9DD7F9563478DD83880AAB2304B545759B2275305DF4EFF9FAC24A" +
"3CC9D3B2D672EFE45D8F48E24A16506C1D7566FC6D1B269FBF201B3AC3309D3E" +
"BC6FD606257A7A707AA2F790EA3FE7A94A51138540C5319010CBA6DE9FB9D85F" +
"CDC78DA60E33DF2F21C46FB9A8554B4F82E0A6EDBA4DB5585D77D331D35DAAED" +
"51B6A5A3E000A299880FB799182C8CA3004B7837A9FEB8BFC76778089993F3D1" +
"1D70233608AF7C50722D680623D2BF54BD4B1E7A604184D9F44E0AF8099FFA47" +
"1E5536E7902793829DB9902DDB61264A62962950AD274EA516B2D44BE9036530" +
"016E607B73F341AEEFED2211F6330364738B435B0D2ED6C57747F6C8230A053F" +
"78C4DD65DB83B26C6A47836A6CBBAB92CBB262C6FB6D08632B4457F5FA8EABFA" +
"65DB34157E1D301E9085CC443582CDD15404314872748545EB3FC3C574882655" +
"8C9A85F966E315775BBE9DA34D1E8B6DADC3C9E120C6D6A2E1CFFE4EB014C3CE" +
"FBC19356CE33DAC60F93D67A4DE247B0DAE13CD8B8C9F15604CC0EC9968E3AD7" +
"F57C9F53C45E2ECB0A0945EC0BA04BAA15B48D8596EDC9F5FE9165A5D21949FB" +
"5FE30A920AD2C0F78799F6443C300629B8CA4DCA19B9DBF1E27AAB7B12271228" +
"119A95C9822BE6439414BEEAE24002B46EB97E030E18BD810ADE0BCF4213A355" +
"038B56584B2FBCC3F5EA215D0CF667FFD823EA03AB62C3B193DFB4450AABB50B" +
"AF306E8088EE7384FA2FDFF03E0DD7ACD61832223E806A94D46E196462522808" +
"3163F1CAF333FDBBE2D54CA86968867CE0B6DD5E5B7F0633C6FAB4A19CC14F64" +
"5EC14D0B1436F7623174301306092A864886F70D010915310604040100000030" +
"5D06092B060104018237110131501E4E004D006900630072006F0073006F0066" +
"00740020005300740072006F006E0067002000430072007900700074006F0067" +
"007200610070006800690063002000500072006F007600690064006500723082" +
"027F06092A864886F70D010706A08202703082026C0201003082026506092A86" +
"4886F70D010701301C060A2A864886F70D010C0106300E0408E0C117E67A75D8" +
"EB020207D080820238292882408B31826F0DC635F9BBE7C199A48A3B4FEFC729" +
"DBF95508D6A7D04805A8DD612427F93124F522AC7D3C6F4DDB74D937F57823B5" +
"B1E8CFAE4ECE4A1FFFD801558D77BA31985AA7F747D834CBE84464EF777718C9" +
"865C819D6C9DAA0FA25E2A2A80B3F2AAA67D40E382EB084CCA85E314EA40C3EF" +
"3ED1593904D7A16F37807C99AF06C917093F6C5AAEBB12A6C58C9956D4FBBDDE" +
"1F1E389989C36E19DD38D4B978D6F47131E458AB68E237E40CB6A87F21C8773D" +
"E845780B50995A51F041106F47C740B3BD946038984F1AC9E91230616480962F" +
"11B0683F8802173C596C4BD554642F51A76F9DFFF9053DEF7B3C3F759FC7EEAC" +
"3F2386106C4B8CB669589E004FB235F0357EA5CF0B5A6FC78A6D941A3AE44AF7" +
"B601B59D15CD1EC61BCCC481FBB83EAE2F83153B41E71EF76A2814AB59347F11" +
"6AB3E9C1621668A573013D34D13D3854E604286733C6BAD0F511D7F8FD6356F7" +
"C3198D0CB771AF27F4B5A3C3B571FDD083FD68A9A1EEA783152C436F7513613A" +
"7E399A1DA48D7E55DB7504DC47D1145DF8D7B6D32EAA4CCEE06F98BB3DDA2CC0" +
"D0564A962F86DFB122E4F7E2ED6F1B509C58D4A3B2D0A68788F7E313AECFBDEF" +
"456C31B96FC13586E02AEB65807ED83BB0CB7C28F157BC95C9C593C919469153" +
"9AE3C620ED1D4D4AF0177F6B9483A5341D7B084BC5B425AFB658168EE2D8FB2B" +
"FAB07A3BA061687A5ECD1F8DA9001DD3E7BE793923094ABB0F2CF4D24CB071B9" +
"E568B18336BB4DC541352C9785C48D0F0E53066EB2009EFCB3E5644ED12252C1" +
"BC303B301F300706052B0E03021A04144DEAB829B57A3156AEBC8239C0E7E884" +
"EFD96E680414E147930B932899741C92D7652268938770254A2B020207D0").HexToByteArray();
public static byte[] StoreSavedAsPfxData = (
"3082070406092a864886f70d010702a08206f5308206f10201013100300b0609" +
"2a864886f70d010701a08206d9308201e530820152a0030201020210d5b5bc1c" +
"458a558845bff51cb4dff31c300906052b0e03021d05003011310f300d060355" +
"040313064d794e616d65301e170d3130303430313038303030305a170d313130" +
"3430313038303030305a3011310f300d060355040313064d794e616d6530819f" +
"300d06092a864886f70d010101050003818d0030818902818100b11e30ea8742" +
"4a371e30227e933ce6be0e65ff1c189d0d888ec8ff13aa7b42b68056128322b2" +
"1f2b6976609b62b6bc4cf2e55ff5ae64e9b68c78a3c2dacc916a1bc7322dd353" +
"b32898675cfb5b298b176d978b1f12313e3d865bc53465a11cca106870a4b5d5" +
"0a2c410938240e92b64902baea23eb093d9599e9e372e48336730203010001a3" +
"46304430420603551d01043b3039801024859ebf125e76af3f0d7979b4ac7a96" +
"a1133011310f300d060355040313064d794e616d658210d5b5bc1c458a558845" +
"bff51cb4dff31c300906052b0e03021d0500038181009bf6e2cf830ed485b86d" +
"6b9e8dffdcd65efc7ec145cb9348923710666791fcfa3ab59d689ffd7234b787" +
"2611c5c23e5e0714531abadb5de492d2c736e1c929e648a65cc9eb63cd84e57b" +
"5909dd5ddf5dbbba4a6498b9ca225b6e368b94913bfc24de6b2bd9a26b192b95" +
"7304b89531e902ffc91b54b237bb228be8afcda26476308204ec308203d4a003" +
"020102021333000000b011af0a8bd03b9fdd0001000000b0300d06092a864886" +
"f70d01010505003079310b300906035504061302555331133011060355040813" +
"0a57617368696e67746f6e3110300e060355040713075265646d6f6e64311e30" +
"1c060355040a13154d6963726f736f667420436f72706f726174696f6e312330" +
"210603550403131a4d6963726f736f667420436f6465205369676e696e672050" +
"4341301e170d3133303132343232333333395a170d3134303432343232333333" +
"395a308183310b3009060355040613025553311330110603550408130a576173" +
"68696e67746f6e3110300e060355040713075265646d6f6e64311e301c060355" +
"040a13154d6963726f736f667420436f72706f726174696f6e310d300b060355" +
"040b13044d4f5052311e301c060355040313154d6963726f736f667420436f72" +
"706f726174696f6e30820122300d06092a864886f70d01010105000382010f00" +
"3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" +
"407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" +
"137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" +
"b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" +
"109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" +
"2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" +
"2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" +
"84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" +
"0b950005b14f6571c50203010001a38201603082015c30130603551d25040c30" +
"0a06082b06010505070303301d0603551d0e041604145971a65a334dda980780" +
"ff841ebe87f9723241f230510603551d11044a3048a4463044310d300b060355" +
"040b13044d4f5052313330310603550405132a33313539352b34666166306237" +
"312d616433372d346161332d613637312d373662633035323334346164301f06" +
"03551d23041830168014cb11e8cad2b4165801c9372e331616b94c9a0a1f3056" +
"0603551d1f044f304d304ba049a0478645687474703a2f2f63726c2e6d696372" +
"6f736f66742e636f6d2f706b692f63726c2f70726f64756374732f4d6963436f" +
"645369675043415f30382d33312d323031302e63726c305a06082b0601050507" +
"0101044e304c304a06082b06010505073002863e687474703a2f2f7777772e6d" +
"6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f64536967" +
"5043415f30382d33312d323031302e637274300d06092a864886f70d01010505" +
"00038201010031d76e2a12573381d59dc6ebf93ad4444d089eee5edf6a5bb779" +
"cf029cbc76689e90a19c0bc37fa28cf14dba9539fb0de0e19bf45d240f1b8d88" +
"153a7cdbadceb3c96cba392c457d24115426300d0dff47ea0307e5e4665d2c7b" +
"9d1da910fa1cb074f24f696b9ea92484daed96a0df73a4ef6a1aac4b629ef17c" +
"c0147f48cd4db244f9f03c936d42d8e87ce617a09b68680928f90297ef1103ba" +
"6752adc1e9b373a6d263cd4ae23ee4f34efdffa1e0bb02133b5d20de553fa3ae" +
"9040313875285e04a9466de6f57a7940bd1fcde845d5aee25d3ef575c7e66663" +
"60ccd59a84878d2430f7ef34d0631db142674a0e4bbf3a0eefb6953aa738e425" +
"9208a68866823100").HexToByteArray();
public static byte[] StoreSavedAsCerData = (
"308201e530820152a0030201020210d5b5bc1c458a558845bff51cb4dff31c30" +
"0906052b0e03021d05003011310f300d060355040313064d794e616d65301e17" +
"0d3130303430313038303030305a170d3131303430313038303030305a301131" +
"0f300d060355040313064d794e616d6530819f300d06092a864886f70d010101" +
"050003818d0030818902818100b11e30ea87424a371e30227e933ce6be0e65ff" +
"1c189d0d888ec8ff13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55f" +
"f5ae64e9b68c78a3c2dacc916a1bc7322dd353b32898675cfb5b298b176d978b" +
"1f12313e3d865bc53465a11cca106870a4b5d50a2c410938240e92b64902baea" +
"23eb093d9599e9e372e48336730203010001a346304430420603551d01043b30" +
"39801024859ebf125e76af3f0d7979b4ac7a96a1133011310f300d0603550403" +
"13064d794e616d658210d5b5bc1c458a558845bff51cb4dff31c300906052b0e" +
"03021d0500038181009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb93" +
"48923710666791fcfa3ab59d689ffd7234b7872611c5c23e5e0714531abadb5d" +
"e492d2c736e1c929e648a65cc9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca" +
"225b6e368b94913bfc24de6b2bd9a26b192b957304b89531e902ffc91b54b237" +
"bb228be8afcda26476").HexToByteArray();
public static byte[] StoreSavedAsSerializedCerData = (
"0200000001000000bc0000001c0000006c000000010000000000000000000000" +
"00000000020000007b00370037004500420044003000320044002d0044003800" +
"440045002d0034003700350041002d0038003800360037002d00440032003000" +
"4200300030003600340045003400390046007d00000000004d00690063007200" +
"6f0073006f006600740020005300740072006f006e0067002000430072007900" +
"700074006f0067007200610070006800690063002000500072006f0076006900" +
"64006500720000002000000001000000e9010000308201e530820152a0030201" +
"020210d5b5bc1c458a558845bff51cb4dff31c300906052b0e03021d05003011" +
"310f300d060355040313064d794e616d65301e170d3130303430313038303030" +
"305a170d3131303430313038303030305a3011310f300d060355040313064d79" +
"4e616d6530819f300d06092a864886f70d010101050003818d00308189028181" +
"00b11e30ea87424a371e30227e933ce6be0e65ff1c189d0d888ec8ff13aa7b42" +
"b68056128322b21f2b6976609b62b6bc4cf2e55ff5ae64e9b68c78a3c2dacc91" +
"6a1bc7322dd353b32898675cfb5b298b176d978b1f12313e3d865bc53465a11c" +
"ca106870a4b5d50a2c410938240e92b64902baea23eb093d9599e9e372e48336" +
"730203010001a346304430420603551d01043b3039801024859ebf125e76af3f" +
"0d7979b4ac7a96a1133011310f300d060355040313064d794e616d658210d5b5" +
"bc1c458a558845bff51cb4dff31c300906052b0e03021d0500038181009bf6e2" +
"cf830ed485b86d6b9e8dffdcd65efc7ec145cb9348923710666791fcfa3ab59d" +
"689ffd7234b7872611c5c23e5e0714531abadb5de492d2c736e1c929e648a65c" +
"c9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca225b6e368b94913bfc24de6b" +
"2bd9a26b192b957304b89531e902ffc91b54b237bb228be8afcda26476").HexToByteArray();
public static byte[] StoreSavedAsSerializedStoreData = (
"00000000434552540200000001000000bc0000001c0000006c00000001000000" +
"000000000000000000000000020000007b003700370045004200440030003200" +
"44002d0044003800440045002d0034003700350041002d003800380036003700" +
"2d004400320030004200300030003600340045003400390046007d0000000000" +
"4d006900630072006f0073006f006600740020005300740072006f006e006700" +
"2000430072007900700074006f00670072006100700068006900630020005000" +
"72006f007600690064006500720000002000000001000000e9010000308201e5" +
"30820152a0030201020210d5b5bc1c458a558845bff51cb4dff31c300906052b" +
"0e03021d05003011310f300d060355040313064d794e616d65301e170d313030" +
"3430313038303030305a170d3131303430313038303030305a3011310f300d06" +
"0355040313064d794e616d6530819f300d06092a864886f70d01010105000381" +
"8d0030818902818100b11e30ea87424a371e30227e933ce6be0e65ff1c189d0d" +
"888ec8ff13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55ff5ae64e9" +
"b68c78a3c2dacc916a1bc7322dd353b32898675cfb5b298b176d978b1f12313e" +
"3d865bc53465a11cca106870a4b5d50a2c410938240e92b64902baea23eb093d" +
"9599e9e372e48336730203010001a346304430420603551d01043b3039801024" +
"859ebf125e76af3f0d7979b4ac7a96a1133011310f300d060355040313064d79" +
"4e616d658210d5b5bc1c458a558845bff51cb4dff31c300906052b0e03021d05" +
"00038181009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb9348923710" +
"666791fcfa3ab59d689ffd7234b7872611c5c23e5e0714531abadb5de492d2c7" +
"36e1c929e648a65cc9eb63cd84e57b5909dd5ddf5dbbba4a6498b9ca225b6e36" +
"8b94913bfc24de6b2bd9a26b192b957304b89531e902ffc91b54b237bb228be8" +
"afcda264762000000001000000f0040000308204ec308203d4a0030201020213" +
"33000000b011af0a8bd03b9fdd0001000000b0300d06092a864886f70d010105" +
"05003079310b3009060355040613025553311330110603550408130a57617368" +
"696e67746f6e3110300e060355040713075265646d6f6e64311e301c06035504" +
"0a13154d6963726f736f667420436f72706f726174696f6e3123302106035504" +
"03131a4d6963726f736f667420436f6465205369676e696e6720504341301e17" +
"0d3133303132343232333333395a170d3134303432343232333333395a308183" +
"310b3009060355040613025553311330110603550408130a57617368696e6774" +
"6f6e3110300e060355040713075265646d6f6e64311e301c060355040a13154d" +
"6963726f736f667420436f72706f726174696f6e310d300b060355040b13044d" +
"4f5052311e301c060355040313154d6963726f736f667420436f72706f726174" +
"696f6e30820122300d06092a864886f70d01010105000382010f003082010a02" +
"82010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb407db38e33" +
"e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb137688b02c" +
"f0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bbab95c759316" +
"524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1109d772285" +
"847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd2f826a8103" +
"f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c4252e2aae9d18" +
"1f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b280184b82a29cf" +
"bfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec6430b950005b1" +
"4f6571c50203010001a38201603082015c30130603551d25040c300a06082b06" +
"010505070303301d0603551d0e041604145971a65a334dda980780ff841ebe87" +
"f9723241f230510603551d11044a3048a4463044310d300b060355040b13044d" +
"4f5052313330310603550405132a33313539352b34666166306237312d616433" +
"372d346161332d613637312d373662633035323334346164301f0603551d2304" +
"1830168014cb11e8cad2b4165801c9372e331616b94c9a0a1f30560603551d1f" +
"044f304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f6674" +
"2e636f6d2f706b692f63726c2f70726f64756374732f4d6963436f6453696750" +
"43415f30382d33312d323031302e63726c305a06082b06010505070101044e30" +
"4c304a06082b06010505073002863e687474703a2f2f7777772e6d6963726f73" +
"6f66742e636f6d2f706b692f63657274732f4d6963436f645369675043415f30" +
"382d33312d323031302e637274300d06092a864886f70d010105050003820101" +
"0031d76e2a12573381d59dc6ebf93ad4444d089eee5edf6a5bb779cf029cbc76" +
"689e90a19c0bc37fa28cf14dba9539fb0de0e19bf45d240f1b8d88153a7cdbad" +
"ceb3c96cba392c457d24115426300d0dff47ea0307e5e4665d2c7b9d1da910fa" +
"1cb074f24f696b9ea92484daed96a0df73a4ef6a1aac4b629ef17cc0147f48cd" +
"4db244f9f03c936d42d8e87ce617a09b68680928f90297ef1103ba6752adc1e9" +
"b373a6d263cd4ae23ee4f34efdffa1e0bb02133b5d20de553fa3ae9040313875" +
"285e04a9466de6f57a7940bd1fcde845d5aee25d3ef575c7e6666360ccd59a84" +
"878d2430f7ef34d0631db142674a0e4bbf3a0eefb6953aa738e4259208a68866" +
"82000000000000000000000000").HexToByteArray();
public static byte[] DssCer = (
"3082025d3082021da00302010202101e9ae1e91e07de8640ac7af21ac22e8030" +
"0906072a8648ce380403300e310c300a06035504031303466f6f301e170d3135" +
"303232343232313734375a170d3136303232343232313734375a300e310c300a" +
"06035504031303466f6f308201b73082012c06072a8648ce3804013082011f02" +
"818100871018cc42552d14a5a9286af283f3cfba959b8835ec2180511d0dceb8" +
"b979285708c800fc10cb15337a4ac1a48ed31394072015a7a6b525986b49e5e1" +
"139737a794833c1aa1e0eaaa7e9d4efeb1e37a65dbc79f51269ba41e8f0763aa" +
"613e29c81c3b977aeeb3d3c3f6feb25c270cdcb6aee8cd205928dfb33c44d2f2" +
"dbe819021500e241edcf37c1c0e20aadb7b4e8ff7aa8fde4e75d02818100859b" +
"5aeb351cf8ad3fabac22ae0350148fd1d55128472691709ec08481584413e9e5" +
"e2f61345043b05d3519d88c021582ccef808af8f4b15bd901a310fefd518af90" +
"aba6f85f6563db47ae214a84d0b7740c9394aa8e3c7bfef1beedd0dafda079bf" +
"75b2ae4edb7480c18b9cdfa22e68a06c0685785f5cfb09c2b80b1d05431d0381" +
"8400028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371e" +
"bf07bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a" +
"0707ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638bec" +
"ca7786312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3" +
"f2f8bf0963300906072a8648ce380403032f00302c021461f6d143a47a4f7e0e" +
"0ef9848b7f83eacbf83ffd021420e2ac47e656874633e01b0d207a99280c1127" +
"01").HexToByteArray();
public static byte[] CertWithPolicies = (
"308201f33082015ca0030201020210134fb7082cf69bbb4930bfc8e1ca446130" +
"0d06092a864886f70d0101050500300e310c300a06035504031303466f6f301e" +
"170d3135303330313232343735385a170d3136303330313034343735385a300e" +
"310c300a06035504031303466f6f30819f300d06092a864886f70d0101010500" +
"03818d0030818902818100c252d52fb96658ddbb7d19dd9caaf203ec0376f77c" +
"3012bd93e14bb22a6ff2b5ce8060a197e3fd8289fbff826746baae0db8d68b47" +
"a1cf13678717d7db9a16dab028927173a3e843b3a7df8c5a4ff675957ea20703" +
"6389a60a83d643108bd1293e2135a672a1cff10b7d5b3c78ab44d35e20ca6a5c" +
"5b6f714c5bfd66ed4307070203010001a3523050301b06092b06010401823714" +
"02040e1e0c00480065006c006c006f0000301a06092b0601040182371507040d" +
"300b060357080902010302010230150603551d20040e300c3004060262133004" +
"06027021300d06092a864886f70d0101050500038181001be04e59fbea63acfb" +
"c8b6fd3d02dd7442532344cfbc124e924c0bacf23865e4ce2f442ad60ae457d8" +
"4f7a1f05d50fb867c20e778e412a25237054555669ced01c1ce1ba8e8e57510f" +
"73e1167c920f78aa5415dc5281f0c761fb25bb1ebc707bc003dd90911e649915" +
"918cfe4f3176972f8afdc1cccd9705e7fb307a0c17d273").HexToByteArray();
public static byte[] CertWithTemplateData = (
"308201dc30820145a00302010202105101b8242daf6cae4c53bac68a948b0130" +
"0d06092a864886f70d0101050500300e310c300a06035504031303466f6f301e" +
"170d3135303330313232333133395a170d3136303330313034333133395a300e" +
"310c300a06035504031303466f6f30819f300d06092a864886f70d0101010500" +
"03818d0030818902818100a6dcff50bd1fe420301fea5fa56be93a7a53f2599c" +
"e453cf3422bec797bac0ed78a03090a3754569e6494bcd585ac16a5ea5086344" +
"3f25521085ca09580579cf0b46bd6e50015319fba5d2bd3724c53b20cdddf604" +
"74bd7ef426aead9ca5ffea275a4b2b1b6f87c203ab8783559b75e319722886fb" +
"eb784f5f06823906b2a9950203010001a33b3039301b06092b06010401823714" +
"02040e1e0c00480065006c006c006f0000301a06092b0601040182371507040d" +
"300b0603570809020103020102300d06092a864886f70d010105050003818100" +
"962594da079523c26e2d3fc573fd17189ca33bedbeb2c38c92508fc2a865973b" +
"e85ba686f765101aea0a0391b22fcfa6c0760eece91a0eb75501bf6871553f8d" +
"6b089cf2ea63c872e0b4a178795b71826c4569857b45994977895e506dfb8075" +
"ed1b1096987f2c8f65f2d6bbc788b1847b6ba13bee17ef6cb9c6a3392e13003f").HexToByteArray();
public static byte[] ComplexNameInfoCert = (
"308204BE30820427A00302010202080123456789ABCDEF300D06092A864886F70" +
"D01010505003081A43110300E06035504061307436F756E747279310E300C0603" +
"550408130553746174653111300F060355040713084C6F63616C6974793111300" +
"F060355040A13084578616D706C654F31123010060355040B13094578616D706C" +
"654F55311E301C06035504031315636E2E6973737565722E6578616D706C652E6" +
"F72673126302406092A864886F70D0109011617697373756572656D61696C4065" +
"78616D706C652E6F7267301E170D3133313131323134313531365A170D3134313" +
"231333135313631375A3081A63110300E06035504061307436F756E747279310E" +
"300C0603550408130553746174653111300F060355040713084C6F63616C69747" +
"93111300F060355040A13084578616D706C654F31123010060355040B13094578" +
"616D706C654F55311F301D06035504031316636E2E7375626A6563742E6578616" +
"D706C652E6F72673127302506092A864886F70D01090116187375626A65637465" +
"6D61696C406578616D706C652E6F7267305C300D06092A864886F70D010101050" +
"0034B003048024100DC6FBBDA0300520DFBC9F046CC865D8876AEAC353807EA84" +
"F58F92FE45EE03C22E970CAF41031D47F97C8A5117C62718482911A8A31B58D92" +
"328BA3CF9E605230203010001A382023730820233300B0603551D0F0404030200" +
"B0301D0603551D250416301406082B0601050507030106082B060105050703023" +
"081FD0603551D120481F53081F28217646E73312E6973737565722E6578616D70" +
"6C652E6F72678217646E73322E6973737565722E6578616D706C652E6F7267811" +
"569616E656D61696C31406578616D706C652E6F7267811569616E656D61696C32" +
"406578616D706C652E6F7267A026060A2B060104018237140203A0180C1669737" +
"375657275706E31406578616D706C652E6F7267A026060A2B0601040182371402" +
"03A0180C1669737375657275706E32406578616D706C652E6F7267861F6874747" +
"03A2F2F757269312E6973737565722E6578616D706C652E6F72672F861F687474" +
"703A2F2F757269322E6973737565722E6578616D706C652E6F72672F308201030" +
"603551D110481FB3081F88218646E73312E7375626A6563742E6578616D706C65" +
"2E6F72678218646E73322E7375626A6563742E6578616D706C652E6F726781157" +
"3616E656D61696C31406578616D706C652E6F7267811573616E656D61696C3240" +
"6578616D706C652E6F7267A027060A2B060104018237140203A0190C177375626" +
"A65637475706E31406578616D706C652E6F7267A027060A2B0601040182371402" +
"03A0190C177375626A65637475706E32406578616D706C652E6F7267862068747" +
"4703A2F2F757269312E7375626A6563742E6578616D706C652E6F72672F862068" +
"7474703A2F2F757269322E7375626A6563742E6578616D706C652E6F72672F300" +
"D06092A864886F70D0101050500038181005CD44A247FF4DFBF2246CC04D7D57C" +
"EF2B6D3A4BC83FF685F6B5196B65AFC8F992BE19B688E53E353EEA8B63951EC40" +
"29008DE8B851E2C30B6BF73F219BCE651E5972E62D651BA171D1DA9831A449D99" +
"AF4E2F4B9EE3FD0991EF305ADDA633C44EB5E4979751280B3F54F9CCD561AC27D" +
"3426BC6FF32E8E1AAF9F7C0150A726B").HexToByteArray();
internal static readonly byte[] MultiPrivateKeyPfx = (
"30820F1602010330820ED606092A864886F70D010701A0820EC704820EC33082" +
"0EBF308206A806092A864886F70D010701A08206990482069530820691308203" +
"4C060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" +
"010C0103300E0408ED42EEFCD77BB2EB020207D00482029048F341D409492D23" +
"D89C0C01DEE7EFFB6715B15D2BB558E9045D635CADFFFEC85C10A4849AB0657D" +
"A17FE7EC578F779BA2DC129FA959664DC7E85DFD13CAC673E487208FE457223A" +
"75732915FFCF3FF70F557B0846D62AD507300EA1770EDED82F7D8E6E75075728" +
"A29D3BF829E75F09EF283A9DDEDDFBABC2E25698DA8C24E4FE34CD43C87554BF" +
"55B1D4B2B0979F399AEC95B781C62CBE9E412329F9A9BCABF20F716A95F1D795" +
"7C379A27587F6BBFA44A0B75FAAC15CA3730629C55E87990EE521BC4657EE2A4" +
"41AF099A226D31707685A89A28EB27CA65512B70DEC09231369AA1A265D4F5C3" +
"C5D17CB11DB54C70AB83EA28F4740D1F79D490F46F926FB267D5F0E4B2FE096D" +
"F161A4FF9E9AC068EFCA999B3ED0A3BD05D8D1E3B67CF51E6A478154B427D87D" +
"C861D0FE2A7A42600483D7B979DC71E8A00D0E805E3BB86E8673234DC1D14987" +
"99272754A5FD5FEC118CF1E2B2A539B604FED5486A4E4D73FAAFF69023263B84" +
"6870D6B8DB01E31CB3A1E4BA3588C1FA81C786745A33B95573D5381AB307827A" +
"549A36AF535FD05E1247BB92C6C6FCB0E76E87F2E4C8136F37C9C19BE3001F59" +
"FC5CB459C620B8E73711BF102D78F665F40E4D1A341370BC1FB7A5567C29359C" +
"FFB938237002904BE59F5605AF96E8A670E2248AB71D27FE63E327077144F095" +
"4CA815E0284E2FF5E1A11B2946276A99B91BF138A79B057436798AF72FD86842" +
"881C5A5ECDA8A961A21553CC930703047F1F45699CEFEF26AAB6B7DBC65C8C62" +
"4CA3286094596F2AA48268B9F5411058613185507332833AFB312D5780CEFF96" +
"6DD05A2CB6E1B252D9656D8E92E63E6C0360F119232E954E11DE777D2DE1C208" +
"F704DDB16E1351F49B42A859E3B6B2D94E1E2B3CD97F06B1123E9CCA049201E6" +
"DB7273C0BDE63CC9318182301306092A864886F70D0109153106040401000000" +
"306B06092B0601040182371101315E1E5C004D006900630072006F0073006F00" +
"66007400200045006E00680061006E0063006500640020004300720079007000" +
"74006F0067007200610070006800690063002000500072006F00760069006400" +
"650072002000760031002E00303082033D060B2A864886F70D010C0A0102A082" +
"02B6308202B2301C060A2A864886F70D010C0103300E04081F85B7ED57F6F934" +
"020207D00482029051A5ADA683AAE06A699761CCF05CB081A4398A7B1256A250" +
"84DBE1115BFAB07A5A9146BC22F2E4223FF25BCA1836AE218691815F20A27A1B" +
"98D1FC78F84AFA7E90A55954EE5BEA47FFA35928A990CB47346767F6F4212DBC" +
"D03FFF1E4D137979006B46B19A9FC3BC9B5036ED6F8582E2007D08DB94B2B576" +
"E154719CAC90DFB6F238CA875FCBEBCF9E9F933E4451E6A2B60C2A0A8A35B5FD" +
"20E5DDA000008DCCE95BBDF604A8F93001F594E402FF8649A6582DE5901EDF9D" +
"ED7D6F9657C5A184D82690EFCFB2F25BFCE02BC56F0FF00595996EBF1BA25475" +
"AB613461280DD641186237D8A3AB257BD6FB1BDC3768B00719D233E0D5FD26D0" +
"8BA6EAB29D732B990FB9423E643E4663ABBA0D8885DD2A276EE02C92778261C7" +
"853F708E2B9AF8D2E96416F676D0191BD24D0C8430BD419049F43C8E2A0C32F8" +
"62207B3DA661577CE5933460D0EF69FAD7323098B55FEF3A9955FE632FBCE845" +
"2BB5F3430AE2A9021EBF756CC7FDFC3E63581C8B0D7AB77760F447F868B59236" +
"14DAA9C36AEBC67DC854B93C38E8A6D3AC11B1EE1D02855CE96ADEB840B626BF" +
"C4B3BFD6487C9073F8A15F55BA945D58AD1636A7AED476EBDB5227A71144BF87" +
"45192EF5CD177818F61836717ED9EB0A83BEEE582ADEDD407035E453083B17E7" +
"C237009D9F04F355CEAB0C0E9AD6F13A3B54459FA05B19E02275FE2588258B63" +
"A125F549D1B44C827CDC94260A02F4A1B42A30E675B9760D876685D6CA05C258" +
"03BDE1F33D325CF6020A662B0F5DCCC8D77B941B273AC462F0D3E050CEB5AEF7" +
"107C45372F7063EF1AB420CA555A6C9BE6E1067966755584346CDDE7C05B6132" +
"E553B11C374DB90B54E5C096062349A1F6CB78A1A2D995C483541750CFA956DE" +
"A0EB3667DE7AD78931C65B6E039B5DE461810B68C344D2723174301306092A86" +
"4886F70D0109153106040402000000305D06092B060104018237110131501E4E" +
"004D006900630072006F0073006F006600740020005300740072006F006E0067" +
"002000430072007900700074006F006700720061007000680069006300200050" +
"0072006F007600690064006500723082080F06092A864886F70D010706A08208" +
"00308207FC020100308207F506092A864886F70D010701301C060A2A864886F7" +
"0D010C0106300E04089ADEE71816BCD023020207D0808207C851AA1EA533FECA" +
"BB26D3846FAEE8DEDB919C29F8B98BBBF785BC306C12A8ACB1437786C4689161" +
"683718BB7E40EB60D9BE0C87056B5ECF20ACCB8BF7F36033B8FCB84ED1474E97" +
"DE0A8709B563B6CF8E69DF4B3F970C92324946723C32D08B7C3A76C871C6B6C8" +
"C56F2D3C4C00B8A809E65A4EB5EFECC011E2B10F0E44ECDA07B325417B249240" +
"80844F6D7F1F6E420346EA85825EB830C7E05A5383412A9502A51F1AC07F315A" +
"DE357F1F9FB2E6427976E78B8FF9CD6C2F9841F2D84658AC8747694EFD0C451B" +
"7AC5B83D5F0780808417501666BB452B53CEB0698162D94541DE181A7968DB13" +
"9F17A1076EDEB70B38B8881DBC6DE2B694070A5A1AA71E4CDFBF7F4D5DBCF166" +
"46768364D3C74FA212E40CBE3BE7C51A74D271164D00E89F997FD418C51A7C2D" +
"73130D7C6FCAA2CA65082CE38BFB753BB30CC71656529E8DBA4C4D0B7E1A79CF" +
"2A052FFEFA2DEE3373115472AFD1F40A80B23AA6141D5CDE0A378FE6210D4EE6" +
"9B8771D3E192FD989AEC14C26EA4845D261B8A45ABC1C8FA305449DCDEDA9882" +
"DD4DDC69B2DE315645FBC3EE52090907E7687A22A63F538E030AB5A5413CA415" +
"F1D70E70CB567261FB892A8B3BAFC72D632CD2FDCC0559E01D5C246CC27C9348" +
"63CCFA52490E1F01D8D2D0AF2587E4D04011140A494FFA3CA42C5F645B94EE30" +
"100DE019B27F66FFC035E49A65B2A3F6CB14EB1E2FFF1F25B5C87481BD8506F3" +
"07E0B042A2C85B99ECA520B4AAC7DFF2B11C1213E4128A01765DDB27B867336B" +
"8CCF148CE738465D46E7A0BEA466CD8BBCCE2E11B16E0F9D24FF2F2D7C9F8527" +
"79ADBB818F87E4AFF7C21A9C2BC20D38209322A34B0B393B187C96583D3D73D9" +
"440F994B2F320D3274848AB7167942179CFF725C2C7556CCC289A5E788C5B863" +
"E6FCDD5E4B87E41458BEB3F43D14C7E5196C38CA36322F8B83064862178D5892" +
"5AEF34F444A31A4FB18431D7D37C65ED519643BC7BD025F801390430022253AA" +
"FCEA670726512C3532EA9F410DB8AA6628CC455E4AB3F478A6981DB9180B7A2A" +
"24B365F37554CE04B08F22B3539D98BF9A1AC623BBF9A08DBEC951E9730C1318" +
"02B2C40750AAE6A791B3219A96A5BAC7AE17A2F7EA02FF66D6FB36C2E6B6AB90" +
"D821A6322BF3E8D82969756A474551DB9EAA8C587FC878F996F5FA1E1C39E983" +
"F164B0A67897EB3755C378807FFDFE964C5C0F290784A08E8C925E85775A9B89" +
"2E278F68C3C1DE72622AC10EA56D88C909EF4AC9F47ED61376737C1E43DBF0F8" +
"9337F0684FA0B96E7A993EC328A6A5FBCDCB809ACBFDAE4ECE192A45480104ED" +
"12820238AB6AC9C88CC9A82585FD29A81A7BC5BC591738A4D49A86D06B4E18BD" +
"C83DFFAA60D8A0D4F70CC63D4E83812CB6753F3744545592D04223793E5B3051" +
"25AAD8807A753D235769BD0280E2DE808B0CEE2B98B0F5562FF9EF68161A6B7E" +
"08C8B105766EBCFC44AC858B1A89E34C099B194A8B24D1DBABC13909EFAF5B9A" +
"9E77AEAF7DD9BE772FA01AB9518EB8864AE6D07D7DD7451797541D2F723BC71A" +
"9C14ED1D811594E2C4A57017D4CB90FD82C195FA9B823DF1E2FFD965E3139F9A" +
"6E8AAC36FA39CFA4C52E85D2A661F9D0D466720C5AB7ECDE968FF51B535B019A" +
"3E9C76058E6F673A49CDD89EA7EC998BDADE71186EA084020A897A328753B72E" +
"213A9D82443F7E34D94508199A2A63E71A12BD441C132201E9A3829B2727F23E" +
"65C519F4DA2C40162A3A501B1BD57568ED75447FEAF8B42988CE25407644BFA0" +
"B76059D275EC994BB336055E271751B32233D79A6E5E3AA700F3803CCA50586D" +
"28934E3D4135FA043AF7DFAB977477283602B1739C4AF40E3856E75C34EB98C6" +
"9A928ADE05B67A679630EFA14E64B2957EDD1AB4EC0B0E7BC38D4851EBF67928" +
"33EACB62FB6C862B089E3066AE5EAAFD2A8B7FC712DE9BD2F488222EEB1FB91B" +
"4E57C2D24092818965621C123280453EDCFA2EC9D9B50AFA437D1ED09EC36FD2" +
"32B169ED301E0DB0BABE562B67130F90EBC85D325A90931A5B5A94736A4B3AAD" +
"B8CA295F59AF7FF08CCFADE5AFBBC2346BC6D78D9E5F470E9BDFF547F2574B10" +
"A48DD9D56B5B03E9E24D65C367B6E342A26A344111A66B1908EDAECD0834930D" +
"A74E1CFE2E4B0636A7C18E51A27AD21992A2DCF466BAACAC227B90B5E61BED79" +
"9C97DEE7EDB33CCAF5DAD7AAD3CACCDE59478CF69AE64B9065FCB436E1993514" +
"C42872DD486ABB75A07A4ED46CDF0E12C0D73FAB83564CF1A814791971EC9C7C" +
"6A08A13CE0453C2C3236C8B2E146D242E3D37A3ECF6C350D0B2AB956CB21057F" +
"DC630750A71C61C66DE3D4A6DB187BEE2F86DEB93E723C5943EA17E699E93555" +
"756920416BD6B267A4CFAC4EE90E96A6419302B4C0A3B9705509CA09EE92F184" +
"FD2817BA09BE29E465909DB6C93E3C1CAF6DC29E1A5838F3C32CCB220235EF82" +
"9CD21D1B3E960518A80D08AE7FF08D3AFB7451C823E9B8D49DAF66F503E4AE53" +
"99FECFC958429D758C06EFF8338BC02457F6FE5053AA3C2F27D360058FD93566" +
"3B55F026B504E39D86E7CE15F04B1C62BBFA0B1CA5E64FF0BD088D94FB1518E0" +
"5B2F40BF9D71C61FC43E3AF8440570C44030F59D14B8858B7B8506B136E7E39B" +
"B04F9AFEAF2FA292D28A8822046CEFDE381F2399370BDE9B97BC700418585C31" +
"E9C353635ADAA6A00A833899D0EDA8F5FFC558D822AEB99C7E35526F5297F333" +
"F9E758D4CD53277316608B1F7DB6AC71309A8542A356D407531BA1D3071BA9DC" +
"02AE91C7DF2561AEBC3845A118B00D21913B4A401DDDC40CE983178EF26C4A41" +
"343037301F300706052B0E03021A041454F0864331D9415EBA750C62FA93C97D" +
"3402E1A40414B610EC75D16EA23BF253AAD061FAC376E1EAF684").HexToByteArray();
internal static readonly byte[] EmptyPfx = (
"304F020103301106092A864886F70D010701A004040230003037301F30070605" +
"2B0E03021A0414822078BC83E955E314BDA908D76D4C5177CC94EB0414711018" +
"F2897A44A90E92779CB655EA11814EC598").HexToByteArray();
internal const string ChainPfxPassword = "test";
internal static readonly byte[] ChainPfxBytes = (
"308213790201033082133506092A864886F70D010701A0821326048213223082" +
"131E3082036706092A864886F70D010701A08203580482035430820350308203" +
"4C060B2A864886F70D010C0A0102A08202B6308202B2301C060A2A864886F70D" +
"010C0103300E040811E8B9808BA6E96C020207D004820290D11DA8713602105C" +
"95792D65BCDFC1B7E3708483BF6CD83008082F89DAE4D003F86081B153BD4D4A" +
"C122E802752DEA29F07D0B7E8F0FB8A762B4CAA63360F9F72CA5846771980A6F" +
"AE2643CD412E6E4A101625371BBD48CC6E2D25191D256B531B06DB7CDAC04DF3" +
"E10C6DC556D5FE907ABF32F2966A561C988A544C19B46DF1BE531906F2CC2263" +
"A301302A857075C7A9C48A395241925C6A369B60D176419D75E320008D5EFD91" +
"5257B160F6CD643953E85F19EBE4E4F72B9B787CF93E95F819D1E43EF01CCFA7" +
"48F0E7260734EA9BC6039BA7557BE6328C0149718A1D9ECF3355082DE697B6CD" +
"630A9C224D831B7786C7E904F1EF2D9D004E0E825DD74AC4A576CDFCA7CECD14" +
"D8E2E6CCAA3A302871AE0BA979BB25559215D771FAE647905878E797BBA9FC62" +
"50F30F518A8008F5A12B35CE526E31032B56EFE5A4121E1E39DC7339A0CE8023" +
"24CDDB7E9497BA37D8B9F8D826F901C52708935B4CA5B0D4D760A9FB33B0442D" +
"008444D5AEB16E5C32187C7038F29160DD1A2D4DB1F9E9A6C035CF5BCED45287" +
"C5DEBAB18743AAF90E77201FEA67485BA3BBCE90CEA4180C447EE588AC19C855" +
"638B9552D47933D2760351174D9C3493DCCE9708B3EFE4BE398BA64051BF52B7" +
"C1DCA44D2D0ED5A6CFB116DDA41995FA99373C254F3F3EBF0F0049F1159A8A76" +
"4CFE9F9CC56C5489DD0F4E924158C9B1B626030CB492489F6AD0A9DCAF3E141D" +
"B4D4821B2D8A384110B6B0B522F62A9DC0C1315A2A73A7F25F96C530E2F700F9" +
"86829A839B944AE6758B8DD1A1E9257F91C160878A255E299C18424EB9983EDE" +
"6DD1C5F4D5453DD5A56AC87DB1EFA0806E3DBFF10A9623FBAA0BAF352F50AB5D" +
"B16AB1171145860D21E2AB20B45C8865B48390A66057DE3A1ABE45EA65376EF6" +
"A96FE36285C2328C318182301306092A864886F70D0109153106040401000000" +
"306B06092B0601040182371101315E1E5C004D006900630072006F0073006F00" +
"66007400200045006E00680061006E0063006500640020004300720079007000" +
"74006F0067007200610070006800690063002000500072006F00760069006400" +
"650072002000760031002E003030820FAF06092A864886F70D010706A0820FA0" +
"30820F9C02010030820F9506092A864886F70D010701301C060A2A864886F70D" +
"010C0106300E0408FFCC41FD8C8414F6020207D080820F68092C6010873CF9EC" +
"54D4676BCFB5FA5F523D03C981CB4A3DC096074E7D04365DDD1E80BF366B8F9E" +
"C4BC056E8CE0CAB516B9C28D17B55E1EB744C43829D0E06217852FA99CCF5496" +
"176DEF9A48967C1EEB4A384DB7783E643E35B5B9A50533B76B8D53581F02086B" +
"782895097860D6CA512514E10D004165C85E561DF5F9AEFD2D89B64F178A7385" +
"C7FA40ECCA899B4B09AE40EE60DAE65B31FF2D1EE204669EFF309A1C7C8D7B07" +
"51AE57276D1D0FB3E8344A801AC5226EA4ED97FCD9399A4EB2E778918B81B17F" +
"E4F65B502595195C79E6B0E37EB8BA36DB12435587E10037D31173285D45304F" +
"6B0056512B3E147D7B5C397709A64E1D74F505D2BD72ED99055161BC57B6200F" +
"2F48CF128229EFBEBFC2707678C0A8C51E3C373271CB4FD8EF34A1345696BF39" +
"50E8CE9831F667D68184F67FE4D30332E24E5C429957694AF23620EA7742F08A" +
"38C9A517A7491083A367B31C60748D697DFA29635548C605F898B64551A48311" +
"CB2A05B1ACA8033128D48E4A5AA263D970FE59FBA49017F29049CF80FFDBD192" +
"95B421FEFF6036B37D2F8DC8A6E36C4F5D707FB05274CC0D8D94AFCC8C6AF546" +
"A0CF49FBD3A67FB6D20B9FE6FDA6321E8ABF5F7CC794CFCC46005DC57A7BAFA8" +
"9954E43230402C8100789F11277D9F05C78DF0509ECFBF3A85114FD35F4F17E7" +
"98D60C0008064E2557BA7BF0B6F8663A6C014E0220693AE29E2AB4BDE5418B61" +
"0889EC02FF5480BD1B344C87D73E6E4DB98C73F881B22C7D298059FE9D7ADA21" +
"92BB6C87F8D25F323A70D234E382F6C332FEF31BB11C37E41903B9A59ADEA5E0" +
"CBAB06DFB835257ABC179A897DEAD9F19B7DF861BE94C655DC73F628E065F921" +
"E5DE98FFCBDF2A54AC01E677E365DD8B932B5BDA761A0032CE2127AB2A2B9DCB" +
"63F1EA8A51FC360AB5BC0AD435F21F9B6842980D795A6734FDB27A4FA8209F73" +
"62DD632FC5FB1F6DE762473D6EA68BFC4BCF983865E66E6D93159EFACC40AB31" +
"AA178806CF893A76CAAA3279C988824A33AF734FAF8E21020D988640FAB6DB10" +
"DF21D93D01776EEA5DAECF695E0C690ED27AD386E6F2D9C9482EA38946008CCB" +
"8F0BD08F9D5058CF8057CA3AD50BB537116A110F3B3ACD9360322DB4D242CC1A" +
"6E15FA2A95192FC65886BE2672031D04A4FB0B1F43AE8476CF82638B61B416AA" +
"97925A0110B736B4D83D7977456F35D947B3D6C9571D8E2DA0E9DEE1E665A844" +
"259C17E01E044FAB898AA170F99157F7B525D524B01BD0710D23A7689A615703" +
"8A0697BD48FFE0253ABD6F862093574B2FC9BA38E1A6EC60AF187F10D79FF71F" +
"7C50E87A07CC0A51099899F7336FE742ADEF25E720B8E0F8781EC7957D414CF5" +
"D44D6998E7E35D2433AFD86442CCA637A1513BE3020B5334614277B3101ED7AD" +
"22AFE50DE99A2AD0E690596C93B881E2962D7E52EE0A770FAF6917106A8FF029" +
"8DF38D6DE926C30834C5D96854FFD053BDB020F7827FB81AD04C8BC2C773B2A5" +
"9FDD6DDF7298A052B3486E03FECA5AA909479DDC7FED972192792888F49C40F3" +
"910140C5BE264D3D07BEBF3275117AF51A80C9F66C7028A2C3155414CF939997" +
"268A1F0AA9059CC3AA7C8BBEF880187E3D1BA8978CBB046E43289A020CAE11B2" +
"5140E2247C15A32CF70C7AA186CBB68B258CF2397D2971F1632F6EBC4846444D" +
"E445673B942F1F110C7D586B6728ECA5B0A62D77696BF25E21ED9196226E5BDA" +
"5A80ECCC785BEEDE917EBC6FFDC2F7124FE8F719B0A937E35E9A720BB9ED72D2" +
"1213E68F058D80E9F8D7162625B35CEC4863BD47BC2D8D80E9B9048811BDD8CB" +
"B70AB215962CD9C40D56AE50B7003630AE26341C6E243B3D12D5933F73F78F15" +
"B014C5B1C36B6C9F410A77CA997931C8BD5CCB94C332F6723D53A4CCC630BFC9" +
"DE96EFA7FDB66FA519F967D6A2DB1B4898BB188DEB98A41FFA7907AE7601DDE2" +
"30E241779A0FDF551FB84D80AAEE3D979F0510CD026D4AE2ED2EFB7468418CCD" +
"B3BD2A29CD7C7DC6419B4637412304D5DA2DC178C0B4669CA8330B9713A812E6" +
"52E812135D807E361167F2A6814CEF2A8A9591EFE2C18216A517473B9C3BF2B7" +
"51E47844893DA30F7DCD4222D1A55D570C1B6F6A99AD1F9213BA8F84C0B14A6D" +
"ED6A26EAFF8F89DF733EEB44117DF0FD357186BA4A15BD5C669F60D6D4C34028" +
"322D4DDF035302131AB6FD08683804CC90C1791182F1AE3281EE69DDBBCC12B8" +
"1E60942FD082286B16BE27DC11E3BB0F18C281E02F3BA66E48C5FD8E8EA3B731" +
"BDB12A4A3F2D9E1F833DD204372003532E1BB11298BDF5092F2959FC439E6BD2" +
"DC6C37E3E775DCBE821B9CBB02E95D84C15E736CEA2FDDAD63F5CD47115B4AD5" +
"5227C2A02886CD2700540EBFD5BF18DC5F94C5874972FD5424FE62B30500B1A8" +
"7521EA3798D11970220B2BE7EFC915FCB7A6B8962F09ABA005861E839813EDA3" +
"E59F70D1F9C277B73928DFFC84A1B7B0F78A8B001164EB0824F2510885CA269F" +
"DCBB2C3AE91BDE91A8BBC648299A3EB626E6F4236CCE79E14C803498562BAD60" +
"28F5B619125F80925A2D3B1A56790795D04F417003A8E9E53320B89D3A3109B1" +
"9BB17B34CC9700DA138FABB5997EC34D0A44A26553153DBCFF8F6A1B5432B150" +
"58F7AD87C6B37537796C95369DAD53BE5543D86D940892F93983153B4031D4FA" +
"B25DAB02C1091ACC1DAE2118ABD26D19435CD4F1A02BDE1896236C174743BCA6" +
"A33FB5429E627EB3FD9F513E81F7BD205B81AAE627C69CF227B043722FA05141" +
"39347D202C9B7B4E55612FC27164F3B5F287F29C443793E22F6ED6D2F353ED82" +
"A9F33EDBA8F5F1B2958F1D6A3943A9614E7411FDBCA597965CD08A8042307081" +
"BAC5A070B467E52D5B91CA58F986C5A33502236B5BAE6DB613B1A408D16B29D3" +
"560F1E94AD840CFA93E83412937A115ABF68322538DA8082F0192D19EAAA41C9" +
"299729D487A9404ECDB6396DDA1534841EAE1E7884FA43574E213AE656116D9E" +
"F7591AA7BDE2B44733DFE27AA59949E5DC0EE00FDF42130A748DDD0FB0053C1A" +
"55986983C8B9CEAC023CAD7EDFFA1C20D3C437C0EF0FC9868D845484D8BE6538" +
"EAADA6365D48BA776EE239ED045667B101E3798FE53E1D4B9A2ACBBE6AF1E5C8" +
"8A3FB03AD616404013E249EC34458F3A7C9363E7772151119FE058BD0939BAB7" +
"64A2E545B0B2FDAA650B7E849C8DD4033922B2CAE46D0461C04A2C87657CB4C0" +
"FFBA23DED69D097109EC8BFDC25BB64417FEEB32842DE3EFEF2BF4A47F08B9FC" +
"D1907BC899CA9DA604F5132FB420C8D142D132E7E7B5A4BD0EF4A56D9E9B0ACD" +
"88F0E862D3F8F0440954879FFE3AA7AA90573C6BFDC6D6474C606ACA1CD94C1C" +
"3404349DD83A639B786AFCDEA1779860C05400E0479708F4A9A0DD51429A3F35" +
"FBD5FB9B68CECC1D585F3E35B7BBFC469F3EAEEB8020A6F0C8E4D1804A3EB32E" +
"B3909E80B0A41571B23931E164E0E1D0D05379F9FD3BF51AF04D2BE78BDB84BD" +
"787D419E85626297CB35FCFB6ED64042EAD2EBC17BB65677A1A33A5C48ADD280" +
"237FB2451D0EFB3A3C32354222C7AB77A3C92F7A45B5FB10092698D88725864A" +
"3685FBDD0DC741424FCCD8A00B928F3638150892CAAB535CC2813D13026615B9" +
"9977F7B8240E914ACA0FF2DCB1A9274BA1F55DF0D24CCD2BAB7741C9EA8B1ECD" +
"E97477C45F88F034FDF73023502944AEE1FF370260C576992826C4B2E5CE9924" +
"84E3B85170FCCAC3413DC0FF6F093593219E637F699A98BD29E8EE4550C128CA" +
"182680FDA3B10BC07625734EE8A8274B43B170FC3AEC9AA58CD92709D388E166" +
"AB4ADFD5A4876DC47C17DE51FDD42A32AF672515B6A81E7ABECFE748912B321A" +
"FD0CBF4880298DD79403900A4002B5B436230EB6E49192DF49FAE0F6B60EBA75" +
"A54592587C141AD3B319129006367E9532861C2893E7A2D0D2832DF4377C3184" +
"5CB02A1D020282C3D2B7F77221F71FEA7FF0A988FEF15C4B2F6637159EEC5752" +
"D8A7F4AB971117666A977370E754A4EB0DC52D6E8901DC60FCD87B5B6EF9A91A" +
"F8D9A4E11E2FFDAB55FC11AF6EEB5B36557FC8945A1E291B7FF8931BE4A57B8E" +
"68F04B9D4A9A02FC61AE913F2E2DDBEE42C065F4D30F568834D5BB15FDAF691F" +
"197EF6C25AE87D8E968C6D15351093AAC4813A8E7B191F77E6B19146F839A43E" +
"2F40DE8BE28EB22C0272545BADF3BD396D383B8DA8388147100B347999DDC412" +
"5AB0AA1159BC6776BD2BF51534C1B40522D41466F414BDE333226973BAD1E6D5" +
"7639D30AD94BEA1F6A98C047F1CE1294F0067B771778D59E7C722C73C2FF100E" +
"13603206A694BF0ED07303BE0655DC984CA29893FD0A088B122B67AABDC803E7" +
"3E5729E868B1CA26F5D05C818D9832C70F5992E7D15E14F9775C6AD24907CF2F" +
"211CF87167861F94DCF9E3D365CB600B336D93AD44B8B89CA24E59C1F7812C84" +
"DBE3EE57A536ED0D4BF948F7662E5BCBBB388C72243CFCEB720852D5A4A52F01" +
"8C2C087E4DB43410FE9ABA3A8EF737B6E8FFDB1AB9832EBF606ED5E4BD62A86B" +
"BCAE115C67682EDEA93E7845D0D6962C146B411F7784545851D2F327BEC7E434" +
"4D68F137CDA217A3F0FF3B752A34C3B5339C79CB8E1AC690C038E85D6FC13379" +
"090198D3555394D7A2159A23BD5EEF06EB0BCC729BB29B5BE911D02DA78FDA56" +
"F035E508C722139AD6F25A6C84BED0E98893370164B033A2B52BC40D9BF5163A" +
"F9650AB55EABB23370492A7D3A87E17C11B4D07A7296273F33069C835FD208BA" +
"8F989A3CF8659054E2CCCFB0C983531DC6590F27C4A1D2C3A780FE945F7E52BB" +
"9FFD2E324640E3E348541A620CD62605BBDB284AF97C621A00D5D1D2C31D6BD6" +
"1149137B8A0250BC426417A92445A52574E999FB9102C16671914A1542E92DDE" +
"541B2A0457112AF936DA84707CADFEA43BFEDAE5F58859908640420948086E57" +
"FFD1B867C241D40197CB0D4AD58BB69B3724772E0079406A1272858AAA620668" +
"F696955102639F3E95CFFC637EAF8AB54F0B5B2131AB292438D06E15F3826352" +
"DEDC653DA5A4AACE2BB97061A498F3B6789A2310471B32F91A6B7A9944DDBB70" +
"31525B3AE387214DC85A1C7749E9168F41272680D0B3C331D61175F23B623EEC" +
"40F984C35C831268036680DE0821E5DEE5BB250C6984775D49B7AF94057371DB" +
"72F81D2B0295FC6A51BCD00A697649D4346FDD59AC0DFAF21BFCC942C23C6134" +
"FFBA2ABABC141FF700B52C5B26496BF3F42665A5B71BAC7F0C19870BD9873890" +
"239C578CDDD8E08A1B0A429312FB24F151A11E4D180359A7FA043E8155453F67" +
"265CB2812B1C98C144E7675CFC86413B40E35445AE7710227D13DC0B5550C870" +
"10B363C492DA316FB40D3928570BF71BF47638F1401549369B1255DB080E5DFA" +
"18EA666B9ECBE5C9768C06B3FF125D0E94B98BB24B4FD44E770B78D7B336E021" +
"4FD72E77C1D0BE9F313EDCD147957E3463C62E753C10BB98584C85871AAEA9D1" +
"F397FE9F1A639ADE31D40EAB391B03B588B8B031BCAC6C837C61B06E4B745052" +
"474D33531086519C39EDD6310F3079EB5AC83289A6EDCBA3DC97E36E837134F7" +
"303B301F300706052B0E03021A0414725663844329F8BF6DECA5873DDD8C96AA" +
"8CA5D40414DF1D90CD18B3FBC72226B3C66EC2CB1AB351D4D2020207D0").HexToByteArray();
internal static readonly byte[] Pkcs7ChainDerBytes = (
"30820E1606092A864886F70D010702A0820E0730820E030201013100300B0609" +
"2A864886F70D010701A0820DEB3082050B30820474A003020102020A15EAA83A" +
"000100009291300D06092A864886F70D010105050030818131133011060A0992" +
"268993F22C6401191603636F6D31193017060A0992268993F22C64011916096D" +
"6963726F736F667431143012060A0992268993F22C6401191604636F72703117" +
"3015060A0992268993F22C64011916077265646D6F6E643120301E0603550403" +
"13174D532050617373706F7274205465737420537562204341301E170D313330" +
"3131303231333931325A170D3331313231333232323630375A308185310B3009" +
"060355040613025553310B30090603550408130257413110300E060355040713" +
"075265646D6F6E64310D300B060355040A130454455354310D300B060355040B" +
"130454455354311330110603550403130A746573742E6C6F63616C3124302206" +
"092A864886F70D010901161563726973706F70406D6963726F736F66742E636F" +
"6D30819F300D06092A864886F70D010101050003818D0030818902818100B406" +
"851089E9CF7CDB438DD77BEBD819197BEEFF579C35EF9C4652DF9E6330AA7E2E" +
"24B181C59DA4AF10E97220C1DF99F66CE6E97247E9126A016AC647BD2EFD136C" +
"31470C7BE01A20E381243BEEC8530B7F6466C50A051DCE37274ED7FF2AFFF4E5" +
"8AABA61D5A448F4A8A9B3765D1D769F627ED2F2DE9EE67B1A7ECA3D288C90203" +
"010001A38202823082027E300E0603551D0F0101FF0404030204F0301D060355" +
"1D250416301406082B0601050507030106082B06010505070302301D0603551D" +
"0E04160414FB3485708CBF6188F720EF948489405C8D0413A7301F0603551D23" +
"0418301680146A6678620A4FF49CA8B75FD566348F3371E42B133081D0060355" +
"1D1F0481C83081C53081C2A081BFA081BC865F687474703A2F2F707074657374" +
"73756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E636F6D" +
"2F43657274456E726F6C6C2F4D5325323050617373706F727425323054657374" +
"25323053756225323043412831292E63726C865966696C653A2F2F5C5C707074" +
"65737473756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E" +
"636F6D5C43657274456E726F6C6C5C4D532050617373706F7274205465737420" +
"5375622043412831292E63726C3082013806082B060105050701010482012A30" +
"82012630819306082B06010505073002868186687474703A2F2F707074657374" +
"73756263612E7265646D6F6E642E636F72702E6D6963726F736F66742E636F6D" +
"2F43657274456E726F6C6C2F70707465737473756263612E7265646D6F6E642E" +
"636F72702E6D6963726F736F66742E636F6D5F4D5325323050617373706F7274" +
"2532305465737425323053756225323043412831292E63727430818D06082B06" +
"01050507300286818066696C653A2F2F5C5C70707465737473756263612E7265" +
"646D6F6E642E636F72702E6D6963726F736F66742E636F6D5C43657274456E72" +
"6F6C6C5C70707465737473756263612E7265646D6F6E642E636F72702E6D6963" +
"726F736F66742E636F6D5F4D532050617373706F727420546573742053756220" +
"43412831292E637274300D06092A864886F70D0101050500038181009DEBB8B5" +
"A41ED54859795F68EF767A98A61EF7B07AAC190FCC0275228E4CAD360C9BA98B" +
"0AE153C75522EEF42D400E813B4E49E7ACEB963EEE7B61D3C8DA05C183471544" +
"725B2EBD1889877F62134827FB5993B8FDF618BD421ABA18D70D1C5B41ECDD11" +
"695A48CB42EB501F96DA905471830C612B609126559120F6E18EA44830820358" +
"308202C1A00302010202101B9671A4BC128B8341B0E314EAD9A191300D06092A" +
"864886F70D01010505003081A13124302206092A864886F70D01090116156173" +
"6D656D6F6E406D6963726F736F66742E636F6D310B3009060355040613025553" +
"310B30090603550408130257413110300E060355040713075265646D6F6E6431" +
"123010060355040A13094D6963726F736F667431163014060355040B130D5061" +
"7373706F727420546573743121301F060355040313184D532050617373706F72" +
"74205465737420526F6F74204341301E170D3035303132363031333933325A17" +
"0D3331313231333232323630375A3081A13124302206092A864886F70D010901" +
"161561736D656D6F6E406D6963726F736F66742E636F6D310B30090603550406" +
"13025553310B30090603550408130257413110300E060355040713075265646D" +
"6F6E6431123010060355040A13094D6963726F736F667431163014060355040B" +
"130D50617373706F727420546573743121301F060355040313184D5320506173" +
"73706F7274205465737420526F6F7420434130819F300D06092A864886F70D01" +
"0101050003818D0030818902818100C4673C1226254F6BBD01B01D21BB05264A" +
"9AA5B77AC51748EAC52048706DA6B890DCE043C6426FC44E76D70F9FE3A4AC85" +
"5F533E3D08E140853DB769EE24DBDB7269FABEC0FDFF6ADE0AA85F0085B78864" +
"58E7585E433B0924E81600433CB1177CE6AD5F2477B2A0E2D1A34B41F6C6F5AD" +
"E4A9DD7D565C65F02C2AAA01C8E0C10203010001A3818E30818B301306092B06" +
"0104018237140204061E0400430041300B0603551D0F040403020186300F0603" +
"551D130101FF040530030101FF301D0603551D0E04160414F509C1D6267FC39F" +
"CA1DE648C969C74FB111FE10301206092B060104018237150104050203010002" +
"302306092B0601040182371502041604147F7A5208411D4607C0057C98F0C473" +
"07010CB3DE300D06092A864886F70D0101050500038181004A8EAC73D8EA6D7E" +
"893D5880945E0E3ABFC79C40BFA60A680CF8A8BF63EDC3AD9C11C081F1F44408" +
"9581F5C8DCB23C0AEFA27571D971DBEB2AA9A1B3F7B9B0877E9311D36098A65B" +
"7D03FC69A835F6C3096DEE135A864065F9779C82DEB0C777B9C4DB49F0DD11A0" +
"EAB287B6E352F7ECA467D0D3CA2A8081119388BAFCDD25573082057C308204E5" +
"A003020102020A6187C7F200020000001B300D06092A864886F70D0101050500" +
"3081A13124302206092A864886F70D010901161561736D656D6F6E406D696372" +
"6F736F66742E636F6D310B3009060355040613025553310B3009060355040813" +
"0257413110300E060355040713075265646D6F6E6431123010060355040A1309" +
"4D6963726F736F667431163014060355040B130D50617373706F727420546573" +
"743121301F060355040313184D532050617373706F7274205465737420526F6F" +
"74204341301E170D3039313032373231333133395A170D333131323133323232" +
"3630375A30818131133011060A0992268993F22C6401191603636F6D31193017" +
"060A0992268993F22C64011916096D6963726F736F667431143012060A099226" +
"8993F22C6401191604636F727031173015060A0992268993F22C640119160772" +
"65646D6F6E643120301E060355040313174D532050617373706F727420546573" +
"742053756220434130819F300D06092A864886F70D010101050003818D003081" +
"8902818100A6A4918F93C5D23B3C3A325AD8EC77043D207A0DDC294AD3F5BDE0" +
"4033FADD4097BB1DB042B1D3B2F26A42CC3CB88FA9357710147AB4E1020A0DFB" +
"2597AB8031DB62ABDC48398067EB79E4E2BBE5762F6B4C5EA7629BAC23F70269" +
"06D46EC106CC6FBB4D143F7D5ADADEDE19B021EEF4A6BCB9D01DAEBB9A947703" +
"40B748A3490203010001A38202D7308202D3300F0603551D130101FF04053003" +
"0101FF301D0603551D0E041604146A6678620A4FF49CA8B75FD566348F3371E4" +
"2B13300B0603551D0F040403020186301206092B060104018237150104050203" +
"010001302306092B060104018237150204160414A0A485AE8296EA4944C6F6F3" +
"886A8603FD07472C301906092B0601040182371402040C1E0A00530075006200" +
"430041301F0603551D23041830168014F509C1D6267FC39FCA1DE648C969C74F" +
"B111FE103081D60603551D1F0481CE3081CB3081C8A081C5A081C28663687474" +
"703A2F2F70617373706F72747465737463612E7265646D6F6E642E636F72702E" +
"6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F4D532532305061" +
"7373706F727425323054657374253230526F6F7425323043412831292E63726C" +
"865B66696C653A2F2F50415353504F52545445535443412E7265646D6F6E642E" +
"636F72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F4D53" +
"2050617373706F7274205465737420526F6F742043412831292E63726C308201" +
"4406082B06010505070101048201363082013230819A06082B06010505073002" +
"86818D687474703A2F2F70617373706F72747465737463612E7265646D6F6E64" +
"2E636F72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F50" +
"415353504F52545445535443412E7265646D6F6E642E636F72702E6D6963726F" +
"736F66742E636F6D5F4D5325323050617373706F727425323054657374253230" +
"526F6F7425323043412832292E63727430819206082B06010505073002868185" +
"66696C653A2F2F50415353504F52545445535443412E7265646D6F6E642E636F" +
"72702E6D6963726F736F66742E636F6D2F43657274456E726F6C6C2F50415353" +
"504F52545445535443412E7265646D6F6E642E636F72702E6D6963726F736F66" +
"742E636F6D5F4D532050617373706F7274205465737420526F6F742043412832" +
"292E637274300D06092A864886F70D010105050003818100C44788F8C4F5C2DC" +
"84976F66417CBAE19FBFA82C257DA4C7FED6267BC711D113C78B1C097154A62A" +
"B462ADC84A434AEBAE38DEB9605FAB534A3CAF7B72C199448E58640388911296" +
"115ED6B3478D0E741D990F2D59D66F12E58669D8983489AB0406E37462164B56" +
"6AA1D9B273C406FA694A2556D1D3ACE723382C19871B8C143100").HexToByteArray();
internal static readonly byte[] Pkcs7ChainPemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN PKCS7-----
MIIOFgYJKoZIhvcNAQcCoIIOBzCCDgMCAQExADALBgkqhkiG9w0BBwGggg3rMIIF
CzCCBHSgAwIBAgIKFeqoOgABAACSkTANBgkqhkiG9w0BAQUFADCBgTETMBEGCgmS
JomT8ixkARkWA2NvbTEZMBcGCgmSJomT8ixkARkWCW1pY3Jvc29mdDEUMBIGCgmS
JomT8ixkARkWBGNvcnAxFzAVBgoJkiaJk/IsZAEZFgdyZWRtb25kMSAwHgYDVQQD
ExdNUyBQYXNzcG9ydCBUZXN0IFN1YiBDQTAeFw0xMzAxMTAyMTM5MTJaFw0zMTEy
MTMyMjI2MDdaMIGFMQswCQYDVQQGEwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcT
B1JlZG1vbmQxDTALBgNVBAoTBFRFU1QxDTALBgNVBAsTBFRFU1QxEzARBgNVBAMT
CnRlc3QubG9jYWwxJDAiBgkqhkiG9w0BCQEWFWNyaXNwb3BAbWljcm9zb2Z0LmNv
bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtAaFEInpz3zbQ43Xe+vYGRl7
7v9XnDXvnEZS355jMKp+LiSxgcWdpK8Q6XIgwd+Z9mzm6XJH6RJqAWrGR70u/RNs
MUcMe+AaIOOBJDvuyFMLf2RmxQoFHc43J07X/yr/9OWKq6YdWkSPSoqbN2XR12n2
J+0vLenuZ7Gn7KPSiMkCAwEAAaOCAoIwggJ+MA4GA1UdDwEB/wQEAwIE8DAdBgNV
HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwHQYDVR0OBBYEFPs0hXCMv2GI9yDv
lISJQFyNBBOnMB8GA1UdIwQYMBaAFGpmeGIKT/ScqLdf1WY0jzNx5CsTMIHQBgNV
HR8EgcgwgcUwgcKggb+ggbyGX2h0dHA6Ly9wcHRlc3RzdWJjYS5yZWRtb25kLmNv
cnAubWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL01TJTIwUGFzc3BvcnQlMjBUZXN0
JTIwU3ViJTIwQ0EoMSkuY3JshllmaWxlOi8vXFxwcHRlc3RzdWJjYS5yZWRtb25k
LmNvcnAubWljcm9zb2Z0LmNvbVxDZXJ0RW5yb2xsXE1TIFBhc3Nwb3J0IFRlc3Qg
U3ViIENBKDEpLmNybDCCATgGCCsGAQUFBwEBBIIBKjCCASYwgZMGCCsGAQUFBzAC
hoGGaHR0cDovL3BwdGVzdHN1YmNhLnJlZG1vbmQuY29ycC5taWNyb3NvZnQuY29t
L0NlcnRFbnJvbGwvcHB0ZXN0c3ViY2EucmVkbW9uZC5jb3JwLm1pY3Jvc29mdC5j
b21fTVMlMjBQYXNzcG9ydCUyMFRlc3QlMjBTdWIlMjBDQSgxKS5jcnQwgY0GCCsG
AQUFBzAChoGAZmlsZTovL1xccHB0ZXN0c3ViY2EucmVkbW9uZC5jb3JwLm1pY3Jv
c29mdC5jb21cQ2VydEVucm9sbFxwcHRlc3RzdWJjYS5yZWRtb25kLmNvcnAubWlj
cm9zb2Z0LmNvbV9NUyBQYXNzcG9ydCBUZXN0IFN1YiBDQSgxKS5jcnQwDQYJKoZI
hvcNAQEFBQADgYEAneu4taQe1UhZeV9o73Z6mKYe97B6rBkPzAJ1Io5MrTYMm6mL
CuFTx1Ui7vQtQA6BO05J56zrlj7ue2HTyNoFwYNHFURyWy69GImHf2ITSCf7WZO4
/fYYvUIauhjXDRxbQezdEWlaSMtC61AfltqQVHGDDGErYJEmVZEg9uGOpEgwggNY
MIICwaADAgECAhAblnGkvBKLg0Gw4xTq2aGRMA0GCSqGSIb3DQEBBQUAMIGhMSQw
IgYJKoZIhvcNAQkBFhVhc21lbW9uQG1pY3Jvc29mdC5jb20xCzAJBgNVBAYTAlVT
MQswCQYDVQQIEwJXQTEQMA4GA1UEBxMHUmVkbW9uZDESMBAGA1UEChMJTWljcm9z
b2Z0MRYwFAYDVQQLEw1QYXNzcG9ydCBUZXN0MSEwHwYDVQQDExhNUyBQYXNzcG9y
dCBUZXN0IFJvb3QgQ0EwHhcNMDUwMTI2MDEzOTMyWhcNMzExMjEzMjIyNjA3WjCB
oTEkMCIGCSqGSIb3DQEJARYVYXNtZW1vbkBtaWNyb3NvZnQuY29tMQswCQYDVQQG
EwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcTB1JlZG1vbmQxEjAQBgNVBAoTCU1p
Y3Jvc29mdDEWMBQGA1UECxMNUGFzc3BvcnQgVGVzdDEhMB8GA1UEAxMYTVMgUGFz
c3BvcnQgVGVzdCBSb290IENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDE
ZzwSJiVPa70BsB0huwUmSpqlt3rFF0jqxSBIcG2muJDc4EPGQm/ETnbXD5/jpKyF
X1M+PQjhQIU9t2nuJNvbcmn6vsD9/2reCqhfAIW3iGRY51heQzsJJOgWAEM8sRd8
5q1fJHeyoOLRo0tB9sb1reSp3X1WXGXwLCqqAcjgwQIDAQABo4GOMIGLMBMGCSsG
AQQBgjcUAgQGHgQAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0G
A1UdDgQWBBT1CcHWJn/Dn8od5kjJacdPsRH+EDASBgkrBgEEAYI3FQEEBQIDAQAC
MCMGCSsGAQQBgjcVAgQWBBR/elIIQR1GB8AFfJjwxHMHAQyz3jANBgkqhkiG9w0B
AQUFAAOBgQBKjqxz2Optfok9WICUXg46v8ecQL+mCmgM+Ki/Y+3DrZwRwIHx9EQI
lYH1yNyyPArvonVx2XHb6yqpobP3ubCHfpMR02CYplt9A/xpqDX2wwlt7hNahkBl
+Xecgt6wx3e5xNtJ8N0RoOqyh7bjUvfspGfQ08oqgIERk4i6/N0lVzCCBXwwggTl
oAMCAQICCmGHx/IAAgAAABswDQYJKoZIhvcNAQEFBQAwgaExJDAiBgkqhkiG9w0B
CQEWFWFzbWVtb25AbWljcm9zb2Z0LmNvbTELMAkGA1UEBhMCVVMxCzAJBgNVBAgT
AldBMRAwDgYDVQQHEwdSZWRtb25kMRIwEAYDVQQKEwlNaWNyb3NvZnQxFjAUBgNV
BAsTDVBhc3Nwb3J0IFRlc3QxITAfBgNVBAMTGE1TIFBhc3Nwb3J0IFRlc3QgUm9v
dCBDQTAeFw0wOTEwMjcyMTMxMzlaFw0zMTEyMTMyMjI2MDdaMIGBMRMwEQYKCZIm
iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MRQwEgYKCZIm
iZPyLGQBGRYEY29ycDEXMBUGCgmSJomT8ixkARkWB3JlZG1vbmQxIDAeBgNVBAMT
F01TIFBhc3Nwb3J0IFRlc3QgU3ViIENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
iQKBgQCmpJGPk8XSOzw6MlrY7HcEPSB6DdwpStP1veBAM/rdQJe7HbBCsdOy8mpC
zDy4j6k1dxAUerThAgoN+yWXq4Ax22Kr3Eg5gGfreeTiu+V2L2tMXqdim6wj9wJp
BtRuwQbMb7tNFD99Wtre3hmwIe70pry50B2uu5qUdwNAt0ijSQIDAQABo4IC1zCC
AtMwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUamZ4YgpP9Jyot1/VZjSPM3Hk
KxMwCwYDVR0PBAQDAgGGMBIGCSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYBBAGCNxUC
BBYEFKCkha6ClupJRMb284hqhgP9B0csMBkGCSsGAQQBgjcUAgQMHgoAUwB1AGIA
QwBBMB8GA1UdIwQYMBaAFPUJwdYmf8Ofyh3mSMlpx0+xEf4QMIHWBgNVHR8Egc4w
gcswgciggcWggcKGY2h0dHA6Ly9wYXNzcG9ydHRlc3RjYS5yZWRtb25kLmNvcnAu
bWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL01TJTIwUGFzc3BvcnQlMjBUZXN0JTIw
Um9vdCUyMENBKDEpLmNybIZbZmlsZTovL1BBU1NQT1JUVEVTVENBLnJlZG1vbmQu
Y29ycC5taWNyb3NvZnQuY29tL0NlcnRFbnJvbGwvTVMgUGFzc3BvcnQgVGVzdCBS
b290IENBKDEpLmNybDCCAUQGCCsGAQUFBwEBBIIBNjCCATIwgZoGCCsGAQUFBzAC
hoGNaHR0cDovL3Bhc3Nwb3J0dGVzdGNhLnJlZG1vbmQuY29ycC5taWNyb3NvZnQu
Y29tL0NlcnRFbnJvbGwvUEFTU1BPUlRURVNUQ0EucmVkbW9uZC5jb3JwLm1pY3Jv
c29mdC5jb21fTVMlMjBQYXNzcG9ydCUyMFRlc3QlMjBSb290JTIwQ0EoMikuY3J0
MIGSBggrBgEFBQcwAoaBhWZpbGU6Ly9QQVNTUE9SVFRFU1RDQS5yZWRtb25kLmNv
cnAubWljcm9zb2Z0LmNvbS9DZXJ0RW5yb2xsL1BBU1NQT1JUVEVTVENBLnJlZG1v
bmQuY29ycC5taWNyb3NvZnQuY29tX01TIFBhc3Nwb3J0IFRlc3QgUm9vdCBDQSgy
KS5jcnQwDQYJKoZIhvcNAQEFBQADgYEAxEeI+MT1wtyEl29mQXy64Z+/qCwlfaTH
/tYme8cR0RPHixwJcVSmKrRirchKQ0rrrjjeuWBfq1NKPK97csGZRI5YZAOIkRKW
EV7Ws0eNDnQdmQ8tWdZvEuWGadiYNImrBAbjdGIWS1Zqodmyc8QG+mlKJVbR06zn
IzgsGYcbjBQxAA==
-----END PKCS7-----");
internal static readonly byte[] Pkcs7EmptyPemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN PKCS7-----
MCcGCSqGSIb3DQEHAqAaMBgCAQExADALBgkqhkiG9w0BBwGgAKEAMQA=
-----END PKCS7-----");
internal static readonly byte[] Pkcs7EmptyDerBytes = (
"302706092A864886F70D010702A01A30180201013100300B06092A864886F70D" +
"010701A000A1003100").HexToByteArray();
internal static readonly byte[] Pkcs7SingleDerBytes = (
"3082021406092A864886F70D010702A0820205308202010201013100300B0609" +
"2A864886F70D010701A08201E9308201E530820152A0030201020210D5B5BC1C" +
"458A558845BFF51CB4DFF31C300906052B0E03021D05003011310F300D060355" +
"040313064D794E616D65301E170D3130303430313038303030305A170D313130" +
"3430313038303030305A3011310F300D060355040313064D794E616D6530819F" +
"300D06092A864886F70D010101050003818D0030818902818100B11E30EA8742" +
"4A371E30227E933CE6BE0E65FF1C189D0D888EC8FF13AA7B42B68056128322B2" +
"1F2B6976609B62B6BC4CF2E55FF5AE64E9B68C78A3C2DACC916A1BC7322DD353" +
"B32898675CFB5B298B176D978B1F12313E3D865BC53465A11CCA106870A4B5D5" +
"0A2C410938240E92B64902BAEA23EB093D9599E9E372E48336730203010001A3" +
"46304430420603551D01043B3039801024859EBF125E76AF3F0D7979B4AC7A96" +
"A1133011310F300D060355040313064D794E616D658210D5B5BC1C458A558845" +
"BFF51CB4DFF31C300906052B0E03021D0500038181009BF6E2CF830ED485B86D" +
"6B9E8DFFDCD65EFC7EC145CB9348923710666791FCFA3AB59D689FFD7234B787" +
"2611C5C23E5E0714531ABADB5DE492D2C736E1C929E648A65CC9EB63CD84E57B" +
"5909DD5DDF5DBBBA4A6498B9CA225B6E368B94913BFC24DE6B2BD9A26B192B95" +
"7304B89531E902FFC91B54B237BB228BE8AFCDA264763100").HexToByteArray();
internal static readonly byte[] Pkcs7SinglePemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN PKCS7-----
MIICFAYJKoZIhvcNAQcCoIICBTCCAgECAQExADALBgkqhkiG9w0BBwGgggHpMIIB
5TCCAVKgAwIBAgIQ1bW8HEWKVYhFv/UctN/zHDAJBgUrDgMCHQUAMBExDzANBgNV
BAMTBk15TmFtZTAeFw0xMDA0MDEwODAwMDBaFw0xMTA0MDEwODAwMDBaMBExDzAN
BgNVBAMTBk15TmFtZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsR4w6odC
SjceMCJ+kzzmvg5l/xwYnQ2Ijsj/E6p7QraAVhKDIrIfK2l2YJtitrxM8uVf9a5k
6baMeKPC2syRahvHMi3TU7MomGdc+1spixdtl4sfEjE+PYZbxTRloRzKEGhwpLXV
CixBCTgkDpK2SQK66iPrCT2VmenjcuSDNnMCAwEAAaNGMEQwQgYDVR0BBDswOYAQ
JIWevxJedq8/DXl5tKx6lqETMBExDzANBgNVBAMTBk15TmFtZYIQ1bW8HEWKVYhF
v/UctN/zHDAJBgUrDgMCHQUAA4GBAJv24s+DDtSFuG1rno3/3NZe/H7BRcuTSJI3
EGZnkfz6OrWdaJ/9cjS3hyYRxcI+XgcUUxq6213kktLHNuHJKeZIplzJ62PNhOV7
WQndXd9du7pKZJi5yiJbbjaLlJE7/CTeayvZomsZK5VzBLiVMekC/8kbVLI3uyKL
6K/NomR2MQA=
-----END PKCS7-----");
internal static readonly byte[] MicrosoftDotComSslCertBytes = (
"308205943082047CA00302010202103DF70C5D9903F8D8868B9B8CCF20DF6930" +
"0D06092A864886F70D01010B05003077310B3009060355040613025553311D30" +
"1B060355040A131453796D616E74656320436F72706F726174696F6E311F301D" +
"060355040B131653796D616E746563205472757374204E6574776F726B312830" +
"260603550403131F53796D616E74656320436C61737320332045562053534C20" +
"4341202D204733301E170D3134313031353030303030305A170D313631303135" +
"3233353935395A3082010F31133011060B2B0601040182373C02010313025553" +
"311B3019060B2B0601040182373C0201020C0A57617368696E67746F6E311D30" +
"1B060355040F131450726976617465204F7267616E697A6174696F6E31123010" +
"06035504051309363030343133343835310B3009060355040613025553310E30" +
"0C06035504110C0539383035323113301106035504080C0A57617368696E6774" +
"6F6E3110300E06035504070C075265646D6F6E643118301606035504090C0F31" +
"204D6963726F736F667420576179311E301C060355040A0C154D6963726F736F" +
"667420436F72706F726174696F6E310E300C060355040B0C054D53434F4D311A" +
"301806035504030C117777772E6D6963726F736F66742E636F6D30820122300D" +
"06092A864886F70D01010105000382010F003082010A0282010100A46861FA9D" +
"5DB763633BF5A64EF6E7C2C2367F48D2D46643A22DFCFCCB24E58A14D0F06BDC" +
"956437F2A56BA4BEF70BA361BF12964A0D665AFD84B0F7494C8FA4ABC5FCA2E0" +
"17C06178AEF2CDAD1B5F18E997A14B965C074E8F564970607276B00583932240" +
"FE6E2DD013026F9AE13D7C91CC07C4E1E8E87737DC06EF2B575B89D62EFE4685" +
"9F8255A123692A706C68122D4DAFE11CB205A7B3DE06E553F7B95F978EF8601A" +
"8DF819BF32040BDF92A0DE0DF269B4514282E17AC69934E8440A48AB9D1F5DF8" +
"9A502CEF6DFDBE790045BD45E0C94E5CA8ADD76A013E9C978440FC8A9E2A9A49" +
"40B2460819C3E302AA9C9F355AD754C86D3ED77DDAA3DA13810B4D0203010001" +
"A38201803082017C30310603551D11042A302882117777772E6D6963726F736F" +
"66742E636F6D821377777771612E6D6963726F736F66742E636F6D3009060355" +
"1D1304023000300E0603551D0F0101FF0404030205A0301D0603551D25041630" +
"1406082B0601050507030106082B0601050507030230660603551D20045F305D" +
"305B060B6086480186F84501071706304C302306082B06010505070201161768" +
"747470733A2F2F642E73796D63622E636F6D2F637073302506082B0601050507" +
"020230191A1768747470733A2F2F642E73796D63622E636F6D2F727061301F06" +
"03551D230418301680140159ABE7DD3A0B59A66463D6CF200757D591E76A302B" +
"0603551D1F042430223020A01EA01C861A687474703A2F2F73722E73796D6362" +
"2E636F6D2F73722E63726C305706082B06010505070101044B3049301F06082B" +
"060105050730018613687474703A2F2F73722E73796D63642E636F6D30260608" +
"2B06010505073002861A687474703A2F2F73722E73796D63622E636F6D2F7372" +
"2E637274300D06092A864886F70D01010B0500038201010015F8505B627ED7F9" +
"F96707097E93A51E7A7E05A3D420A5C258EC7A1CFE1843EC20ACF728AAFA7A1A" +
"1BC222A7CDBF4AF90AA26DEEB3909C0B3FB5C78070DAE3D645BFCF840A4A3FDD" +
"988C7B3308BFE4EB3FD66C45641E96CA3352DBE2AEB4488A64A9C5FB96932BA7" +
"0059CE92BD278B41299FD213471BD8165F924285AE3ECD666C703885DCA65D24" +
"DA66D3AFAE39968521995A4C398C7DF38DFA82A20372F13D4A56ADB21B582254" +
"9918015647B5F8AC131CC5EB24534D172BC60218A88B65BCF71C7F388CE3E0EF" +
"697B4203720483BB5794455B597D80D48CD3A1D73CBBC609C058767D1FF060A6" +
"09D7E3D4317079AF0CD0A8A49251AB129157F9894A036487").HexToByteArray();
internal static readonly byte[] MicrosoftDotComIssuerBytes = (
"3082052B30820413A00302010202107EE14A6F6FEFF2D37F3FAD654D3ADAB430" +
"0D06092A864886F70D01010B05003081CA310B30090603550406130255533117" +
"3015060355040A130E566572695369676E2C20496E632E311F301D060355040B" +
"1316566572695369676E205472757374204E6574776F726B313A303806035504" +
"0B1331286329203230303620566572695369676E2C20496E632E202D20466F72" +
"20617574686F72697A656420757365206F6E6C79314530430603550403133C56" +
"6572695369676E20436C6173732033205075626C6963205072696D6172792043" +
"657274696669636174696F6E20417574686F72697479202D204735301E170D31" +
"33313033313030303030305A170D3233313033303233353935395A3077310B30" +
"09060355040613025553311D301B060355040A131453796D616E74656320436F" +
"72706F726174696F6E311F301D060355040B131653796D616E74656320547275" +
"7374204E6574776F726B312830260603550403131F53796D616E74656320436C" +
"61737320332045562053534C204341202D20473330820122300D06092A864886" +
"F70D01010105000382010F003082010A0282010100D8A1657423E82B64E232D7" +
"33373D8EF5341648DD4F7F871CF84423138EFB11D8445A18718E601626929BFD" +
"170BE1717042FEBFFA1CC0AAA3A7B571E8FF1883F6DF100A1362C83D9CA7DE2E" +
"3F0CD91DE72EFB2ACEC89A7F87BFD84C041532C9D1CC9571A04E284F84D935FB" +
"E3866F9453E6728A63672EBE69F6F76E8E9C6004EB29FAC44742D27898E3EC0B" +
"A592DCB79ABD80642B387C38095B66F62D957A86B2342E859E900E5FB75DA451" +
"72467013BF67F2B6A74D141E6CB953EE231A4E8D48554341B189756A4028C57D" +
"DDD26ED202192F7B24944BEBF11AA99BE3239AEAFA33AB0A2CB7F46008DD9F1C" +
"CDDD2D016680AFB32F291D23B88AE1A170070C340F0203010001A382015D3082" +
"0159302F06082B0601050507010104233021301F06082B060105050730018613" +
"687474703A2F2F73322E73796D63622E636F6D30120603551D130101FF040830" +
"060101FF02010030650603551D20045E305C305A0604551D2000305230260608" +
"2B06010505070201161A687474703A2F2F7777772E73796D617574682E636F6D" +
"2F637073302806082B06010505070202301C1A1A687474703A2F2F7777772E73" +
"796D617574682E636F6D2F72706130300603551D1F042930273025A023A02186" +
"1F687474703A2F2F73312E73796D63622E636F6D2F706361332D67352E63726C" +
"300E0603551D0F0101FF04040302010630290603551D1104223020A41E301C31" +
"1A30180603550403131153796D616E746563504B492D312D353333301D060355" +
"1D0E041604140159ABE7DD3A0B59A66463D6CF200757D591E76A301F0603551D" +
"230418301680147FD365A7C2DDECBBF03009F34339FA02AF333133300D06092A" +
"864886F70D01010B050003820101004201557BD0161A5D58E8BB9BA84DD7F3D7" +
"EB139486D67F210B47BC579B925D4F059F38A4107CCF83BE0643468D08BC6AD7" +
"10A6FAABAF2F61A863F265DF7F4C8812884FB369D9FF27C00A97918F56FB89C4" +
"A8BB922D1B73B0C6AB36F4966C2008EF0A1E6624454F670040C8075474333BA6" +
"ADBB239F66EDA2447034FB0EEA01FDCF7874DFA7AD55B75F4DF6D63FE086CE24" +
"C742A9131444354BB6DFC960AC0C7FD993214BEE9CE4490298D3607B5CBCD530" +
"2F07CE4442C40B99FEE69FFCB07886516DD12C9DC696FB8582BB042FF76280EF" +
"62DA7FF60EAC90B856BD793FF2806EA3D9B90F5D3A071D9193864B294CE1DCB5" +
"E1E0339DB3CB36914BFEA1B4EEF0F9").HexToByteArray();
internal static readonly byte[] MicrosoftDotComRootBytes = (
"308204D3308203BBA003020102021018DAD19E267DE8BB4A2158CDCC6B3B4A30" +
"0D06092A864886F70D01010505003081CA310B30090603550406130255533117" +
"3015060355040A130E566572695369676E2C20496E632E311F301D060355040B" +
"1316566572695369676E205472757374204E6574776F726B313A303806035504" +
"0B1331286329203230303620566572695369676E2C20496E632E202D20466F72" +
"20617574686F72697A656420757365206F6E6C79314530430603550403133C56" +
"6572695369676E20436C6173732033205075626C6963205072696D6172792043" +
"657274696669636174696F6E20417574686F72697479202D204735301E170D30" +
"36313130383030303030305A170D3336303731363233353935395A3081CA310B" +
"300906035504061302555331173015060355040A130E566572695369676E2C20" +
"496E632E311F301D060355040B1316566572695369676E205472757374204E65" +
"74776F726B313A3038060355040B133128632920323030362056657269536967" +
"6E2C20496E632E202D20466F7220617574686F72697A656420757365206F6E6C" +
"79314530430603550403133C566572695369676E20436C617373203320507562" +
"6C6963205072696D6172792043657274696669636174696F6E20417574686F72" +
"697479202D20473530820122300D06092A864886F70D01010105000382010F00" +
"3082010A0282010100AF240808297A359E600CAAE74B3B4EDC7CBC3C451CBB2B" +
"E0FE2902F95708A364851527F5F1ADC831895D22E82AAAA642B38FF8B955B7B1" +
"B74BB3FE8F7E0757ECEF43DB66621561CF600DA4D8DEF8E0C362083D5413EB49" +
"CA59548526E52B8F1B9FEBF5A191C23349D843636A524BD28FE870514DD18969" +
"7BC770F6B3DC1274DB7B5D4B56D396BF1577A1B0F4A225F2AF1C926718E5F406" +
"04EF90B9E400E4DD3AB519FF02BAF43CEEE08BEB378BECF4D7ACF2F6F03DAFDD" +
"759133191D1C40CB7424192193D914FEAC2A52C78FD50449E48D6347883C6983" +
"CBFE47BD2B7E4FC595AE0E9DD4D143C06773E314087EE53F9F73B8330ACF5D3F" +
"3487968AEE53E825150203010001A381B23081AF300F0603551D130101FF0405" +
"30030101FF300E0603551D0F0101FF040403020106306D06082B060105050701" +
"0C0461305FA15DA05B3059305730551609696D6167652F6769663021301F3007" +
"06052B0E03021A04148FE5D31A86AC8D8E6BC3CF806AD448182C7B192E302516" +
"23687474703A2F2F6C6F676F2E766572697369676E2E636F6D2F76736C6F676F" +
"2E676966301D0603551D0E041604147FD365A7C2DDECBBF03009F34339FA02AF" +
"333133300D06092A864886F70D0101050500038201010093244A305F62CFD81A" +
"982F3DEADC992DBD77F6A5792238ECC4A7A07812AD620E457064C5E797662D98" +
"097E5FAFD6CC2865F201AA081A47DEF9F97C925A0869200DD93E6D6E3C0D6ED8" +
"E606914018B9F8C1EDDFDB41AAE09620C9CD64153881C994EEA284290B136F8E" +
"DB0CDD2502DBA48B1944D2417A05694A584F60CA7E826A0B02AA251739B5DB7F" +
"E784652A958ABD86DE5E8116832D10CCDEFDA8822A6D281F0D0BC4E5E71A2619" +
"E1F4116F10B595FCE7420532DBCE9D515E28B69E85D35BEFA57D4540728EB70E" +
"6B0E06FB33354871B89D278BC4655F0D86769C447AF6955CF65D320833A454B6" +
"183F685CF2424A853854835FD1E82CF2AC11D6A8ED636A").HexToByteArray();
internal static readonly byte[] Rsa384CertificatePemBytes = ByteUtils.AsciiBytes(
@"-----BEGIN CERTIFICATE-----
MIICTzCCAgmgAwIBAgIJAMQtYhFJ0+5jMA0GCSqGSIb3DQEBBQUAMIGSMQswCQYD
VQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwHUmVkbW9uZDEY
MBYGA1UECgwPTWljcm9zb2Z0IENvcnAuMSAwHgYDVQQLDBcuTkVUIEZyYW1ld29y
ayAoQ29yZUZ4KTEgMB4GA1UEAwwXUlNBIDM4NC1iaXQgQ2VydGlmaWNhdGUwHhcN
MTYwMzAyMTY1OTA0WhcNMTYwNDAxMTY1OTA0WjCBkjELMAkGA1UEBhMCVVMxEzAR
BgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1JlZG1vbmQxGDAWBgNVBAoMD01p
Y3Jvc29mdCBDb3JwLjEgMB4GA1UECwwXLk5FVCBGcmFtZXdvcmsgKENvcmVGeCkx
IDAeBgNVBAMMF1JTQSAzODQtYml0IENlcnRpZmljYXRlMEwwDQYJKoZIhvcNAQEB
BQADOwAwOAIxANrMIthuZxV1Ay4x8gbc/BksZeLVEInlES0JbyiCr9tbeM22Vy/S
9h2zkEciMuPZ9QIDAQABo1AwTjAdBgNVHQ4EFgQU5FG2Fmi86hJOCf4KnjaxOGWV
dRUwHwYDVR0jBBgwFoAU5FG2Fmi86hJOCf4KnjaxOGWVdRUwDAYDVR0TBAUwAwEB
/zANBgkqhkiG9w0BAQUFAAMxAEzDg/u8TlApCnE8qxhcbTXk2MbX+2n5PCn+MVrW
wggvPj3b2WMXsVWiPr4S1Y/nBA==
-----END CERTIFICATE-----");
internal static readonly ECDsaCngKeyValues ECDsaCng256PublicKey =
new ECDsaCngKeyValues()
{
QX = "448d98ee08aeba0d8b40f3c6dbd500e8b69f07c70c661771655228ea5a178a91".HexToByteArray(),
QY = "0ef5cb1759f6f2e062021d4f973f5bb62031be87ae915cff121586809e3219af".HexToByteArray(),
D = "692837e9cf613c0e290462a6f08faadcc7002398f75598d5554698a0cb51cf47".HexToByteArray(),
};
internal static readonly byte[] ECDsa256Certificate =
("308201223081c9a00302010202106a3c9e85ba6af1ac4f08111d8bdda340300906072a8648ce3d0401301431123010060355"
+ "04031309456332353655736572301e170d3135303931303231333533305a170d3136303931303033333533305a3014311230"
+ "10060355040313094563323536557365723059301306072a8648ce3d020106082a8648ce3d03010703420004448d98ee08ae"
+ "ba0d8b40f3c6dbd500e8b69f07c70c661771655228ea5a178a910ef5cb1759f6f2e062021d4f973f5bb62031be87ae915cff"
+ "121586809e3219af300906072a8648ce3d04010349003046022100f221063dca71955d17c8f0e0f63a144c4065578fd9f68e"
+ "1ae6a7683e209ea742022100ed1db6a8be27cfb20ab43e0ca061622ceff26f7249a0f791e4d6be1a4e52adfa").HexToByteArray();
internal static readonly ECDsaCngKeyValues ECDsaCng384PublicKey =
new ECDsaCngKeyValues()
{
QX = "c59eca607aa5559e6b2f8ac2eeb12d9ab47f420feabeb444c3f71520d7f2280439979323ab5a67344811d296fef6d1bd".HexToByteArray(),
QY = "d15f307cc6cc6c8baeeeb168bfb02c34d6eb0621efb3d06ad31c06b29eaf6ec2ec67bf288455e729d82e5a6439f70901".HexToByteArray(),
D = "f55ba33e28cea32a014e2fe1213bb4d41cef361f1fee022116b15be50feb96bc946b10a46a9a7a94176787e0928a3e1d".HexToByteArray(),
};
internal static readonly byte[] ECDsa384Certificate =
("3082015f3081e6a00302010202101e78eb573e70a2a64744672296988ad7300906072a8648ce3d0401301431123010060355"
+ "04031309456333383455736572301e170d3135303931303231333634365a170d3136303931303033333634365a3014311230"
+ "10060355040313094563333834557365723076301006072a8648ce3d020106052b8104002203620004c59eca607aa5559e6b"
+ "2f8ac2eeb12d9ab47f420feabeb444c3f71520d7f2280439979323ab5a67344811d296fef6d1bdd15f307cc6cc6c8baeeeb1"
+ "68bfb02c34d6eb0621efb3d06ad31c06b29eaf6ec2ec67bf288455e729d82e5a6439f70901300906072a8648ce3d04010369"
+ "003066023100a8fbaeeae61953897eae5f0beeeffaca48e89bc0cb782145f39f4ba5b03390ce6a28e432e664adf5ebc6a802"
+ "040b238b023100dcc19109383b9482fdda68f40a63ee41797dbb8f25c0284155cc4238d682fbb3fb6e86ea0933297e850a26"
+ "16f6c39bbf").HexToByteArray();
internal static readonly ECDsaCngKeyValues ECDsaCng521PublicKey =
new ECDsaCngKeyValues()
{
QX = "0134af29d1fe5e581fd2ff6194263abcb6f8cb4d9c08bdb384ede9b8663ae2f4e1af6c85eacc69dc768fbfcd856630792e05484cefb1fefb693081dc6490dac579c0".HexToByteArray(),
QY = "00bfe103f53cbcb039873b1a3e81a9da9abd71995e722318367281d30b35a338bf356662342b653eff38e85881863b7128ddbb856d8ae158365550bb6330b93d4ef0".HexToByteArray(),
D = "0153603164bcef5c9f62388d06dcbf5681479be4397c07ff6f44bb848465e3397537d5f61abc7bc9266d4df6bae1df4847fcfd3dabdda37a2fe549b821ea858d088d".HexToByteArray(),
};
internal static readonly byte[] ECDsa521Certificate =
("308201a93082010ca00302010202102c3134fe79bb9daa48df6431f4c1e4f3300906072a8648ce3d04013014311230100603"
+ "5504031309456335323155736572301e170d3135303931303231333832305a170d3136303931303033333832305a30143112"
+ "30100603550403130945633532315573657230819b301006072a8648ce3d020106052b8104002303818600040134af29d1fe"
+ "5e581fd2ff6194263abcb6f8cb4d9c08bdb384ede9b8663ae2f4e1af6c85eacc69dc768fbfcd856630792e05484cefb1fefb"
+ "693081dc6490dac579c000bfe103f53cbcb039873b1a3e81a9da9abd71995e722318367281d30b35a338bf356662342b653e"
+ "ff38e85881863b7128ddbb856d8ae158365550bb6330b93d4ef0300906072a8648ce3d040103818b0030818702420090bdf5"
+ "dfb328501910da4b02ba3ccd41f2bb073608c55f0f2b2e1198496c59b44db9e516a6a63ba7841d22cf590e39d3f09636d0eb"
+ "cd59a92c105f499e1329615602414285111634719b9bbd10eb7d08655b2fa7d7eb5e225bfdafef15562ae2f9f0c6a943a7bd"
+ "f0e39223d807b5e2e617a8e424294d90869567326531bcad0f893a0f3a").HexToByteArray();
internal static readonly byte[] EccCert_KeyAgreement = (
"308201553081FDA00302010202105A1C956450FFED894E85DC61E11CD968300A" +
"06082A8648CE3D04030230143112301006035504030C09454344482054657374" +
"301E170D3135303433303138303131325A170D3136303433303138323131325A" +
"30143112301006035504030C094543444820546573743059301306072A8648CE" +
"3D020106082A8648CE3D0301070342000477DE73EA00A82250B69E3F24A14CDD" +
"C4C47C83993056DD0A2C6C17D5C8E7A054216B9253533D12C082E0C8B91B3B10" +
"CDAB564820D417E6D056E4E34BCCA87301A331302F300E0603551D0F0101FF04" +
"0403020009301D0603551D0E0416041472DE05F588BF2741C8A28FF99EA399F7" +
"AAB2C1B3300A06082A8648CE3D040302034700304402203CDF0CC71C63747BDA" +
"2D2D563115AE68D34867E74BCA02738086C316B846CDF2022079F3990E5DCCEE" +
"627B2E6E42317D4D279181EE695EE239D0C8516DD53A896EC3").HexToByteArray();
internal static readonly byte[] ECDsa224Certificate = (
"3082026630820214A003020102020900B94BCCE3179BAA21300A06082A8648CE" +
"3D040302308198310B30090603550406130255533113301106035504080C0A57" +
"617368696E67746F6E3110300E06035504070C075265646D6F6E64311E301C06" +
"0355040A0C154D6963726F736F667420436F72706F726174696F6E3120301E06" +
"0355040B0C172E4E4554204672616D65776F726B2028436F7265465829312030" +
"1E06035504030C174E4953542F53454320502D3232342054657374204B657930" +
"1E170D3135313233313232353532345A170D3136303133303232353532345A30" +
"8198310B30090603550406130255533113301106035504080C0A57617368696E" +
"67746F6E3110300E06035504070C075265646D6F6E64311E301C060355040A0C" +
"154D6963726F736F667420436F72706F726174696F6E3120301E060355040B0C" +
"172E4E4554204672616D65776F726B2028436F72654658293120301E06035504" +
"030C174E4953542F53454320502D3232342054657374204B6579304E30100607" +
"2A8648CE3D020106052B81040021033A000452FF02B55AE35AA7FFF1B0A82DC2" +
"260083DD7D5893E85FBAD1D663B718176F7D5D9A04B8AEA968E9FECFEE348CDB" +
"49A938401783BADAC484A350304E301D0603551D0E041604140EA9C5C4681A6E" +
"48CE64E47EE8BBB0BA5FF8AB3E301F0603551D230418301680140EA9C5C4681A" +
"6E48CE64E47EE8BBB0BA5FF8AB3E300C0603551D13040530030101FF300A0608" +
"2A8648CE3D040302034000303D021D00AC10B79B6FD6BEE113573A1B68A3B771" +
"3B9DA2719A9588376E334811021C1AAC3CA829DA79CE223FA83283E6F0A5A59D" +
"2399E140D957C1C9DDAF").HexToByteArray();
internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_Windows = (
"308204470201033082040306092A864886F70D010701A08203F4048203F03082" +
"03EC3082016D06092A864886F70D010701A082015E0482015A30820156308201" +
"52060B2A864886F70D010C0A0102A081CC3081C9301C060A2A864886F70D010C" +
"0103300E0408EC154269C5878209020207D00481A80BAA4AF8660E6FAB7B050B" +
"8EF604CFC378652B54FE005DC3C7E2F12E5EFC7FE2BB0E1B3828CAFE752FD64C" +
"7CA04AF9FBC5A1F36E30D7D299C52BF6AE65B54B9240CC37C04E7E06330C24E9" +
"6D19A67B7015A6BF52C172FFEA719B930DBE310EEBC756BDFF2DF2846EE973A6" +
"6C63F4E9130083D64487B35C1941E98B02B6D5A92972293742383C62CCAFB996" +
"EAD71A1DF5D0380EFFF25BA60B233A39210FD7D55A9B95CD8A440DF666317430" +
"1306092A864886F70D0109153106040401000000305D06092B06010401823711" +
"0131501E4E004D006900630072006F0073006F0066007400200053006F006600" +
"7400770061007200650020004B00650079002000530074006F00720061006700" +
"65002000500072006F007600690064006500723082027706092A864886F70D01" +
"0706A0820268308202640201003082025D06092A864886F70D010701301C060A" +
"2A864886F70D010C0106300E0408175CCB1790C48584020207D080820230E956" +
"E38768A035D8EA911283A63F2E5B6E5B73231CFC4FFD386481DE24B7BB1B0995" +
"D614A0D1BD086215CE0054E01EF9CF91B7D80A4ACB6B596F1DFD6CBCA71476F6" +
"10C0D6DD24A301E4B79BA6993F15D34A8ADB7115A8605E797A2C6826A4379B65" +
"90B56CA29F7C36997119257A827C3CA0EC7F8F819536208C650E324C8F884794" +
"78705F833155463A4EFC02B5D5E2608B83F3CAF6C9BB97C1BBBFC6C5584BDCD3" +
"9C46A3944915B3845C41429C7792EB4FA3A7EDECCD801F31A4B6EF57D808AEEA" +
"AF3D1F55F378EF8EF9632CED16EDA3EFBE4A9D5C5F608CA90A9AC8D3F86462AC" +
"219BFFD0B8A87DDD22CF029230369B33FC2B488B5F82702EFC3F270F912EAD2E" +
"2402D99F8324164C5CD5959F22DEC0D1D212345B4B3F62848E7D9CFCE2224B61" +
"976C107E1B218B4B7614FF65BCCA388F85D6920270D4C588DEED323C416D014F" +
"5F648CC2EE941855EB3C889DCB9A345ED11CAE94041A86ED23E5789137A3DE22" +
"5F4023D260BB686901F2149B5D7E37102FFF5282995892BDC2EAB48BD5DA155F" +
"72B1BD05EE3EDD32160AC852E5B47CA9AEACE24946062E9D7DCDA642F945C9E7" +
"C98640DFAC7A2B88E76A560A0B4156611F9BE8B3613C71870F035062BD4E3D9F" +
"D896CF373CBFBFD31410972CDE50739FFB8EC9180A52D7F5415EBC997E5A4221" +
"349B4BB7D53614630EEEA729A74E0C0D20726FDE5814321D6C265A7DC6BA24CA" +
"F2FCE8C8C162733D58E02E08921E70EF838B95C96A5818489782563AE8A2A85F" +
"64A95EB350FF8EF6D625AD031BCD303B301F300706052B0E03021A0414C8D96C" +
"ED140F5CA3CB92BEFCA32C690804576ABF0414B59D4FECA9944D40EEFDE7FB96" +
"196D167B0FA511020207D0").HexToByteArray();
// The PFX in ECDsaP256_DigitalSignature_Pfx_Windows washed through OpenSSL
internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_OpenSsl = (
"308203BE0201033082038406092A864886F70D010701A0820375048203713082" +
"036D308201FF06092A864886F70D010706A08201F0308201EC020100308201E5" +
"06092A864886F70D010701301C060A2A864886F70D010C0106300E040888F579" +
"00302DB63A02020800808201B8F5EDB44F8B2572E85E52946B233A47F03DF776" +
"BC3A05CB74B4145A9D3AE3C7FD61B330194E1E154B89929F3FA3908FEE95512A" +
"052FDDE8E1913E2CCFD803EE6D868696D86934DCF5300DC951F36BE93E3F4AA2" +
"096B926CF8410AF77FFA087213F84F17EB1D36B61AF4AAD87288301569239B9A" +
"B66392ADA3D468DC33F42FCEC3BEE78148CA72686BB733DB89FC951AE92FD0F7" +
"D5937DE78B1AF984BD13E5127F73A91D40097976AEF00157DCC34B16C1724E5B" +
"88090A1A2DA7337C72720A7ED8F1A89C09AB4143C3F6D80B1925AB8F744069F6" +
"399D997827F7D0931DCB5E3B09783D1D8555910906B33AD03759D292021C21A2" +
"9EA2F29CF9BA4D66E4E69AA9FDCCCB4D49A806DBB804EBEBAED7AE0DD4AD2133" +
"1482A3CC5DB246CE59998824B7E46F337F8887D990FA1756D6A039D293B243BB" +
"DCFB19AD613A42C5778E7094EA43C3136EF359209790462A36CF87D89B6D76CF" +
"BD8C34B8C41D96C83683751B8B067F42017A37D05B599B82B70830B5A93499A0" +
"A4791F5DAB2143C8DF35EC7E88B71A0990E7F6FEA304CE594C9280D7B9120816" +
"45C87112B1ED85124533792ABEF8B4946F811FB9FE922F6F786E5BFD7D7C43F6" +
"48AB43C43F3082016606092A864886F70D010701A0820157048201533082014F" +
"3082014B060B2A864886F70D010C0A0102A081B43081B1301C060A2A864886F7" +
"0D010C0103300E0408F58B95D6E307213C02020800048190E0FB35890FFB6F30" +
"7DD0BD8B10EB10488EAB18702E5AC9F67C557409DF8E3F382D06060FB3B5A08D" +
"1EA31313E80A0488B4034C8906BD873A5308E412783684A35DBD9EEACF5D090D" +
"AE7390E3309D016C41133946A6CF70E32BE8002CD4F06A90F5BBCE6BF932EC71" +
"F634312D315310CE2015B30C51FCC54B60FB3D6E7B734C1ADEBE37056A46AB3C" +
"23276B16603FC50C318184302306092A864886F70D01091531160414F20D17B7" +
"9B898999F0AA1D5EA333FAEF2BDB2A29305D06092B060104018237110131501E" +
"4E004D006900630072006F0073006F0066007400200053006F00660074007700" +
"61007200650020004B00650079002000530074006F0072006100670065002000" +
"500072006F0076006900640065007230313021300906052B0E03021A05000414" +
"96C2244022AB2B809E0F97270F7F4EA7769DD26F04084C0E2946D65F8F220202" +
"0800").HexToByteArray();
internal struct ECDsaCngKeyValues
{
public byte[] QX;
public byte[] QY;
public byte[] D;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
/////////////////////////////////////////////////////////////////////////////////
// Defines the structure used when binding types
// CheckConstraints options.
[Flags]
internal enum CheckConstraintsFlags
{
None = 0x00,
Outer = 0x01,
NoErrors = 0x04,
}
/////////////////////////////////////////////////////////////////////////////////
// TypeBind has static methods to accomplish most tasks.
//
// For some of these tasks there are also instance methods. The instance
// method versions don't report not found errors (they may report others) but
// instead record error information in the TypeBind instance. Call the
// ReportErrors method to report recorded errors.
internal static class TypeBind
{
// Check the constraints of any type arguments in the given Type.
public static bool CheckConstraints(CType type, CheckConstraintsFlags flags)
{
type = type.GetNakedType(false);
if (!(type is AggregateType ats))
{
if (type is NullableType nub)
{
ats = nub.GetAts();
}
else
{
return true;
}
}
if (ats.TypeArgsAll.Count == 0)
{
// Common case: there are no type vars, so there are no constraints.
ats.ConstraintError = false;
return true;
}
// Already checked.
if (ats.ConstraintError.HasValue)
{
// No errors
if (!ats.ConstraintError.GetValueOrDefault())
{
return true;
}
// We want the result, not an exception.
if ((flags & CheckConstraintsFlags.NoErrors) != 0)
{
return false;
}
}
TypeArray typeVars = ats.OwningAggregate.GetTypeVars();
TypeArray typeArgsThis = ats.TypeArgsThis;
TypeArray typeArgsAll = ats.TypeArgsAll;
Debug.Assert(typeVars.Count == typeArgsThis.Count);
// Check the outer type first. If CheckConstraintsFlags.Outer is not specified and the
// outer type has already been checked then don't bother checking it.
if (ats.OuterType != null && ((flags & CheckConstraintsFlags.Outer) != 0 || !ats.OuterType.ConstraintError.HasValue))
{
if (!CheckConstraints(ats.OuterType, flags))
{
ats.ConstraintError = true;
return false;
}
}
if (typeVars.Count > 0)
{
if (!CheckConstraintsCore(ats.OwningAggregate, typeVars, typeArgsThis, typeArgsAll, null, flags & CheckConstraintsFlags.NoErrors))
{
ats.ConstraintError = true;
return false;
}
}
// Now check type args themselves.
for (int i = 0; i < typeArgsThis.Count; i++)
{
CType arg = typeArgsThis[i].GetNakedType(true);
if (arg is AggregateType atArg && !atArg.ConstraintError.HasValue)
{
CheckConstraints(atArg, flags | CheckConstraintsFlags.Outer);
if (atArg.ConstraintError.GetValueOrDefault())
{
ats.ConstraintError = true;
return false;
}
}
}
ats.ConstraintError = false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Check the constraints on the method instantiation.
public static void CheckMethConstraints(MethWithInst mwi)
{
Debug.Assert(mwi.Meth() != null && mwi.GetType() != null && mwi.TypeArgs != null);
Debug.Assert(mwi.Meth().typeVars.Count == mwi.TypeArgs.Count);
Debug.Assert(mwi.GetType().OwningAggregate == mwi.Meth().getClass());
if (mwi.TypeArgs.Count > 0)
{
CheckConstraintsCore(mwi.Meth(), mwi.Meth().typeVars, mwi.TypeArgs, mwi.GetType().TypeArgsAll, mwi.TypeArgs, CheckConstraintsFlags.None);
}
}
////////////////////////////////////////////////////////////////////////////////
// Check whether typeArgs satisfies the constraints of typeVars. The
// typeArgsCls and typeArgsMeth are used for substitution on the bounds. The
// tree and symErr are used for error reporting.
private static bool CheckConstraintsCore(Symbol symErr, TypeArray typeVars, TypeArray typeArgs, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
{
Debug.Assert(typeVars.Count == typeArgs.Count);
Debug.Assert(typeVars.Count > 0);
Debug.Assert(flags == CheckConstraintsFlags.None || flags == CheckConstraintsFlags.NoErrors);
for (int i = 0; i < typeVars.Count; i++)
{
// Empty bounds should be set to object.
TypeParameterType var = (TypeParameterType)typeVars[i];
CType arg = typeArgs[i];
if (!CheckSingleConstraint(symErr, var, arg, typeArgsCls, typeArgsMeth, flags))
{
return false;
}
}
return true;
}
private static bool CheckSingleConstraint(Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
{
Debug.Assert(!(arg is PointerType));
Debug.Assert(!arg.IsStaticClass);
bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors);
if (var.HasRefConstraint && !arg.IsReferenceType)
{
if (fReportErrors)
{
throw ErrorHandling.Error(ErrorCode.ERR_RefConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
return false;
}
TypeArray bnds = TypeManager.SubstTypeArray(var.Bounds, typeArgsCls, typeArgsMeth);
int itypeMin = 0;
if (var.HasValConstraint)
{
// If we have a type variable that is constrained to a value type, then we
// want to check if its a nullable type, so that we can report the
// constraint error below. In order to do this however, we need to check
// that either the type arg is not a value type, or it is a nullable type.
//
// To check whether or not its a nullable type, we need to get the resolved
// bound from the type argument and check against that.
if (!arg.IsNonNullableValueType)
{
if (fReportErrors)
{
throw ErrorHandling.Error(ErrorCode.ERR_ValConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
return false;
}
// Since FValCon() is set it is redundant to check System.ValueType as well.
if (bnds.Count != 0 && bnds[0].IsPredefType(PredefinedType.PT_VALUE))
{
itypeMin = 1;
}
}
for (int j = itypeMin; j < bnds.Count; j++)
{
CType typeBnd = bnds[j];
if (!SatisfiesBound(arg, typeBnd))
{
if (fReportErrors)
{
// The bound isn't satisfied because of a constraint type. Explain to the user why not.
// There are 4 main cases, based on the type of the supplied type argument:
// - reference type, or type parameter known to be a reference type
// - nullable type, from which there is a boxing conversion to the constraint type(see below for details)
// - type variable
// - value type
// These cases are broken out because: a) The sets of conversions which can be used
// for constraint satisfaction is different based on the type argument supplied,
// and b) Nullable is one funky type, and user's can use all the help they can get
// when using it.
ErrorCode error;
if (arg.IsReferenceType)
{
// A reference type can only satisfy bounds to types
// to which they have an implicit reference conversion
error = ErrorCode.ERR_GenericConstraintNotSatisfiedRefType;
}
else if (arg is NullableType nubArg && SymbolLoader.HasBaseConversion(nubArg.UnderlyingType, typeBnd)) // This is inlining FBoxingConv
{
// nullable types do not satisfy bounds to every type that they are boxable to
// They only satisfy bounds of object and ValueType
if (typeBnd.IsPredefType(PredefinedType.PT_ENUM) || nubArg.UnderlyingType == typeBnd)
{
// Nullable types don't satisfy bounds of EnumType, or the underlying type of the enum
// even though the conversion from Nullable to these types is a boxing conversion
// This is a rare case, because these bounds can never be directly stated ...
// These bounds can only occur when one type paramter is constrained to a second type parameter
// and the second type parameter is instantiated with Enum or the underlying type of the first type
// parameter
error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum;
}
else
{
// Nullable types don't satisfy the bounds of any interface type
// even when there is a boxing conversion from the Nullable type to
// the interface type. This will be a relatively common scenario
// so we cal it out separately from the previous case.
Debug.Assert(typeBnd.IsInterfaceType);
error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface;
}
}
else
{
// Value types can only satisfy bounds through boxing conversions.
// Note that the exceptional case of Nullable types and boxing is handled above.
error = ErrorCode.ERR_GenericConstraintNotSatisfiedValType;
}
throw ErrorHandling.Error(error, new ErrArg(symErr), new ErrArg(typeBnd, ErrArgFlags.Unique), var, new ErrArg(arg, ErrArgFlags.Unique));
}
return false;
}
}
// Check the newable constraint.
if (!var.HasNewConstraint || arg.IsValueType)
{
return true;
}
if (arg.IsClassType)
{
AggregateSymbol agg = ((AggregateType)arg).OwningAggregate;
// Due to late binding nature of IDE created symbols, the AggregateSymbol might not
// have all the information necessary yet, if it is not fully bound.
// by calling LookupAggMember, it will ensure that we will update all the
// information necessary at least for the given method.
SymbolLoader.LookupAggMember(NameManager.GetPredefinedName(PredefinedName.PN_CTOR), agg, symbmask_t.MASK_ALL);
if (agg.HasPubNoArgCtor() && !agg.IsAbstract())
{
return true;
}
}
if (fReportErrors)
{
throw ErrorHandling.Error(ErrorCode.ERR_NewConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// Determine whether the arg type satisfies the typeBnd constraint. Note that
// typeBnd could be just about any type (since we added naked type parameter
// constraints).
private static bool SatisfiesBound(CType arg, CType typeBnd)
{
if (typeBnd == arg)
return true;
switch (typeBnd.TypeKind)
{
default:
Debug.Assert(false, "Unexpected type.");
return false;
case TypeKind.TK_VoidType:
case TypeKind.TK_PointerType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_TypeParameterType:
break;
case TypeKind.TK_NullableType:
typeBnd = ((NullableType)typeBnd).GetAts();
break;
case TypeKind.TK_AggregateType:
break;
}
Debug.Assert(typeBnd is AggregateType || typeBnd is TypeParameterType || typeBnd is ArrayType);
switch (arg.TypeKind)
{
default:
return false;
case TypeKind.TK_PointerType:
return false;
case TypeKind.TK_NullableType:
arg = ((NullableType)arg).GetAts();
// Fall through.
goto case TypeKind.TK_TypeParameterType;
case TypeKind.TK_TypeParameterType:
case TypeKind.TK_ArrayType:
case TypeKind.TK_AggregateType:
return SymbolLoader.HasBaseConversion(arg, typeBnd);
}
}
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
public class CCParticleSystemQuad : CCParticleSystem
{
// ivars
CCBlendFunc blendFunc;
CCTexture2D texture;
CCPoint currentPosition;
CCRawList<CCV3F_C4B_T2F_Quad> quads;
CCCustomCommand renderParticlesCommand;
#region Properties
public bool BlendAdditive
{
get { return BlendFunc == CCBlendFunc.Additive; }
set
{
if (value)
{
blendFunc = CCBlendFunc.Additive;
}
else
{
if (Texture != null && !Texture.HasPremultipliedAlpha)
{
blendFunc = CCBlendFunc.NonPremultiplied;
}
else
{
blendFunc = CCBlendFunc.AlphaBlend;
}
}
}
}
public override int TotalParticles
{
set
{
if(value == TotalParticles)
return;
if (value > AllocatedParticles)
{
if (EmitterMode == CCEmitterMode.Gravity)
GravityParticles = new CCParticleGravity[value];
else
RadialParticles = new CCParticleRadial[value];
if(quads != null)
quads.Capacity = value;
AllocatedParticles = value;
}
base.TotalParticles = value;
}
}
public CCBlendFunc BlendFunc
{
get { return blendFunc; }
set
{
if (blendFunc.Source != value.Source || blendFunc.Destination != value.Destination)
{
blendFunc = value;
UpdateBlendFunc();
}
}
}
public CCTexture2D Texture
{
get { return texture; }
set
{
if (value == null)
return;
// Only update the texture if is different from the current one
if (value != Texture)
{
texture = value;
CCSize s = value.ContentSizeInPixels;
TextureRect = new CCRect (0, 0, s.Width, s.Height);
UpdateBlendFunc();
}
}
}
public CCRect TextureRect
{
set { ResetTexCoords(value); }
}
CCRawList<CCV3F_C4B_T2F_Quad> Quads
{
set
{
if (Texture!= null && value != null && value != quads && GameView != null)
{
quads = value;
CCSize texSize = Texture.ContentSizeInPixels;
// Load the quads with tex coords
ResetTexCoords(new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height));
}
}
}
#endregion Properties
#region Constructors
public CCParticleSystemQuad(int numberOfParticles = 0, CCEmitterMode emitterMode=CCEmitterMode.Gravity)
: base(numberOfParticles, emitterMode)
{
InitRenderCommand();
}
public CCParticleSystemQuad(CCParticleSystemConfig config)
: base(config)
{
InitRenderCommand();
Texture = config.Texture;
CCBlendFunc blendFunc = new CCBlendFunc();
blendFunc.Source = config.BlendFunc.Source;
blendFunc.Destination = config.BlendFunc.Destination;
BlendFunc = blendFunc;
}
public CCParticleSystemQuad (string plistFile, string directoryName = null)
: this (new CCParticleSystemConfig (plistFile, directoryName))
{ }
void InitRenderCommand()
{
quads = new CCRawList<CCV3F_C4B_T2F_Quad> (TotalParticles);
renderParticlesCommand = new CCCustomCommand(RenderParticles);
}
#endregion Constructors
protected override void VisitRenderer(ref CCAffineTransform worldTransform)
{
if(ParticleCount == 0)
return;
renderParticlesCommand.GlobalDepth = worldTransform.Tz;
renderParticlesCommand.WorldTransform = worldTransform;
Renderer.AddCommand(renderParticlesCommand);
}
void RenderParticles()
{
DrawManager.BlendFunc(BlendFunc);
DrawManager.BindTexture(Texture);
DrawManager.DrawQuads(quads, 0, ParticleCount);
}
#region Updating quads
// pointRect should be in Texture coordinates, not pixel coordinates
void ResetTexCoords(CCRect texRectInPixels)
{
float wide = texRectInPixels.Size.Width;
float high = texRectInPixels.Size.Height;
if (Texture != null)
{
wide = Texture.PixelsWide;
high = Texture.PixelsHigh;
}
#if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
float left = (texRectInPixels.Origin.X * 2 + 1) / (wide * 2);
float bottom = (texRectInPixels.Origin.Y * 2 + 1) / (high * 2);
float right = left + (texRectInPixels.Size.Width * 2 - 2) / (wide * 2);
float top = bottom + (texRectInPixels.Size.Height * 2 - 2) / (high * 2);
#else
float left = texRectInPixels.Origin.X / wide;
float bottom = texRectInPixels.Origin.Y / high;
float right = left + texRectInPixels.Size.Width / wide;
float top = bottom + texRectInPixels.Size.Height / high;
#endif
// ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
// Important. Textures in CocosSharp are inverted, so the Y component should be inverted
float tmp = top;
top = bottom;
bottom = tmp;
CCV3F_C4B_T2F_Quad[] rawQuads;
int start, end;
rawQuads = quads.Elements;
start = 0;
end = TotalParticles;
for (int i = start; i < end; i++)
{
rawQuads[i].BottomLeft.TexCoords.U = left;
rawQuads[i].BottomLeft.TexCoords.V = bottom;
rawQuads[i].BottomRight.TexCoords.U = right;
rawQuads[i].BottomRight.TexCoords.V = bottom;
rawQuads[i].TopLeft.TexCoords.U = left;
rawQuads[i].TopLeft.TexCoords.V = top;
rawQuads[i].TopRight.TexCoords.U = right;
rawQuads[i].TopRight.TexCoords.V = top;
}
}
void UpdateQuad(ref CCV3F_C4B_T2F_Quad quad, ref CCParticleBase particle)
{
CCPoint newPosition;
if(PositionType == CCPositionType.Free)
{
newPosition.X = particle.Position.X - (currentPosition.X - particle.StartPosition.X);
newPosition.Y = particle.Position.Y - (currentPosition.Y - particle.StartPosition.Y);
}
else
{
newPosition = particle.Position;
}
CCColor4B color = new CCColor4B();
if(OpacityModifyRGB)
{
color.R = (byte) (particle.Color.R * particle.Color.A * 255);
color.G = (byte) (particle.Color.G * particle.Color.A * 255);
color.B = (byte) (particle.Color.B * particle.Color.A * 255);
color.A = (byte)(particle.Color.A * 255);
}
else
{
color.R = (byte)(particle.Color.R * 255);
color.G = (byte)(particle.Color.G * 255);
color.B = (byte)(particle.Color.B * 255);
color.A = (byte)(particle.Color.A * 255);
}
quad.BottomLeft.Colors = color;
quad.BottomRight.Colors = color;
quad.TopLeft.Colors = color;
quad.TopRight.Colors = color;
// vertices
float size_2 = particle.Size / 2;
if (particle.Rotation != 0.0)
{
float x1 = -size_2;
float y1 = -size_2;
float x2 = size_2;
float y2 = size_2;
float x = newPosition.X;
float y = newPosition.Y;
float r = -CCMathHelper.ToRadians(particle.Rotation);
float cr = CCMathHelper.Cos(r);
float sr = CCMathHelper.Sin(r);
float ax = x1 * cr - y1 * sr + x;
float ay = x1 * sr + y1 * cr + y;
float bx = x2 * cr - y1 * sr + x;
float by = x2 * sr + y1 * cr + y;
float cx = x2 * cr - y2 * sr + x;
float cy = x2 * sr + y2 * cr + y;
float dx = x1 * cr - y2 * sr + x;
float dy = x1 * sr + y2 * cr + y;
// bottom-left
quad.BottomLeft.Vertices.X = ax;
quad.BottomLeft.Vertices.Y = ay;
// bottom-right vertex:
quad.BottomRight.Vertices.X = bx;
quad.BottomRight.Vertices.Y = by;
// top-left vertex:
quad.TopLeft.Vertices.X = dx;
quad.TopLeft.Vertices.Y = dy;
// top-right vertex:
quad.TopRight.Vertices.X = cx;
quad.TopRight.Vertices.Y = cy;
}
else
{
// bottom-left vertex:
quad.BottomLeft.Vertices.X = newPosition.X - size_2;
quad.BottomLeft.Vertices.Y = newPosition.Y - size_2;
// bottom-right vertex:
quad.BottomRight.Vertices.X = newPosition.X + size_2;
quad.BottomRight.Vertices.Y = newPosition.Y - size_2;
// top-left vertex:
quad.TopLeft.Vertices.X = newPosition.X - size_2;
quad.TopLeft.Vertices.Y = newPosition.Y + size_2;
// top-right vertex:
quad.TopRight.Vertices.X = newPosition.X + size_2;
quad.TopRight.Vertices.Y = newPosition.Y + size_2;
}
}
public override void UpdateQuads()
{
if (!Visible || Layer == null)
{
return;
}
currentPosition = CCPoint.Zero;
if (PositionType == CCPositionType.Free)
{
currentPosition = Position;
}
CCV3F_C4B_T2F_Quad[] rawQuads = quads.Elements;
if (EmitterMode == CCEmitterMode.Gravity)
{
UpdateGravityParticleQuads(rawQuads);
}
else
{
UpdateRadialParticleQuads(rawQuads);
}
}
void UpdateGravityParticleQuads(CCV3F_C4B_T2F_Quad[] rawQuads)
{
var count = ParticleCount;
for (int i = 0; i < count; i++)
{
UpdateQuad(ref rawQuads[i], ref GravityParticles[i].ParticleBase);
}
}
void UpdateRadialParticleQuads(CCV3F_C4B_T2F_Quad[] rawQuads)
{
var count = ParticleCount;
for (int i = 0; i < count; i++)
{
UpdateQuad(ref rawQuads[i], ref RadialParticles[i].ParticleBase);
}
}
#endregion Updating quads
public CCParticleSystemQuad Clone()
{
var p = new CCParticleSystemQuad(TotalParticles, EmitterMode);
// angle
p.Angle = Angle;
p.AngleVar = AngleVar;
// duration
p.Duration = Duration;
// blend function
p.BlendFunc = BlendFunc;
// color
p.StartColor = StartColor;
p.StartColorVar = StartColorVar;
p.EndColor = EndColor;
p.EndColorVar = EndColorVar;
// particle size
p.StartSize = StartSize;
p.StartSizeVar = StartSizeVar;
p.EndSize = EndSize;
p.EndSizeVar = EndSizeVar;
// position
p.Position = Position;
p.PositionVar = PositionVar;
// Spinning
p.StartSpin = StartSpin;
p.StartSpinVar = StartSpinVar;
p.EndSpin = EndSpin;
p.EndSpinVar = EndSpinVar;
p.GravityMode = GravityMode;
p.RadialMode = RadialMode;
// life span
p.Life = Life;
p.LifeVar = LifeVar;
// emission Rate
p.EmissionRate = EmissionRate;
p.OpacityModifyRGB = OpacityModifyRGB;
p.Texture = Texture;
p.AutoRemoveOnFinish = AutoRemoveOnFinish;
return p;
}
void UpdateBlendFunc()
{
if (Texture != null)
{
bool premultiplied = Texture.HasPremultipliedAlpha;
OpacityModifyRGB = false;
if (blendFunc == CCBlendFunc.AlphaBlend)
{
if (premultiplied)
OpacityModifyRGB = true;
else
blendFunc = CCBlendFunc.NonPremultiplied;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Microsoft.VisualStudioTools.Project
{
internal class SR
{
internal const string AddReferenceDialogTitle = "AddReferenceDialogTitle";
internal const string AddReferenceExtensions = "AddReferenceExtensions";
internal const string AddToNullProjectError = "AddToNullProjectError";
internal const string Advanced = "Advanced";
internal const string AttributeLoad = "AttributeLoad";
internal const string BuildAction = "BuildAction";
internal const string BuildActionDescription = "BuildActionDescription";
internal const string BuildCaption = "BuildCaption";
internal const string BuildVerbosity = "BuildVerbosity";
internal const string BuildVerbosityDescription = "BuildVerbosityDescription";
internal const string BuildEventError = "BuildEventError";
internal const string Cancel = "Cancel";
internal const string CancelQueryEdit = "CancelQueryEdit";
internal const string CancelQueryEditMultiple = "CancelQueryEditMultiple";
internal const string CannotAddFileExists = "CannotAddFileExists";
internal const string CannotAddFileThatIsOpenInEditor = "CannotAddFileThatIsOpenInEditor";
internal const string CannotAddFolderAsDescendantOfSelf = "CannotAddFolderAsDescendantOfSelf";
internal const string CannotMoveFolderExists = "CannotMoveFolderExists";
internal const string CannotMoveIntoSameDirectory = "CannotMoveIntoSameDirectory";
internal const string CannotMoveIntoSubfolder = "CannotMoveIntoSubfolder";
internal const string CanNotSaveFileNotOpeneInEditor = "CanNotSaveFileNotOpeneInEditor";
internal const string cli1 = "cli1";
internal const string Compile = "Compile";
internal const string ConfirmExtensionChange = "ConfirmExtensionChange";
internal const string Content = "Content";
internal const string CopyToLocal = "CopyToLocal";
internal const string CopyToLocalDescription = "CopyToLocalDescription";
internal const string CustomTool = "CustomTool";
internal const string CustomToolDescription = "CustomToolDescription";
internal const string CustomToolNamespace = "CustomToolNamespace";
internal const string CustomToolNamespaceDescription = "CustomToolNamespaceDescription";
internal const string DetailsImport = "DetailsImport";
internal const string DetailsUserImport = "DetailsUserImport";
internal const string DetailsItem = "DetailsItem";
internal const string DetailsItemLocation = "DetailsItemLocation";
internal const string DetailsProperty = "DetailsProperty";
internal const string DetailsTarget = "DetailsTarget";
internal const string DetailsUsingTask = "DetailsUsingTask";
internal const string Detailed = "Detailed";
internal const string Diagnostic = "Diagnostic";
internal const string DirectoryExists = "DirectoryExists";
internal const string DirectoryExistsShortMessage = "DirectoryExistsShortMessage";
internal const string EditorViewError = "EditorViewError";
internal const string EmbeddedResource = "EmbeddedResource";
internal const string Error = "Error";
internal const string ErrorDetail = "ErrorDetail";
internal const string ErrorInvalidFileName = "ErrorInvalidFileName";
internal const string ErrorInvalidLaunchUrl = "ErrorInvalidLaunchUrl";
internal const string ErrorInvalidProjectName = "ErrorInvalidProjectName";
internal const string ErrorReferenceCouldNotBeAdded = "ErrorReferenceCouldNotBeAdded";
internal const string ErrorMsBuildRegistration = "ErrorMsBuildRegistration";
internal const string ErrorSaving = "ErrorSaving";
internal const string Exe = "Exe";
internal const string ExpectedObjectOfType = "ExpectedObjectOfType";
internal const string FailedToRetrieveProperties = "FailedToRetrieveProperties";
internal const string FileNameCannotContainALeadingPeriod = "FileNameCannotContainALeadingPeriod";
internal const string FileCannotBeRenamedToAnExistingFile = "FileCannotBeRenamedToAnExistingFile";
internal const string FileAlreadyExistsAndCannotBeRenamed = "FileAlreadyExistsAndCannotBeRenamed";
internal const string FileAlreadyExists = "FileAlreadyExists";
internal const string FileAlreadyExistsCaption = "FileAlreadyExistsCaption";
internal const string FileAlreadyInProject = "FileAlreadyInProject";
internal const string FileAlreadyInProjectCaption = "FileAlreadyInProjectCaption";
internal const string FileCopyError = "FileCopyError";
internal const string FileName = "FileName";
internal const string FileNameDescription = "FileNameDescription";
internal const string FileOrFolderAlreadyExists = "FileOrFolderAlreadyExists";
internal const string FileOrFolderCannotBeFound = "FileOrFolderCannotBeFound";
internal const string FileProperties = "FileProperties";
internal const string FolderCannotBeCreatedOnDisk = "FolderCannotBeCreatedOnDisk";
internal const string FolderName = "FolderName";
internal const string FolderNameDescription = "FolderNameDescription";
internal const string FolderPathTooLongShortMessage = "FolderPathTooLongShortMessage";
internal const string FolderProperties = "FolderProperties";
internal const string FullPath = "FullPath";
internal const string FullPathDescription = "FullPathDescription";
internal const string General = "General";
internal const string ItemDoesNotExistInProjectDirectory = "ItemDoesNotExistInProjectDirectory";
internal const string InvalidAutomationObject = "InvalidAutomationObject";
internal const string InvalidLoggerType = "InvalidLoggerType";
internal const string InvalidParameter = "InvalidParameter";
internal const string LaunchUrl = "LaunchUrl";
internal const string LaunchUrlDescription = "LaunchUrlDescription";
internal const string Library = "Library";
internal const string LinkedItemsAreNotSupported = "LinkedItemsAreNotSupported";
internal const string Minimal = "Minimal";
internal const string Misc = "Misc";
internal const string None = "None";
internal const string Normal = "Normal";
internal const string NestedProjectFailedToReload = "NestedProjectFailedToReload";
internal const string OutputPath = "OutputPath";
internal const string OutputPathDescription = "OutputPathDescription";
internal const string OverwriteFilesInExistingFolder = "OverwriteFilesInExistingFolder";
internal const string PasteFailed = "PasteFailed";
internal const string ParameterMustBeAValidGuid = "ParameterMustBeAValidGuid";
internal const string ParameterMustBeAValidItemId = "ParameterMustBeAValidItemId";
internal const string ParameterCannotBeNullOrEmpty = "ParameterCannotBeNullOrEmpty";
internal const string PathTooLong = "PathTooLong";
internal const string PathTooLongShortMessage = "PathTooLongShortMessage";
internal const string ProjectContainsCircularReferences = "ProjectContainsCircularReferences";
internal const string Program = "Program";
internal const string Project = "Project";
internal const string ProjectFile = "ProjectFile";
internal const string ProjectFileDescription = "ProjectFileDescription";
internal const string ProjectFolder = "ProjectFolder";
internal const string ProjectFolderDescription = "ProjectFolderDescription";
internal const string ProjectHome = "ProjectHome";
internal const string ProjectHomeDescription = "ProjectHomeDescription";
internal const string ProjectProperties = "ProjectProperties";
internal const string Quiet = "Quiet";
internal const string QueryReloadNestedProject = "QueryReloadNestedProject";
internal const string ReferenceAlreadyExists = "ReferenceAlreadyExists";
internal const string ReferencesNodeName = "ReferencesNodeName";
internal const string ReferenceProperties = "ReferenceProperties";
internal const string RefName = "RefName";
internal const string RefNameDescription = "RefNameDescription";
internal const string RenameFolder = "RenameFolder";
internal const string Retry = "Retry";
internal const string RTL = "RTL";
internal const string SaveCaption = "SaveCaption";
internal const string SaveModifiedDocuments = "SaveModifiedDocuments";
internal const string SaveOfProjectFileOutsideCurrentDirectory = "SaveOfProjectFileOutsideCurrentDirectory";
internal const string ScriptArguments = "ScriptArguments";
internal const string ScriptArgumentsDescription = "ScriptArgumentsDescription";
internal const string SeeActivityLog = "SeeActivityLog";
internal const string Settings = "Settings";
internal const string SourceUrlNotFound = "SourceUrlNotFound";
internal const string StandardEditorViewError = "StandardEditorViewError";
internal const string StartupFile = "StartupFile";
internal const string StartupFileDescription = "StartupFileDescription";
internal const string StartWebBrowser = "StartWebBrowser";
internal const string StartWebBrowserDescription = "StartWebBrowserDescription";
internal const string UnknownInParentheses = "UnknownInParentheses";
internal const string URL = "URL";
internal const string UseOfDeletedItemError = "UseOfDeletedItemError";
internal const string v1 = "v1";
internal const string v11 = "v11";
internal const string v2 = "v2";
internal const string v3 = "v3";
internal const string v35 = "v35";
internal const string v4 = "v4";
internal const string Warning = "Warning";
internal const string WorkingDirectory = "WorkingDirectory";
internal const string WorkingDirectoryDescription = "WorkingDirectoryDescription";
internal const string WinExe = "WinExe";
internal const string Publish = "Publish";
internal const string PublishDescription = "PublishDescription";
internal const string WebPiFeed = "WebPiFeed";
internal const string WebPiProduct = "WebPiProduct";
internal const string WebPiFeedDescription = "WebPiFeedDescription";
internal const string WebPiFeedError = "WebPiFeedError";
internal const string WebPiProductDescription = "WebPiProductDescription";
internal const string WebPiReferenceProperties = "WebPiReferenceProperties";
internal const string UnexpectedUpgradeError = "UnexpectedUpgradeError";
internal const string UpgradeNotRequired = "UpgradeNotRequired";
internal const string UpgradeCannotCheckOutProject = "UpgradeCannotCheckOutProject";
internal const string UpgradeCannotLoadProject = "UpgradeCannotLoadProject";
private static readonly Lazy<ResourceManager> _manager = new Lazy<ResourceManager>(
() => new ResourceManager("Microsoft.VisualStudio.Project", typeof(SR).Assembly),
LazyThreadSafetyMode.ExecutionAndPublication
);
private static ResourceManager Manager => _manager.Value;
#if DEBUG
// Detect incorrect calls
[Obsolete]
internal static string GetString(string value, CultureInfo c)
{
return null;
}
#endif
protected static string GetStringInternal(ResourceManager manager, string value, object[] args)
{
var result = manager.GetString(value, CultureInfo.CurrentUICulture);
if (result == null)
{
return null;
}
if (args.Length == 0)
{
Debug.Assert(result.IndexOf("{0}") < 0, "Resource string '" + value + "' requires format arguments.");
return result;
}
Debug.WriteLineIf(
Enumerable.Range(0, args.Length).Any(i => result.IndexOf(string.Format("{{{0}", i)) < 0),
string.Format("Resource string '{0}' does not use all {1} arguments", value, args.Length)
);
Debug.WriteLineIf(
result.IndexOf(string.Format("{{{0}", args.Length)) >= 0,
string.Format("Resource string '{0}' requires more than {1} argument(s)", value, args.Length)
);
return string.Format(CultureInfo.CurrentUICulture, result, args);
}
public static string GetString(string value, params object[] args)
{
var result = GetStringInternal(Manager, value, args);
Debug.Assert(result != null, "String resource '" + value + "' is missing");
return result ?? value;
}
private const string UnhandledException = "UnhandledException";
/// <summary>
/// Gets a localized string suitable for logging details about an
/// otherwise unhandled exception. This should not generally be shown to
/// users through the UI.
/// </summary>
internal static string GetUnhandledExceptionString(
Exception ex,
Type callerType,
[CallerFilePath] string callerFile = null,
[CallerLineNumber] int callerLineNumber = 0,
[CallerMemberName] string callerName = null
)
{
if (string.IsNullOrEmpty(callerName))
{
callerName = callerType != null ? callerType.FullName : string.Empty;
}
else if (callerType != null)
{
callerName = callerType.FullName + "." + callerName;
}
return GetString(UnhandledException, ex, callerFile ?? string.Empty, callerLineNumber, callerName);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/distribution.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/distribution.proto</summary>
public static partial class DistributionReflection {
#region Descriptor
/// <summary>File descriptor for google/api/distribution.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DistributionReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch1nb29nbGUvYXBpL2Rpc3RyaWJ1dGlvbi5wcm90bxIKZ29vZ2xlLmFwaRoc",
"Z29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxoZZ29vZ2xlL3Byb3RvYnVm",
"L2FueS5wcm90bxofZ29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90byKu",
"BQoMRGlzdHJpYnV0aW9uEg0KBWNvdW50GAEgASgDEgwKBG1lYW4YAiABKAES",
"IAoYc3VtX29mX3NxdWFyZWRfZGV2aWF0aW9uGAMgASgBEi0KBXJhbmdlGAQg",
"ASgLMh4uZ29vZ2xlLmFwaS5EaXN0cmlidXRpb24uUmFuZ2USPgoOYnVja2V0",
"X29wdGlvbnMYBiABKAsyJi5nb29nbGUuYXBpLkRpc3RyaWJ1dGlvbi5CdWNr",
"ZXRPcHRpb25zEhUKDWJ1Y2tldF9jb3VudHMYByADKAMaIQoFUmFuZ2USCwoD",
"bWluGAEgASgBEgsKA21heBgCIAEoARq1AwoNQnVja2V0T3B0aW9ucxJHCg5s",
"aW5lYXJfYnVja2V0cxgBIAEoCzItLmdvb2dsZS5hcGkuRGlzdHJpYnV0aW9u",
"LkJ1Y2tldE9wdGlvbnMuTGluZWFySAASUQoTZXhwb25lbnRpYWxfYnVja2V0",
"cxgCIAEoCzIyLmdvb2dsZS5hcGkuRGlzdHJpYnV0aW9uLkJ1Y2tldE9wdGlv",
"bnMuRXhwb25lbnRpYWxIABJLChBleHBsaWNpdF9idWNrZXRzGAMgASgLMi8u",
"Z29vZ2xlLmFwaS5EaXN0cmlidXRpb24uQnVja2V0T3B0aW9ucy5FeHBsaWNp",
"dEgAGkMKBkxpbmVhchIaChJudW1fZmluaXRlX2J1Y2tldHMYASABKAUSDQoF",
"d2lkdGgYAiABKAESDgoGb2Zmc2V0GAMgASgBGk8KC0V4cG9uZW50aWFsEhoK",
"Em51bV9maW5pdGVfYnVja2V0cxgBIAEoBRIVCg1ncm93dGhfZmFjdG9yGAIg",
"ASgBEg0KBXNjYWxlGAMgASgBGhoKCEV4cGxpY2l0Eg4KBmJvdW5kcxgBIAMo",
"AUIJCgdvcHRpb25zQmoKDmNvbS5nb29nbGUuYXBpQhFEaXN0cmlidXRpb25Q",
"cm90b1ABWkNnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlz",
"L2FwaS9kaXN0cmlidXRpb247ZGlzdHJpYnV0aW9uYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Distribution), global::Google.Api.Distribution.Parser, new[]{ "Count", "Mean", "SumOfSquaredDeviation", "Range", "BucketOptions", "BucketCounts" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Distribution.Types.Range), global::Google.Api.Distribution.Types.Range.Parser, new[]{ "Min", "Max" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Distribution.Types.BucketOptions), global::Google.Api.Distribution.Types.BucketOptions.Parser, new[]{ "LinearBuckets", "ExponentialBuckets", "ExplicitBuckets" }, new[]{ "Options" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Distribution.Types.BucketOptions.Types.Linear), global::Google.Api.Distribution.Types.BucketOptions.Types.Linear.Parser, new[]{ "NumFiniteBuckets", "Width", "Offset" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Distribution.Types.BucketOptions.Types.Exponential), global::Google.Api.Distribution.Types.BucketOptions.Types.Exponential.Parser, new[]{ "NumFiniteBuckets", "GrowthFactor", "Scale" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Distribution.Types.BucketOptions.Types.Explicit), global::Google.Api.Distribution.Types.BucketOptions.Types.Explicit.Parser, new[]{ "Bounds" }, null, null, null)})})
}));
}
#endregion
}
#region Messages
/// <summary>
/// Distribution contains summary statistics for a population of values and,
/// optionally, a histogram representing the distribution of those values across
/// a specified set of histogram buckets.
///
/// The summary statistics are the count, mean, sum of the squared deviation from
/// the mean, the minimum, and the maximum of the set of population of values.
///
/// The histogram is based on a sequence of buckets and gives a count of values
/// that fall into each bucket. The boundaries of the buckets are given either
/// explicitly or by specifying parameters for a method of computing them
/// (buckets of fixed width or buckets of exponentially increasing width).
///
/// Although it is not forbidden, it is generally a bad idea to include
/// non-finite values (infinities or NaNs) in the population of values, as this
/// will render the `mean` and `sum_of_squared_deviation` fields meaningless.
/// </summary>
public sealed partial class Distribution : pb::IMessage<Distribution> {
private static readonly pb::MessageParser<Distribution> _parser = new pb::MessageParser<Distribution>(() => new Distribution());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Distribution> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.DistributionReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Distribution() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Distribution(Distribution other) : this() {
count_ = other.count_;
mean_ = other.mean_;
sumOfSquaredDeviation_ = other.sumOfSquaredDeviation_;
Range = other.range_ != null ? other.Range.Clone() : null;
BucketOptions = other.bucketOptions_ != null ? other.BucketOptions.Clone() : null;
bucketCounts_ = other.bucketCounts_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Distribution Clone() {
return new Distribution(this);
}
/// <summary>Field number for the "count" field.</summary>
public const int CountFieldNumber = 1;
private long count_;
/// <summary>
/// The number of values in the population. Must be non-negative.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Count {
get { return count_; }
set {
count_ = value;
}
}
/// <summary>Field number for the "mean" field.</summary>
public const int MeanFieldNumber = 2;
private double mean_;
/// <summary>
/// The arithmetic mean of the values in the population. If `count` is zero
/// then this field must be zero.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Mean {
get { return mean_; }
set {
mean_ = value;
}
}
/// <summary>Field number for the "sum_of_squared_deviation" field.</summary>
public const int SumOfSquaredDeviationFieldNumber = 3;
private double sumOfSquaredDeviation_;
/// <summary>
/// The sum of squared deviations from the mean of the values in the
/// population. For values x_i this is:
///
/// Sum[i=1..n]((x_i - mean)^2)
///
/// Knuth, "The Art of Computer Programming", Vol. 2, page 323, 3rd edition
/// describes Welford's method for accumulating this sum in one pass.
///
/// If `count` is zero then this field must be zero.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double SumOfSquaredDeviation {
get { return sumOfSquaredDeviation_; }
set {
sumOfSquaredDeviation_ = value;
}
}
/// <summary>Field number for the "range" field.</summary>
public const int RangeFieldNumber = 4;
private global::Google.Api.Distribution.Types.Range range_;
/// <summary>
/// If specified, contains the range of the population values. The field
/// must not be present if the `count` is zero.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Distribution.Types.Range Range {
get { return range_; }
set {
range_ = value;
}
}
/// <summary>Field number for the "bucket_options" field.</summary>
public const int BucketOptionsFieldNumber = 6;
private global::Google.Api.Distribution.Types.BucketOptions bucketOptions_;
/// <summary>
/// Defines the histogram bucket boundaries.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Distribution.Types.BucketOptions BucketOptions {
get { return bucketOptions_; }
set {
bucketOptions_ = value;
}
}
/// <summary>Field number for the "bucket_counts" field.</summary>
public const int BucketCountsFieldNumber = 7;
private static readonly pb::FieldCodec<long> _repeated_bucketCounts_codec
= pb::FieldCodec.ForInt64(58);
private readonly pbc::RepeatedField<long> bucketCounts_ = new pbc::RepeatedField<long>();
/// <summary>
/// If `bucket_options` is given, then the sum of the values in `bucket_counts`
/// must equal the value in `count`. If `bucket_options` is not given, no
/// `bucket_counts` fields may be given.
///
/// Bucket counts are given in order under the numbering scheme described
/// above (the underflow bucket has number 0; the finite buckets, if any,
/// have numbers 1 through N-2; the overflow bucket has number N-1).
///
/// The size of `bucket_counts` must be no greater than N as defined in
/// `bucket_options`.
///
/// Any suffix of trailing zero bucket_count fields may be omitted.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<long> BucketCounts {
get { return bucketCounts_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Distribution);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Distribution other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Count != other.Count) return false;
if (Mean != other.Mean) return false;
if (SumOfSquaredDeviation != other.SumOfSquaredDeviation) return false;
if (!object.Equals(Range, other.Range)) return false;
if (!object.Equals(BucketOptions, other.BucketOptions)) return false;
if(!bucketCounts_.Equals(other.bucketCounts_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Count != 0L) hash ^= Count.GetHashCode();
if (Mean != 0D) hash ^= Mean.GetHashCode();
if (SumOfSquaredDeviation != 0D) hash ^= SumOfSquaredDeviation.GetHashCode();
if (range_ != null) hash ^= Range.GetHashCode();
if (bucketOptions_ != null) hash ^= BucketOptions.GetHashCode();
hash ^= bucketCounts_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Count != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Count);
}
if (Mean != 0D) {
output.WriteRawTag(17);
output.WriteDouble(Mean);
}
if (SumOfSquaredDeviation != 0D) {
output.WriteRawTag(25);
output.WriteDouble(SumOfSquaredDeviation);
}
if (range_ != null) {
output.WriteRawTag(34);
output.WriteMessage(Range);
}
if (bucketOptions_ != null) {
output.WriteRawTag(50);
output.WriteMessage(BucketOptions);
}
bucketCounts_.WriteTo(output, _repeated_bucketCounts_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Count != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Count);
}
if (Mean != 0D) {
size += 1 + 8;
}
if (SumOfSquaredDeviation != 0D) {
size += 1 + 8;
}
if (range_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Range);
}
if (bucketOptions_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BucketOptions);
}
size += bucketCounts_.CalculateSize(_repeated_bucketCounts_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Distribution other) {
if (other == null) {
return;
}
if (other.Count != 0L) {
Count = other.Count;
}
if (other.Mean != 0D) {
Mean = other.Mean;
}
if (other.SumOfSquaredDeviation != 0D) {
SumOfSquaredDeviation = other.SumOfSquaredDeviation;
}
if (other.range_ != null) {
if (range_ == null) {
range_ = new global::Google.Api.Distribution.Types.Range();
}
Range.MergeFrom(other.Range);
}
if (other.bucketOptions_ != null) {
if (bucketOptions_ == null) {
bucketOptions_ = new global::Google.Api.Distribution.Types.BucketOptions();
}
BucketOptions.MergeFrom(other.BucketOptions);
}
bucketCounts_.Add(other.bucketCounts_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Count = input.ReadInt64();
break;
}
case 17: {
Mean = input.ReadDouble();
break;
}
case 25: {
SumOfSquaredDeviation = input.ReadDouble();
break;
}
case 34: {
if (range_ == null) {
range_ = new global::Google.Api.Distribution.Types.Range();
}
input.ReadMessage(range_);
break;
}
case 50: {
if (bucketOptions_ == null) {
bucketOptions_ = new global::Google.Api.Distribution.Types.BucketOptions();
}
input.ReadMessage(bucketOptions_);
break;
}
case 58:
case 56: {
bucketCounts_.AddEntriesFrom(input, _repeated_bucketCounts_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Distribution message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The range of the population values.
/// </summary>
public sealed partial class Range : pb::IMessage<Range> {
private static readonly pb::MessageParser<Range> _parser = new pb::MessageParser<Range>(() => new Range());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Range> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Distribution.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Range() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Range(Range other) : this() {
min_ = other.min_;
max_ = other.max_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Range Clone() {
return new Range(this);
}
/// <summary>Field number for the "min" field.</summary>
public const int MinFieldNumber = 1;
private double min_;
/// <summary>
/// The minimum of the population values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Min {
get { return min_; }
set {
min_ = value;
}
}
/// <summary>Field number for the "max" field.</summary>
public const int MaxFieldNumber = 2;
private double max_;
/// <summary>
/// The maximum of the population values.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Max {
get { return max_; }
set {
max_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Range);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Range other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Min != other.Min) return false;
if (Max != other.Max) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Min != 0D) hash ^= Min.GetHashCode();
if (Max != 0D) hash ^= Max.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Min != 0D) {
output.WriteRawTag(9);
output.WriteDouble(Min);
}
if (Max != 0D) {
output.WriteRawTag(17);
output.WriteDouble(Max);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Min != 0D) {
size += 1 + 8;
}
if (Max != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Range other) {
if (other == null) {
return;
}
if (other.Min != 0D) {
Min = other.Min;
}
if (other.Max != 0D) {
Max = other.Max;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
Min = input.ReadDouble();
break;
}
case 17: {
Max = input.ReadDouble();
break;
}
}
}
}
}
/// <summary>
/// A Distribution may optionally contain a histogram of the values in the
/// population. The histogram is given in `bucket_counts` as counts of values
/// that fall into one of a sequence of non-overlapping buckets. The sequence
/// of buckets is described by `bucket_options`.
///
/// A bucket specifies an inclusive lower bound and exclusive upper bound for
/// the values that are counted for that bucket. The upper bound of a bucket
/// is strictly greater than the lower bound.
///
/// The sequence of N buckets for a Distribution consists of an underflow
/// bucket (number 0), zero or more finite buckets (number 1 through N - 2) and
/// an overflow bucket (number N - 1). The buckets are contiguous: the lower
/// bound of bucket i (i > 0) is the same as the upper bound of bucket i - 1.
/// The buckets span the whole range of finite values: lower bound of the
/// underflow bucket is -infinity and the upper bound of the overflow bucket is
/// +infinity. The finite buckets are so-called because both bounds are
/// finite.
///
/// `BucketOptions` describes bucket boundaries in one of three ways. Two
/// describe the boundaries by giving parameters for a formula to generate
/// boundaries and one gives the bucket boundaries explicitly.
///
/// If `bucket_boundaries` is not given, then no `bucket_counts` may be given.
/// </summary>
public sealed partial class BucketOptions : pb::IMessage<BucketOptions> {
private static readonly pb::MessageParser<BucketOptions> _parser = new pb::MessageParser<BucketOptions>(() => new BucketOptions());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<BucketOptions> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Distribution.Descriptor.NestedTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BucketOptions() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BucketOptions(BucketOptions other) : this() {
switch (other.OptionsCase) {
case OptionsOneofCase.LinearBuckets:
LinearBuckets = other.LinearBuckets.Clone();
break;
case OptionsOneofCase.ExponentialBuckets:
ExponentialBuckets = other.ExponentialBuckets.Clone();
break;
case OptionsOneofCase.ExplicitBuckets:
ExplicitBuckets = other.ExplicitBuckets.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public BucketOptions Clone() {
return new BucketOptions(this);
}
/// <summary>Field number for the "linear_buckets" field.</summary>
public const int LinearBucketsFieldNumber = 1;
/// <summary>
/// The linear bucket.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Distribution.Types.BucketOptions.Types.Linear LinearBuckets {
get { return optionsCase_ == OptionsOneofCase.LinearBuckets ? (global::Google.Api.Distribution.Types.BucketOptions.Types.Linear) options_ : null; }
set {
options_ = value;
optionsCase_ = value == null ? OptionsOneofCase.None : OptionsOneofCase.LinearBuckets;
}
}
/// <summary>Field number for the "exponential_buckets" field.</summary>
public const int ExponentialBucketsFieldNumber = 2;
/// <summary>
/// The exponential buckets.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Distribution.Types.BucketOptions.Types.Exponential ExponentialBuckets {
get { return optionsCase_ == OptionsOneofCase.ExponentialBuckets ? (global::Google.Api.Distribution.Types.BucketOptions.Types.Exponential) options_ : null; }
set {
options_ = value;
optionsCase_ = value == null ? OptionsOneofCase.None : OptionsOneofCase.ExponentialBuckets;
}
}
/// <summary>Field number for the "explicit_buckets" field.</summary>
public const int ExplicitBucketsFieldNumber = 3;
/// <summary>
/// The explicit buckets.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Distribution.Types.BucketOptions.Types.Explicit ExplicitBuckets {
get { return optionsCase_ == OptionsOneofCase.ExplicitBuckets ? (global::Google.Api.Distribution.Types.BucketOptions.Types.Explicit) options_ : null; }
set {
options_ = value;
optionsCase_ = value == null ? OptionsOneofCase.None : OptionsOneofCase.ExplicitBuckets;
}
}
private object options_;
/// <summary>Enum of possible cases for the "options" oneof.</summary>
public enum OptionsOneofCase {
None = 0,
LinearBuckets = 1,
ExponentialBuckets = 2,
ExplicitBuckets = 3,
}
private OptionsOneofCase optionsCase_ = OptionsOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OptionsOneofCase OptionsCase {
get { return optionsCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearOptions() {
optionsCase_ = OptionsOneofCase.None;
options_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as BucketOptions);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(BucketOptions other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(LinearBuckets, other.LinearBuckets)) return false;
if (!object.Equals(ExponentialBuckets, other.ExponentialBuckets)) return false;
if (!object.Equals(ExplicitBuckets, other.ExplicitBuckets)) return false;
if (OptionsCase != other.OptionsCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (optionsCase_ == OptionsOneofCase.LinearBuckets) hash ^= LinearBuckets.GetHashCode();
if (optionsCase_ == OptionsOneofCase.ExponentialBuckets) hash ^= ExponentialBuckets.GetHashCode();
if (optionsCase_ == OptionsOneofCase.ExplicitBuckets) hash ^= ExplicitBuckets.GetHashCode();
hash ^= (int) optionsCase_;
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (optionsCase_ == OptionsOneofCase.LinearBuckets) {
output.WriteRawTag(10);
output.WriteMessage(LinearBuckets);
}
if (optionsCase_ == OptionsOneofCase.ExponentialBuckets) {
output.WriteRawTag(18);
output.WriteMessage(ExponentialBuckets);
}
if (optionsCase_ == OptionsOneofCase.ExplicitBuckets) {
output.WriteRawTag(26);
output.WriteMessage(ExplicitBuckets);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (optionsCase_ == OptionsOneofCase.LinearBuckets) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(LinearBuckets);
}
if (optionsCase_ == OptionsOneofCase.ExponentialBuckets) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExponentialBuckets);
}
if (optionsCase_ == OptionsOneofCase.ExplicitBuckets) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExplicitBuckets);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(BucketOptions other) {
if (other == null) {
return;
}
switch (other.OptionsCase) {
case OptionsOneofCase.LinearBuckets:
LinearBuckets = other.LinearBuckets;
break;
case OptionsOneofCase.ExponentialBuckets:
ExponentialBuckets = other.ExponentialBuckets;
break;
case OptionsOneofCase.ExplicitBuckets:
ExplicitBuckets = other.ExplicitBuckets;
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
global::Google.Api.Distribution.Types.BucketOptions.Types.Linear subBuilder = new global::Google.Api.Distribution.Types.BucketOptions.Types.Linear();
if (optionsCase_ == OptionsOneofCase.LinearBuckets) {
subBuilder.MergeFrom(LinearBuckets);
}
input.ReadMessage(subBuilder);
LinearBuckets = subBuilder;
break;
}
case 18: {
global::Google.Api.Distribution.Types.BucketOptions.Types.Exponential subBuilder = new global::Google.Api.Distribution.Types.BucketOptions.Types.Exponential();
if (optionsCase_ == OptionsOneofCase.ExponentialBuckets) {
subBuilder.MergeFrom(ExponentialBuckets);
}
input.ReadMessage(subBuilder);
ExponentialBuckets = subBuilder;
break;
}
case 26: {
global::Google.Api.Distribution.Types.BucketOptions.Types.Explicit subBuilder = new global::Google.Api.Distribution.Types.BucketOptions.Types.Explicit();
if (optionsCase_ == OptionsOneofCase.ExplicitBuckets) {
subBuilder.MergeFrom(ExplicitBuckets);
}
input.ReadMessage(subBuilder);
ExplicitBuckets = subBuilder;
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the BucketOptions message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Specify a sequence of buckets that all have the same width (except
/// overflow and underflow). Each bucket represents a constant absolute
/// uncertainty on the specific value in the bucket.
///
/// Defines `num_finite_buckets + 2` (= N) buckets with these boundaries for
/// bucket `i`:
///
/// Upper bound (0 <= i < N-1): offset + (width * i).
/// Lower bound (1 <= i < N): offset + (width * (i - 1)).
/// </summary>
public sealed partial class Linear : pb::IMessage<Linear> {
private static readonly pb::MessageParser<Linear> _parser = new pb::MessageParser<Linear>(() => new Linear());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Linear> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Distribution.Types.BucketOptions.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Linear() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Linear(Linear other) : this() {
numFiniteBuckets_ = other.numFiniteBuckets_;
width_ = other.width_;
offset_ = other.offset_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Linear Clone() {
return new Linear(this);
}
/// <summary>Field number for the "num_finite_buckets" field.</summary>
public const int NumFiniteBucketsFieldNumber = 1;
private int numFiniteBuckets_;
/// <summary>
/// Must be greater than 0.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int NumFiniteBuckets {
get { return numFiniteBuckets_; }
set {
numFiniteBuckets_ = value;
}
}
/// <summary>Field number for the "width" field.</summary>
public const int WidthFieldNumber = 2;
private double width_;
/// <summary>
/// Must be greater than 0.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Width {
get { return width_; }
set {
width_ = value;
}
}
/// <summary>Field number for the "offset" field.</summary>
public const int OffsetFieldNumber = 3;
private double offset_;
/// <summary>
/// Lower bound of the first bucket.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Offset {
get { return offset_; }
set {
offset_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Linear);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Linear other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (NumFiniteBuckets != other.NumFiniteBuckets) return false;
if (Width != other.Width) return false;
if (Offset != other.Offset) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (NumFiniteBuckets != 0) hash ^= NumFiniteBuckets.GetHashCode();
if (Width != 0D) hash ^= Width.GetHashCode();
if (Offset != 0D) hash ^= Offset.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (NumFiniteBuckets != 0) {
output.WriteRawTag(8);
output.WriteInt32(NumFiniteBuckets);
}
if (Width != 0D) {
output.WriteRawTag(17);
output.WriteDouble(Width);
}
if (Offset != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Offset);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (NumFiniteBuckets != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumFiniteBuckets);
}
if (Width != 0D) {
size += 1 + 8;
}
if (Offset != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Linear other) {
if (other == null) {
return;
}
if (other.NumFiniteBuckets != 0) {
NumFiniteBuckets = other.NumFiniteBuckets;
}
if (other.Width != 0D) {
Width = other.Width;
}
if (other.Offset != 0D) {
Offset = other.Offset;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
NumFiniteBuckets = input.ReadInt32();
break;
}
case 17: {
Width = input.ReadDouble();
break;
}
case 25: {
Offset = input.ReadDouble();
break;
}
}
}
}
}
/// <summary>
/// Specify a sequence of buckets that have a width that is proportional to
/// the value of the lower bound. Each bucket represents a constant relative
/// uncertainty on a specific value in the bucket.
///
/// Defines `num_finite_buckets + 2` (= N) buckets with these boundaries for
/// bucket i:
///
/// Upper bound (0 <= i < N-1): scale * (growth_factor ^ i).
/// Lower bound (1 <= i < N): scale * (growth_factor ^ (i - 1)).
/// </summary>
public sealed partial class Exponential : pb::IMessage<Exponential> {
private static readonly pb::MessageParser<Exponential> _parser = new pb::MessageParser<Exponential>(() => new Exponential());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Exponential> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Distribution.Types.BucketOptions.Descriptor.NestedTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Exponential() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Exponential(Exponential other) : this() {
numFiniteBuckets_ = other.numFiniteBuckets_;
growthFactor_ = other.growthFactor_;
scale_ = other.scale_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Exponential Clone() {
return new Exponential(this);
}
/// <summary>Field number for the "num_finite_buckets" field.</summary>
public const int NumFiniteBucketsFieldNumber = 1;
private int numFiniteBuckets_;
/// <summary>
/// Must be greater than 0.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int NumFiniteBuckets {
get { return numFiniteBuckets_; }
set {
numFiniteBuckets_ = value;
}
}
/// <summary>Field number for the "growth_factor" field.</summary>
public const int GrowthFactorFieldNumber = 2;
private double growthFactor_;
/// <summary>
/// Must be greater than 1.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double GrowthFactor {
get { return growthFactor_; }
set {
growthFactor_ = value;
}
}
/// <summary>Field number for the "scale" field.</summary>
public const int ScaleFieldNumber = 3;
private double scale_;
/// <summary>
/// Must be greater than 0.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Scale {
get { return scale_; }
set {
scale_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Exponential);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Exponential other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (NumFiniteBuckets != other.NumFiniteBuckets) return false;
if (GrowthFactor != other.GrowthFactor) return false;
if (Scale != other.Scale) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (NumFiniteBuckets != 0) hash ^= NumFiniteBuckets.GetHashCode();
if (GrowthFactor != 0D) hash ^= GrowthFactor.GetHashCode();
if (Scale != 0D) hash ^= Scale.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (NumFiniteBuckets != 0) {
output.WriteRawTag(8);
output.WriteInt32(NumFiniteBuckets);
}
if (GrowthFactor != 0D) {
output.WriteRawTag(17);
output.WriteDouble(GrowthFactor);
}
if (Scale != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Scale);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (NumFiniteBuckets != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumFiniteBuckets);
}
if (GrowthFactor != 0D) {
size += 1 + 8;
}
if (Scale != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Exponential other) {
if (other == null) {
return;
}
if (other.NumFiniteBuckets != 0) {
NumFiniteBuckets = other.NumFiniteBuckets;
}
if (other.GrowthFactor != 0D) {
GrowthFactor = other.GrowthFactor;
}
if (other.Scale != 0D) {
Scale = other.Scale;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
NumFiniteBuckets = input.ReadInt32();
break;
}
case 17: {
GrowthFactor = input.ReadDouble();
break;
}
case 25: {
Scale = input.ReadDouble();
break;
}
}
}
}
}
/// <summary>
/// A set of buckets with arbitrary widths.
///
/// Defines `size(bounds) + 1` (= N) buckets with these boundaries for
/// bucket i:
///
/// Upper bound (0 <= i < N-1): bounds[i]
/// Lower bound (1 <= i < N); bounds[i - 1]
///
/// There must be at least one element in `bounds`. If `bounds` has only one
/// element, there are no finite buckets, and that single element is the
/// common boundary of the overflow and underflow buckets.
/// </summary>
public sealed partial class Explicit : pb::IMessage<Explicit> {
private static readonly pb::MessageParser<Explicit> _parser = new pb::MessageParser<Explicit>(() => new Explicit());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Explicit> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Distribution.Types.BucketOptions.Descriptor.NestedTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Explicit() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Explicit(Explicit other) : this() {
bounds_ = other.bounds_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Explicit Clone() {
return new Explicit(this);
}
/// <summary>Field number for the "bounds" field.</summary>
public const int BoundsFieldNumber = 1;
private static readonly pb::FieldCodec<double> _repeated_bounds_codec
= pb::FieldCodec.ForDouble(10);
private readonly pbc::RepeatedField<double> bounds_ = new pbc::RepeatedField<double>();
/// <summary>
/// The values must be monotonically increasing.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<double> Bounds {
get { return bounds_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Explicit);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Explicit other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!bounds_.Equals(other.bounds_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= bounds_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
bounds_.WriteTo(output, _repeated_bounds_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += bounds_.CalculateSize(_repeated_bounds_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Explicit other) {
if (other == null) {
return;
}
bounds_.Add(other.bounds_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 9: {
bounds_.AddEntriesFrom(input, _repeated_bounds_codec);
break;
}
}
}
}
}
}
#endregion
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Threading;
using System.Collections.Generic;
namespace NUnit.Framework.Syntax
{
// NOTE: The tests in this file ensure that the various
// syntactic elements work together to create a
// DelayedConstraint object with the proper values.
public class AfterTest_SimpleConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<after 1000 <equal 10>>";
StaticSyntax = Is.EqualTo(10).After(1000);
BuilderSyntax = Builder().EqualTo(10).After(1000);
}
}
public class AfterMinutesTest_SimpleConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<after 60000 <equal 10>>";
StaticSyntax = Is.EqualTo(10).After(1).Minutes;
BuilderSyntax = Builder().EqualTo(10).After(1).Minutes;
}
}
public class AfterSecondsTest_SimpleConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<after 20000 <equal 10>>";
StaticSyntax = Is.EqualTo(10).After(20).Seconds;
BuilderSyntax = Builder().EqualTo(10).After(20).Seconds;
}
}
public class AfterMillisecondsTest_SimpleConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<after 500 <equal 10>>";
StaticSyntax = Is.EqualTo(10).After(500).MilliSeconds;
BuilderSyntax = Builder().EqualTo(10).After(500).MilliSeconds;
}
}
public class AfterTest_PropertyTest : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<after 1000 <property X <equal 10>>>";
StaticSyntax = Has.Property("X").EqualTo(10).After(1000);
BuilderSyntax = Builder().Property("X").EqualTo(10).After(1000);
}
}
public class AfterTest_AndOperator : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<after 1000 <and <greaterthan 0> <lessthan 10>>>";
StaticSyntax = Is.GreaterThan(0).And.LessThan(10).After(1000);
BuilderSyntax = Builder().GreaterThan(0).And.LessThan(10).After(1000);
}
}
public abstract class AfterSyntaxTests
{
protected bool Flag;
protected int Num;
protected object Ob1, Ob2, Ob3;
protected List<object> List;
protected string Greeting;
[SetUp]
public void InitializeValues()
{
this.Flag = false;
this.Num = 0;
this.Ob1 = new object();
this.Ob2 = new object();
this.Ob3 = new object();
this.List = new List<object>();
this.List.Add(1);
this.List.Add(2);
this.List.Add(3);
this.Greeting = "hello";
new Thread(ModifyValuesAfterDelay).Start();
}
private void ModifyValuesAfterDelay()
{
Thread.Sleep(100);
this.Flag = true;
this.Num = 1;
this.Ob1 = Ob2;
this.Ob3 = null;
this.List.Add(4);
this.Greeting += "world";
}
}
public class AfterSyntaxUsingAnonymousDelegates : AfterSyntaxTests
{
[Test]
public void TrueTest()
{
Assert.That(delegate { return Flag; }, Is.True.After(5000, 200));
}
[Test]
public void EqualToTest()
{
Assert.That(delegate { return Num; }, Is.EqualTo(1).After(5000, 200));
}
[Test]
public void SameAsTest()
{
Assert.That(delegate { return Ob1; }, Is.SameAs(Ob2).After(5000, 200));
}
[Test]
public void GreaterTest()
{
Assert.That(delegate { return Num; }, Is.GreaterThan(0).After(5000,200));
}
[Test]
public void HasMemberTest()
{
Assert.That(delegate { return List; }, Has.Member(4).After(5000, 200));
}
[Test]
public void NullTest()
{
Assert.That(delegate { return Ob3; }, Is.Null.After(5000, 200));
}
[Test]
public void TextTest()
{
Assert.That(delegate { return Greeting; }, Does.EndWith("world").After(5000, 200));
}
}
public class AfterSyntaxUsingLambda : AfterSyntaxTests
{
[Test]
public void TrueTest()
{
Assert.That(() => Flag, Is.True.After(5000, 200));
}
[Test]
public void EqualToTest()
{
Assert.That(() => Num, Is.EqualTo(1).After(5000, 200));
}
[Test]
public void SameAsTest()
{
Assert.That(() => Ob1, Is.SameAs(Ob2).After(5000, 200));
}
[Test]
public void GreaterTest()
{
Assert.That(() => Num, Is.GreaterThan(0).After(5000, 200));
}
[Test]
public void HasMemberTest()
{
Assert.That(() => List, Has.Member(4).After(5000, 200));
}
[Test]
public void NullTest()
{
Assert.That(() => Ob3, Is.Null.After(5000, 200));
}
[Test]
public void TextTest()
{
Assert.That(() => Greeting, Does.EndWith("world").After(5000, 200));
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.IO;
using CoinSharp.IO;
using CoinSharp.TransactionScript;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities.Encoders;
namespace CoinSharp
{
/// <summary>
/// NetworkParameters contains the data needed for working with an instantiation of a BitCoin chain.
/// </summary>
/// <remarks>
/// Currently there are only two, the production chain and the test chain. But in future as BitCoin
/// evolves there may be more. You can create your own as long as they don't conflict.
/// </remarks>
[Serializable]
public class NetworkParameters
{
/// <summary>
/// The protocol version this library implements. A value of 31800 means 0.3.18.00.
/// </summary>
public const uint ProtocolVersion = 60001;
private static readonly byte[] SatoshiKey = Hex.Decode("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284");
// TODO: Seed nodes and checkpoint values should be here as well.
/// <summary>
/// Genesis block for this chain.
/// </summary>
/// <remarks>
/// The first block in every chain is a well known constant shared between all BitCoin implementations. For a
/// block to be valid, it must be eventually possible to work backwards to the genesis block by following the
/// prevBlockHash pointers in the block headers.<p/>
/// The genesis blocks for both test and prod networks contain the timestamp of when they were created,
/// and a message in the coinbase transaction. It says, <i>"The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"</i>.
/// </remarks>
public Block GenesisBlock { get; private set; }
/// <summary>
/// What the easiest allowable proof of work should be.
/// </summary>
public BigInteger ProofOfWorkLimit { get; set; }
/// <summary>
/// Default TCP port on which to connect to nodes.
/// </summary>
public int Port { get; private set; }
/// <summary>
/// The header bytes that identify the start of a packet on this network.
/// </summary>
public uint PacketMagic { get; private set; }
/// <summary>
/// First byte of a base58 encoded address. See <see cref="Address"/>
/// </summary>
public int AddressHeader { get; private set; }
/// <summary>
/// First byte of a base58 encoded dumped private key. See <see cref="DumpedPrivateKey"/>.
/// </summary>
public int DumpedPrivateKeyHeader { get; private set; }
/// <summary>
/// How many blocks pass between difficulty adjustment periods. BitCoin standardises this to be 2015.
/// </summary>
public int Interval { get; private set; }
/// <summary>
/// How much time in seconds is supposed to pass between "interval" blocks. If the actual elapsed time is
/// significantly different from this value, the network difficulty formula will produce a different value. Both
/// test and production BitCoin networks use 2 weeks (1209600 seconds).
/// </summary>
public int TargetTimespan { get; private set; }
public byte[] AlertSigningKey { get; private set; }
private static Block CreateGenesis(NetworkParameters n)
{
var genesisBlock = new Block(n);
var t = new Transaction(n);
// A script containing the difficulty bits and the following message:
//
// "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"
var bytes = Hex.Decode("04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73");
t.AddInput(new TransactionInput(n, t, bytes));
using (var scriptPubKeyBytes = new MemoryStream())
{
Script.WriteBytes(scriptPubKeyBytes, Hex.Decode("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"));
scriptPubKeyBytes.WriteByte((byte) OpCode.OP_CHECKSIG);
t.AddOutput(new TransactionOutput(n, t, scriptPubKeyBytes.ToArray()));
}
genesisBlock.AddTransaction(t);
return genesisBlock;
}
private const int _targetTimespan = 14 * 24 * 60 * 60; // 2 weeks per difficulty cycle, on average.
private const int _targetSpacing = 10 * 60; // 10 minutes per block.
private const int _interval = _targetTimespan / _targetSpacing;
/// <summary>
/// Sets up the given NetworkParameters with testnet values.
/// </summary>
private static NetworkParameters CreateTestNet(NetworkParameters n)
{
// Genesis hash is 0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110
// The proof of work limit has to start with 00, as otherwise the value will be interpreted as negative.
n.ProofOfWorkLimit = new BigInteger("0000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
n.PacketMagic = 0xfabfb5da;
n.Port = 18333;
n.AddressHeader = 111;
n.DumpedPrivateKeyHeader = 239;
n.Interval = _interval;
n.TargetTimespan = _targetTimespan;
n.GenesisBlock = CreateGenesis(n);
n.GenesisBlock.TimeSeconds = 1296688602;
n.GenesisBlock.DifficultyTarget = 0x1d07fff8;
n.GenesisBlock.Nonce = 384568319;
n.AlertSigningKey = SatoshiKey;
var genesisHash = n.GenesisBlock.HashAsString;
Debug.Assert(genesisHash.Equals("00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008"), genesisHash);
return n;
}
/// <summary>
/// Sets up the given NetworkParameters with testnet values.
/// </summary>
private static NetworkParameters CreateTestNet3(NetworkParameters n)
{
// Genesis hash is 0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110
// The proof of work limit has to start with 00, as otherwise the value will be interpreted as negative.
n.ProofOfWorkLimit = new BigInteger("0000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
n.PacketMagic = 0x0b110907;
n.Port = 18333;
n.AddressHeader = 111;
n.DumpedPrivateKeyHeader = 239;
n.Interval = _interval;
n.TargetTimespan = _targetTimespan;
n.GenesisBlock = CreateGenesis(n);
n.GenesisBlock.TimeSeconds = 1296688602;
n.GenesisBlock.DifficultyTarget = 0x1d00ffff;
n.GenesisBlock.Nonce = 414098458;
n.AlertSigningKey = SatoshiKey;
var genesisHash = n.GenesisBlock.HashAsString;
Debug.Assert(genesisHash.Equals("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"), genesisHash);
return n;
}
/// <summary>
/// The test chain created by Gavin.
/// </summary>
public static NetworkParameters TestNet()
{
var n = new NetworkParameters();
return CreateTestNet3(n);
}
/// <summary>
/// The test chain created by Gavin.
/// </summary>
public static NetworkParameters TestNet(int port)
{
var tn = CreateTestNet3(new NetworkParameters());
tn.Port = port;
return tn;
}
/// <summary>
/// The primary BitCoin chain created by Satoshi.
/// </summary>
public static NetworkParameters ProdNet()
{
var n = new NetworkParameters();
n.ProofOfWorkLimit = new BigInteger("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
n.Port = 8333;
n.PacketMagic = 0xf9beb4d9;
n.AddressHeader = 0;
n.DumpedPrivateKeyHeader = 128;
n.Interval = _interval;
n.TargetTimespan = _targetTimespan;
n.GenesisBlock = CreateGenesis(n);
n.GenesisBlock.DifficultyTarget = 0x1d00ffff;
n.GenesisBlock.TimeSeconds = 1231006505;
n.GenesisBlock.Nonce = 2083236893;
n.AlertSigningKey = SatoshiKey;
var genesisHash = n.GenesisBlock.HashAsString;
Debug.Assert(genesisHash.Equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisHash);
return n;
}
/// <summary>
/// Returns a testnet params modified to allow any difficulty target.
/// </summary>
public static NetworkParameters UnitTests()
{
var n = new NetworkParameters();
n = CreateTestNet(n);
n.ProofOfWorkLimit = new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
n.GenesisBlock.DifficultyTarget = Block.EasiestDifficultyTarget;
n.Interval = 10;
n.TargetTimespan = 200000000; // 6 years. Just a very big number.
return n;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using System.Threading;
namespace System.Net.Sockets.Tests
{
// TODO (#7852):
//
// - Connect(EndPoint):
// - disconnected socket
// - Accept(EndPoint):
// - disconnected socket
//
// End*:
// - Invalid asyncresult type
// - asyncresult from different object
// - asyncresult with end already called
public class ArgumentValidation
{
// This type is used to test Socket.Select's argument validation.
private sealed class LargeList : IList
{
private const int MaxSelect = 65536;
public int Count { get { return MaxSelect + 1; } }
public bool IsFixedSize { get { return true; } }
public bool IsReadOnly { get { return true; } }
public bool IsSynchronized { get { return false; } }
public object SyncRoot { get { return null; } }
public object this[int index]
{
get { return null; }
set { }
}
public int Add(object value) { return -1; }
public void Clear() { }
public bool Contains(object value) { return false; }
public void CopyTo(Array array, int index) { }
public IEnumerator GetEnumerator() { return null; }
public int IndexOf(object value) { return -1; }
public void Insert(int index, object value) { }
public void Remove(object value) { }
public void RemoveAt(int index) { }
}
private readonly static byte[] s_buffer = new byte[1];
private readonly static IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) };
private readonly static SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs();
private readonly static Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private readonly static Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
private static void TheAsyncCallback(IAsyncResult ar)
{
}
private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork)
{
Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6);
return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket;
}
[Fact]
public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() =>
{
socket.ExclusiveAddressUse = true;
});
}
}
[Fact]
public void SetReceiveBufferSize_Negative_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().ReceiveBufferSize = -1;
});
}
[Fact]
public void SetSendBufferSize_Negative_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().SendBufferSize = -1;
});
}
[Fact]
public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().ReceiveTimeout = int.MinValue;
});
}
[Fact]
public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().SendTimeout = int.MinValue;
});
}
[Fact]
public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().Ttl = -1;
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
GetSocket().Ttl = 256;
});
}
[Fact]
public void DontFragment_IPv6_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment);
}
[Fact]
public void SetDontFragment_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() =>
{
GetSocket(AddressFamily.InterNetworkV6).DontFragment = true;
});
}
[Fact]
public void Bind_Throws_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null));
}
[Fact]
public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null));
}
[Fact]
public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1)));
}
}
[Fact]
public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1));
}
[Fact]
public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536));
}
[Fact]
public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1));
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1));
}
[Fact]
public void Connect_Host_NullHost_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1));
}
[Fact]
public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536));
}
[Fact]
public void Connect_IPAddresses_NullArray_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1));
}
[Fact]
public void Connect_IPAddresses_EmptyArray_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().Connect(new IPAddress[0], 1));
}
[Fact]
public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536));
}
[Fact]
public void Accept_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().Accept());
}
[Fact]
public void Accept_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.Accept());
}
}
[Fact]
public void Send_Buffer_NullBuffer_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffers_NullBuffers_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, SocketFlags.None, out errorCode));
}
[Fact]
public void Send_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
Assert.Throws<ArgumentException>(() => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
public void SendTo_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)));
}
[Fact]
public void SendTo_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null));
}
[Fact]
public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint));
}
[Fact]
public void SendTo_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint));
}
[Fact]
public void Receive_Buffer_NullBuffer_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
SocketError errorCode;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffers_NullBuffers_Throws_ArgumentNull()
{
SocketError errorCode;
Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, SocketFlags.None, out errorCode));
}
[Fact]
public void Receive_Buffers_EmptyBuffers_Throws_Argument()
{
SocketError errorCode;
Assert.Throws<ArgumentException>(() => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode));
}
[Fact]
public void ReceiveFrom_NullBuffer_Throws_ArgumentNull()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull()
{
EndPoint endpoint = null;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_AddressFamily_Throws_Argument()
{
EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveFrom_NotBound_Throws_InvalidOperation()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint));
}
[Fact]
public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = null;
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_AddressFamily_Throws_Argument()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo));
}
[Fact]
public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo));
}
[Fact]
public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null));
}
[Fact]
public void SetSocketOption_Linger_NotLingerOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object()));
}
[Fact]
public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1)));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1)));
}
[Fact]
public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object()));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object()));
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object()));
}
[Fact]
public void SetSocketOption_Object_InvalidOptionName_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object()));
}
[Fact]
public void Select_NullOrEmptyLists_Throws_ArgumentNull()
{
var emptyList = new List<Socket>();
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1));
Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1));
}
[Fact]
public void Select_LargeList_Throws_ArgumentOutOfRange()
{
var largeList = new LargeList();
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1));
}
[Fact]
public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null));
}
[Fact]
public void AcceptAsync_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => GetSocket().AcceptAsync(eventArgs));
}
[Fact]
public void AcceptAsync_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs));
}
[Fact]
public void AcceptAsync_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs));
}
}
[Fact]
public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null));
}
[Fact]
public void ConnectAsync_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => GetSocket().ConnectAsync(eventArgs));
}
[Fact]
public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs));
}
[Fact]
public void ConnectAsync_ListeningSocket_Throws_InvalidOperation()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1)
};
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs));
}
}
[Fact]
public void ConnectAsync_AddressFamily_Throws_NotSupported()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)
};
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs));
eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs));
}
[Fact]
public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null));
}
[Fact]
public void ConnectAsync_Static_BufferList_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
BufferList = s_buffers
};
Assert.Throws<ArgumentException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs));
}
[Fact]
public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs));
}
[Fact]
public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null));
}
[Fact]
public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null));
}
[Fact]
public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs));
}
[Fact]
public void ReceiveFromAsync_AddressFamily_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs));
}
[Fact]
public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null));
}
[Fact]
public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs));
}
[Fact]
public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument()
{
var eventArgs = new SocketAsyncEventArgs {
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs));
}
[Fact]
public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null));
}
[Fact]
public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null));
}
[Fact]
public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs));
}
[Fact]
public void SendPacketsAsync_NotConnected_Throws_NotSupported()
{
var eventArgs = new SocketAsyncEventArgs {
SendPacketsElements = new SendPacketsElement[0]
};
Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs));
}
[Fact]
public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null));
}
[Fact]
public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs));
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Socket_Connect_DnsEndPoint_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345)));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Socket_Connect_StringHost_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Socket_Connect_MultipleAddresses_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Socket_ConnectAsync_DnsEndPoint_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); });
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Socket_ConnectAsync_StringHost_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); });
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Socket_ConnectAsync_MultipleAddresses_NotSupported()
{
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new[] { IPAddress.Loopback }, 12345); });
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Connect_ConnectTwice_NotSupported()
{
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
//
// Connect once, to an invalid address, expecting failure
//
EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234);
Assert.ThrowsAny<SocketException>(() => client.Connect(ep));
//
// Connect again, expecting PlatformNotSupportedException
//
Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void ConnectAsync_ConnectTwice_NotSupported()
{
AutoResetEvent completed = new AutoResetEvent(false);
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
//
// Connect once, to an invalid address, expecting failure
//
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234);
args.Completed += delegate
{
completed.Set();
};
if (client.ConnectAsync(args))
{
Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection");
}
Assert.NotEqual(SocketError.Success, args.SocketError);
//
// Connect again, expecting PlatformNotSupportedException
//
Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args));
}
}
[Fact]
public void BeginAccept_NotBound_Throws_InvalidOperation()
{
Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null));
}
[Fact]
public void BeginAccept_NotListening_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null));
}
}
[Fact]
public void EndAccept_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null));
}
[Fact]
public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_Host_NullHost_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", -1, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", 65536, TheAsyncCallback, null));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null));
}
}
[Fact]
public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, -1, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, 65536, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported()
{
Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null));
}
[Fact]
public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, -1, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, 65536, TheAsyncCallback, null));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.Listen(1);
Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null));
}
}
[Fact]
public void EndConnect_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null));
}
[Fact]
public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginSend_Buffers_EmptyBuffers_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void EndSend_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null));
}
[Fact]
public void BeginSendTo_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null));
}
[Fact]
public void BeginSendTo_NullEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null));
}
[Fact]
public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null));
}
[Fact]
public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null));
}
[Fact]
public void EndSendTo_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null));
}
[Fact]
public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument()
{
Assert.Throws<ArgumentException>(() => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null));
}
[Fact]
public void EndReceive_NullAsyncResult_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null));
}
[Fact]
public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull()
{
EndPoint endpoint = null;
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveFrom_AddressFamily_Throws_Argument()
{
EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveFrom_NotBound_Throws_InvalidOperation()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null));
}
[Fact]
public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull()
{
EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint));
}
[Fact]
public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull()
{
EndPoint remote = null;
Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument()
{
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null));
Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation()
{
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null));
}
[Fact]
public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = null;
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
[Fact]
public void EndReceiveMessageFrom_AddressFamily_Throws_Argument()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1);
IPPacketInformation packetInfo;
// Behavior difference from Desktop: used to throw ArgumentException.
Assert.Throws<ArgumentNullException>(() => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
[Fact]
public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull()
{
SocketFlags flags = SocketFlags.None;
EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1);
IPPacketInformation packetInfo;
Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo));
}
}
}
| |
//
// SaslMechanismDigestMd5.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2014 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Net;
using System.Text;
using System.Collections.Generic;
#if NETFX_CORE
using Encoding = Portable.Text.Encoding;
using MD5 = MimeKit.Cryptography.MD5;
#else
using MD5 = System.Security.Cryptography.MD5CryptoServiceProvider;
using System.Security.Cryptography;
#endif
namespace MailKit.Security {
/// <summary>
/// The DIGEST-MD5 SASL mechanism.
/// </summary>
/// <remarks>
/// Unlike the PLAIN and LOGIN SASL mechanisms, the DIGEST-MD5 mechanism
/// provides some level of protection and should be relatively safe to
/// use even with a clear-text connection.
/// </remarks>
public class SaslMechanismDigestMd5 : SaslMechanism
{
enum LoginState {
Auth,
Final
}
DigestChallenge challenge;
DigestResponse response;
LoginState state;
string cnonce;
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanismDigestMd5"/> class.
/// </summary>
/// <remarks>
/// Creates a new DIGEST-MD5 SASL context.
/// </remarks>
/// <param name="uri">The URI of the service.</param>
/// <param name="credentials">The user's credentials.</param>
/// <param name="entropy">Random characters to act as the cnonce token.</param>
internal SaslMechanismDigestMd5 (Uri uri, ICredentials credentials, string entropy) : base (uri, credentials)
{
cnonce = entropy;
}
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanismDigestMd5"/> class.
/// </summary>
/// <remarks>
/// Creates a new DIGEST-MD5 SASL context.
/// </remarks>
/// <param name="uri">The URI of the service.</param>
/// <param name="credentials">The user's credentials.</param>
public SaslMechanismDigestMd5 (Uri uri, ICredentials credentials) : base (uri, credentials)
{
}
/// <summary>
/// Gets the name of the mechanism.
/// </summary>
/// <remarks>
/// Gets the name of the mechanism.
/// </remarks>
/// <value>The name of the mechanism.</value>
public override string MechanismName {
get { return "DIGEST-MD5"; }
}
/// <summary>
/// Parses the server's challenge token and returns the next challenge response.
/// </summary>
/// <remarks>
/// Parses the server's challenge token and returns the next challenge response.
/// </remarks>
/// <returns>The next challenge response.</returns>
/// <param name="token">The server's challenge token.</param>
/// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
/// <param name="length">The length of the server's challenge.</param>
/// <exception cref="System.InvalidOperationException">
/// The SASL mechanism is already authenticated.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// THe SASL mechanism does not support SASL-IR.
/// </exception>
/// <exception cref="SaslException">
/// An error has occurred while parsing the server's challenge token.
/// </exception>
protected override byte[] Challenge (byte[] token, int startIndex, int length)
{
if (IsAuthenticated)
throw new InvalidOperationException ();
if (token == null)
throw new NotSupportedException ("DIGEST-MD5 does not support SASL-IR.");
var cred = Credentials.GetCredential (Uri, MechanismName);
switch (state) {
case LoginState.Auth:
if (token.Length > 2048)
throw new SaslException (MechanismName, SaslErrorCode.ChallengeTooLong, "Server challenge too long.");
challenge = DigestChallenge.Parse (Encoding.UTF8.GetString (token, startIndex, length));
if (string.IsNullOrEmpty (cnonce)) {
var entropy = new byte[15];
using (var rng = RandomNumberGenerator.Create ())
rng.GetBytes (entropy);
cnonce = Convert.ToBase64String (entropy);
}
response = new DigestResponse (challenge, Uri.Scheme, Uri.DnsSafeHost, cred.UserName, cred.Password, cnonce);
state = LoginState.Final;
return response.Encode ();
case LoginState.Final:
if (token.Length == 0)
throw new SaslException (MechanismName, SaslErrorCode.MissingChallenge, "Server response did not contain any authentication data.");
var text = Encoding.UTF8.GetString (token, startIndex, length);
string key, value;
int index = 0;
if (!DigestChallenge.TryParseKeyValuePair (text, ref index, out key, out value))
throw new SaslException (MechanismName, SaslErrorCode.IncompleteChallenge, "Server response contained incomplete authentication data.");
var expected = response.ComputeHash (cred.Password, false);
if (value != expected)
throw new SaslException (MechanismName, SaslErrorCode.IncorrectHash, "Server response did not contain the expected hash.");
IsAuthenticated = true;
return new byte[0];
default:
throw new IndexOutOfRangeException ("state");
}
}
/// <summary>
/// Resets the state of the SASL mechanism.
/// </summary>
/// <remarks>
/// Resets the state of the SASL mechanism.
/// </remarks>
public override void Reset ()
{
state = LoginState.Auth;
challenge = null;
response = null;
cnonce = null;
base.Reset ();
}
}
class DigestChallenge
{
public string[] Realms { get; private set; }
public string Nonce { get; private set; }
public HashSet<string> Qop { get; private set; }
public bool Stale { get; private set; }
public int MaxBuf { get; private set; }
public string Charset { get; private set; }
public string Algorithm { get; private set; }
public HashSet<string> Ciphers { get; private set; }
DigestChallenge ()
{
Ciphers = new HashSet<string> ();
Qop = new HashSet<string> ();
}
static bool SkipWhiteSpace (string text, ref int index)
{
int startIndex = index;
while (index < text.Length && char.IsWhiteSpace (text[index]))
index++;
return index > startIndex;
}
static bool TryParseKey (string text, ref int index, out string key)
{
int startIndex = index;
key = null;
while (index < text.Length && !char.IsWhiteSpace (text[index]) && text[index] != '=' && text[index] != ',')
index++;
if (index == startIndex)
return false;
key = text.Substring (startIndex, index - startIndex);
return true;
}
static bool TryParseQuoted (string text, ref int index, out string value)
{
var builder = new StringBuilder ();
bool escaped = false;
value = null;
// skip over leading '"'
index++;
while (index < text.Length) {
if (text[index] == '\\') {
if (escaped)
builder.Append (text[index]);
escaped = !escaped;
} else if (!escaped) {
if (text[index] == '"')
break;
builder.Append (text[index]);
} else {
escaped = false;
}
index++;
}
if (index >= text.Length || text[index] != '"')
return false;
index++;
value = builder.ToString ();
return true;
}
static bool TryParseValue (string text, ref int index, out string value)
{
if (text[index] == '"')
return TryParseQuoted (text, ref index, out value);
int startIndex = index;
value = null;
while (index < text.Length && !char.IsWhiteSpace (text[index]) && text[index] != ',')
index++;
if (index == startIndex)
return false;
value = text.Substring (startIndex, index - startIndex);
return true;
}
public static bool TryParseKeyValuePair (string text, ref int index, out string key, out string value)
{
value = null;
key = null;
SkipWhiteSpace (text, ref index);
if (!TryParseKey (text, ref index, out key))
return false;
SkipWhiteSpace (text, ref index);
if (index >= text.Length || text[index] != '=')
return false;
// skip over '='
index++;
SkipWhiteSpace (text, ref index);
return TryParseValue (text, ref index, out value);
}
public static DigestChallenge Parse (string token)
{
var challenge = new DigestChallenge ();
int index = 0;
while (index < token.Length) {
string key, value;
if (!TryParseKeyValuePair (token, ref index, out key, out value))
throw new SaslException ("DIGEST-MD5", SaslErrorCode.InvalidChallenge, string.Format ("Invalid SASL challenge from the server: {0}", token));
switch (key.ToLowerInvariant ()) {
case "realm":
challenge.Realms = value.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
break;
case "nonce":
challenge.Nonce = value;
break;
case "qop":
foreach (var qop in value.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
challenge.Qop.Add (qop.Trim ());
break;
case "stale":
challenge.Stale = value.ToLowerInvariant () == "true";
break;
case "maxbuf":
challenge.MaxBuf = int.Parse (value);
break;
case "charset":
challenge.Charset = value;
break;
case "algorithm":
challenge.Algorithm = value;
break;
case "cipher":
foreach (var cipher in value.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
challenge.Ciphers.Add (cipher.Trim ());
break;
}
SkipWhiteSpace (token, ref index);
if (index < token.Length && token[index] == ',')
index++;
}
return challenge;
}
}
class DigestResponse
{
public string UserName { get; private set; }
public string Realm { get; private set; }
public string Nonce { get; private set; }
public string CNonce { get; private set; }
public int Nc { get; private set; }
public string Qop { get; private set; }
public string DigestUri { get; private set; }
public string Response { get; private set; }
public int MaxBuf { get; private set; }
public string Charset { get; private set; }
public string Algorithm { get; private set; }
public string Cipher { get; private set; }
public string AuthZid { get; private set; }
public DigestResponse (DigestChallenge challenge, string protocol, string hostName, string userName, string password, string cnonce)
{
UserName = userName;
if (challenge.Realms != null && challenge.Realms.Length > 0)
Realm = challenge.Realms[0];
else
Realm = string.Empty;
Nonce = challenge.Nonce;
CNonce = cnonce;
Nc = 1;
// FIXME: make sure this is supported
Qop = "auth";
DigestUri = string.Format ("{0}/{1}", protocol, hostName);
if (!string.IsNullOrEmpty (challenge.Charset))
Charset = challenge.Charset;
Algorithm = challenge.Algorithm;
AuthZid = null;
Cipher = null;
Response = ComputeHash (password, true);
}
static string HexEncode (byte[] digest)
{
var hex = new StringBuilder ();
for (int i = 0; i < digest.Length; i++)
hex.Append (digest[i].ToString ("x2"));
return hex.ToString ();
}
public string ComputeHash (string password, bool client)
{
string text, a1, a2;
byte[] buf, digest;
// compute A1
text = string.Format ("{0}:{1}:{2}", UserName, Realm, password);
buf = Encoding.UTF8.GetBytes (text);
using (var md5 = new MD5 ())
digest = md5.ComputeHash (buf);
using (var md5 = new MD5 ()) {
md5.TransformBlock (digest, 0, digest.Length, null, 0);
text = string.Format (":{0}:{1}", Nonce, CNonce);
if (!string.IsNullOrEmpty (AuthZid))
text += ":" + AuthZid;
buf = Encoding.ASCII.GetBytes (text);
md5.TransformFinalBlock (buf, 0, buf.Length);
a1 = HexEncode (md5.Hash);
}
// compute A2
text = client ? "AUTHENTICATE:" : ":";
text += DigestUri;
if (Qop == "auth-int" || Qop == "auth-conf")
text += ":00000000000000000000000000000000";
buf = Encoding.ASCII.GetBytes (text);
using (var md5 = new MD5 ())
digest = md5.ComputeHash (buf);
a2 = HexEncode (digest);
// compute KD
text = string.Format ("{0}:{1}:{2:x8}:{3}:{4}:{5}", a1, Nonce, Nc, CNonce, Qop, a2);
buf = Encoding.ASCII.GetBytes (text);
using (var md5 = new MD5 ())
digest = md5.ComputeHash (buf);
return HexEncode (digest);
}
static string Quote (string text)
{
var quoted = new StringBuilder ();
quoted.Append ("\"");
for (int i = 0; i < text.Length; i++) {
if (text[i] == '\\' || text[i] == '"')
quoted.Append ('\\');
quoted.Append (text[i]);
}
quoted.Append ("\"");
return quoted.ToString ();
}
public byte[] Encode ()
{
Encoding encoding;
if (!string.IsNullOrEmpty (Charset))
encoding = Encoding.GetEncoding (Charset);
else
encoding = Encoding.UTF8;
var builder = new StringBuilder ();
builder.AppendFormat ("username={0}", Quote (UserName));
builder.AppendFormat (",realm=\"{0}\"", Realm);
builder.AppendFormat (",nonce=\"{0}\"", Nonce);
builder.AppendFormat (",cnonce=\"{0}\"", CNonce);
builder.AppendFormat (",nc={0:x8}", Nc);
builder.AppendFormat (",qop=\"{0}\"", Qop);
builder.AppendFormat (",digest-uri=\"{0}\"", DigestUri);
builder.AppendFormat (",response={0}", Response);
if (MaxBuf > 0)
builder.AppendFormat (",maxbuf={0}", MaxBuf);
if (!string.IsNullOrEmpty (Charset))
builder.AppendFormat (",charset={0}", Charset);
if (!string.IsNullOrEmpty (Algorithm))
builder.AppendFormat (",algorithm={0}", Algorithm);
if (!string.IsNullOrEmpty (Cipher))
builder.AppendFormat (",cipher=\"{0}\"", Cipher);
if (!string.IsNullOrEmpty (AuthZid))
builder.AppendFormat (",authzid=\"{0}\"", AuthZid);
return encoding.GetBytes (builder.ToString ());
}
}
}
| |
using System;
using System.Collections.Generic;
using Moq;
using Newtonsoft.Json;
using RestSharp;
using Xunit;
namespace Recurly.Tests
{
public class PagerTest
{
public class MyResource : Recurly.Resource
{
[JsonProperty("my_string")]
public string MyString { get; set; }
}
[Fact]
public void EmptyEnumerableTest()
{
var client = MockClient.Build(PagerEmptyResponse());
var pager = Pager<MyResource>.Build("/resources", new Dictionary<string, object> { }, null, client);
var i = 0;
foreach (MyResource r in pager)
{
Assert.True(false, "Should not be iterating anything if response is empty");
}
// There should be 0 resources
Assert.Equal(0, i);
}
[Fact]
public void EnumerableTest()
{
var queryParams = new Dictionary<string, object> {
{ "limit", "200" },
};
var client = GetPagerSuccessClient(queryParams);
var pager = Pager<MyResource>.Build("/resources", queryParams, null, client);
var i = 0;
foreach (MyResource r in pager)
{
if (i < 3)
{
Assert.Equal("A page 1 String", r.MyString);
}
else
{
Assert.Equal("A page 2 String", r.MyString);
}
i++;
}
// There should be 5 resources since
// there is a second page
Assert.Equal(5, i);
// We don't allow resetting pager states right now
Assert.Throws<NotImplementedException>(() =>
{
pager.Reset();
});
// should do nothing
pager.Dispose();
}
[Fact]
public void EnumerablePagesTest()
{
var queryParams = new Dictionary<string, object> {
{ "limit", "200" },
};
var client = GetPagerSuccessClient(queryParams);
var pager = Pager<MyResource>.Build("/resources", queryParams, null, client);
var total = 0;
var page = 0;
while (pager.HasMore)
{
pager.FetchNextPage();
var count = 0;
page++;
foreach (MyResource r in pager.Data)
{
count++;
total++;
}
if (page == 1)
{
Assert.Equal(3, count);
}
else if (page == 2)
{
Assert.Equal(2, count);
}
else
{
Assert.True(false, $"Should not have reached this page: {page}");
}
}
// There should be 5 resources since
// there is a second page
Assert.Equal(5, total);
}
[Fact]
public void PagerFirstTest()
{
var paramsMatcher = MockClient.QueryParameterMatcher(new Dictionary<string, object> {
{ "limit", "1" },
{ "a", "1" },
});
var client = MockClient.Build(paramsMatcher, PagerFirstResponse());
var queryParams = new Dictionary<string, object> {
{ "limit", "200" },
{ "a", "1" },
};
var pager = Pager<MyResource>.Build("/resources", queryParams, null, client);
var resource = pager.First();
Assert.Equal("First Resource", resource.MyString);
}
[Fact]
public void PagerCountTest()
{
var queryParams = new Dictionary<string, object> {
{ "limit", 200 },
{ "a", 1 },
};
var client = MockClient.Build(PagerCountResponse());
var pager = Pager<MyResource>.Build("/resources", queryParams, null, client);
var count = pager.Count();
Assert.Equal(42, count);
}
private Mock<IRestResponse<Pager<MyResource>>> PagerSuccessPage1Response()
{
// When there are no results, the server returns
// an empty array with HasMore == false
var page = new Pager<MyResource>()
{
HasMore = true,
Next = "/next-page",
Data = new List<MyResource>()
{
new MyResource() { MyString = "A page 1 String" },
new MyResource() { MyString = "A page 1 String" },
new MyResource() { MyString = "A page 1 String" },
}
};
var response = new Mock<IRestResponse<Pager<MyResource>>>();
response.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.OK);
response.Setup(_ => _.Headers).Returns(new List<Parameter> { });
response.Setup(_ => _.Data).Returns(page);
return response;
}
private Mock<IRestResponse<Pager<MyResource>>> PagerSuccessPage2Response()
{
// When there are no results, the server returns
// an empty array with HasMore == false
var page = new Pager<MyResource>()
{
HasMore = false,
Data = new List<MyResource>()
{
new MyResource() { MyString = "A page 2 String" },
new MyResource() { MyString = "A page 2 String" },
}
};
var response = new Mock<IRestResponse<Pager<MyResource>>>();
response.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.OK);
response.Setup(_ => _.Headers).Returns(new List<Parameter> { });
response.Setup(_ => _.Data).Returns(page);
return response;
}
private MockClient GetPagerSuccessClient(Dictionary<string, object> expectedParams)
{
var paramsMatcher = MockClient.QueryParameterMatcher(expectedParams);
var page1Response = PagerSuccessPage1Response();
Func<IRestRequest, bool> page1Matcher = delegate (IRestRequest request)
{
if (request.Resource == "/resources")
{
return paramsMatcher(request);
}
return false;
};
var page2Response = PagerSuccessPage2Response();
Func<IRestRequest, bool> page2Matcher = delegate (IRestRequest request)
{
if (request.Resource == "/next-page")
{
return true;
}
return false;
};
var mockCollection = new Dictionary<Func<IRestRequest, bool>, Mock<IRestResponse<Pager<MyResource>>>> {
{ page1Matcher, page1Response },
{ page2Matcher, page2Response },
};
return MockClient.Build(mockCollection);
}
private Mock<IRestResponse<Pager<MyResource>>> PagerEmptyResponse()
{
// When there are no results, the server returns
// an empty array with HasMore == false
var page = new Pager<MyResource>()
{
HasMore = false,
Data = new List<MyResource>() { }
};
var response = new Mock<IRestResponse<Pager<MyResource>>>();
response.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.OK);
response.Setup(_ => _.Headers).Returns(new List<Parameter> { });
response.Setup(_ => _.Data).Returns(page);
return response;
}
private Mock<IRestResponse<Pager<MyResource>>> PagerFirstResponse()
{
// When there are no results, the server returns
// an empty array with HasMore == false
var page = new Pager<MyResource>()
{
HasMore = true,
Data = new List<MyResource>()
{
new MyResource() { MyString = "First Resource" }
}
};
var response = new Mock<IRestResponse<Pager<MyResource>>>();
response.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.OK);
response.Setup(_ => _.Headers).Returns(new List<Parameter> { });
response.Setup(_ => _.Data).Returns(page);
return response;
}
private Mock<IRestResponse<EmptyResource>> PagerCountResponse()
{
var response = new Mock<IRestResponse<EmptyResource>>();
response.Setup(_ => _.StatusCode).Returns(System.Net.HttpStatusCode.OK);
response.Setup(_ => _.Headers).Returns(new List<Parameter> {
new RestSharp.Parameter("Recurly-Total-Records", "42", ParameterType.HttpHeader),
});
return response;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ChangeSignature
{
internal abstract class AbstractChangeSignatureService : ILanguageService
{
protected SyntaxAnnotation changeSignatureFormattingAnnotation = new SyntaxAnnotation("ChangeSignatureFormatting");
/// <summary>
/// Determines the symbol on which we are invoking ReorderParameters
/// </summary>
public abstract ISymbol GetInvocationSymbol(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken);
/// <summary>
/// Given a SyntaxNode for which we want to reorder parameters/arguments, find the
/// SyntaxNode of a kind where we know how to reorder parameters/arguments.
/// </summary>
public abstract SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node);
public abstract Task<IEnumerable<ISymbol>> DetermineCascadedSymbolsFromDelegateInvoke(IMethodSymbol symbol, Document document, CancellationToken cancellationToken);
public abstract SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
public async Task<IEnumerable<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var context = await GetContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false);
return context.CanChangeSignature
? SpecializedCollections.SingletonEnumerable(new ChangeSignatureCodeAction(this, context))
: SpecializedCollections.EmptyEnumerable<ChangeSignatureCodeAction>();
}
internal ChangeSignatureResult ChangeSignature(Document document, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken)
{
var context = GetContextAsync(document, position, restrictToDeclarations: false, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
if (context.CanChangeSignature)
{
return ChangeSignatureWithContext(context, cancellationToken);
}
else
{
switch (context.CannotChangeSignatureReason)
{
case CannotChangeSignatureReason.DefinedInMetadata:
errorHandler(FeaturesResources.TheMemberIsDefinedInMetadata, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.IncorrectKind:
errorHandler(FeaturesResources.YouCanOnlyChangeTheSignatureOfAConstructorIndexerMethodOrDelegate, NotificationSeverity.Error);
break;
case CannotChangeSignatureReason.InsufficientParameters:
errorHandler(FeaturesResources.ThisSignatureDoesNotContainParametersThatCanBeChanged, NotificationSeverity.Error);
break;
}
return new ChangeSignatureResult(succeeded: false);
}
}
private async Task<ChangeSignatureAnalyzedContext> GetContextAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var symbol = GetInvocationSymbol(document, position, restrictToDeclarations, cancellationToken);
// Cross-lang symbols will show as metadata, so map it to source if possible.
symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol;
if (symbol == null)
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
if (symbol is IMethodSymbol)
{
var method = symbol as IMethodSymbol;
var containingType = method.ContainingType;
if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
containingType != null &&
containingType.IsDelegateType() &&
containingType.DelegateInvokeMethod != null)
{
symbol = containingType.DelegateInvokeMethod;
}
}
if (symbol is IEventSymbol)
{
symbol = (symbol as IEventSymbol).Type;
}
if (symbol is INamedTypeSymbol)
{
var typeSymbol = symbol as INamedTypeSymbol;
if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null)
{
symbol = typeSymbol.DelegateInvokeMethod;
}
}
if (symbol.Locations.Any(loc => loc.IsInMetadata))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.DefinedInMetadata);
}
if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType))
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.IncorrectKind);
}
var parameterConfiguration = ParameterConfiguration.Create(symbol.GetParameters().ToList(), symbol is IMethodSymbol && (symbol as IMethodSymbol).IsExtensionMethod);
if (!parameterConfiguration.IsChangeable())
{
return new ChangeSignatureAnalyzedContext(CannotChangeSignatureReason.InsufficientParameters);
}
return new ChangeSignatureAnalyzedContext(document.Project.Solution, symbol, parameterConfiguration);
}
private ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var options = GetChangeSignatureOptions(context, CancellationToken.None);
if (options.IsCancelled)
{
return new ChangeSignatureResult(succeeded: false);
}
return ChangeSignatureWithContext(context, options, cancellationToken);
}
internal ChangeSignatureResult ChangeSignatureWithContext(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken)
{
Solution updatedSolution;
var succeeded = TryCreateUpdatedSolution(context, options, cancellationToken, out updatedSolution);
return new ChangeSignatureResult(succeeded, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges);
}
internal ChangeSignatureOptionsResult GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context, CancellationToken cancellationToken)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
var changeSignatureOptionsService = context.Solution.Workspace.Services.GetService<IChangeSignatureOptionsService>();
var isExtensionMethod = context.Symbol is IMethodSymbol && (context.Symbol as IMethodSymbol).IsExtensionMethod;
return changeSignatureOptionsService.GetChangeSignatureOptions(context.Symbol, context.ParameterConfiguration, notificationService);
}
private static Task<IEnumerable<ReferencedSymbol>> FindChangeSignatureReferencesAsync(
ISymbol symbol,
Solution solution,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken))
{
IImmutableSet<Document> documents = null;
var engine = new FindReferencesSearchEngine(
solution,
documents,
ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod),
FindReferencesProgress.Instance,
cancellationToken);
return engine.FindReferencesAsync(symbol);
}
}
private bool TryCreateUpdatedSolution(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken, out Solution updatedSolution)
{
updatedSolution = context.Solution;
var declaredSymbol = context.Symbol;
var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>();
var definitionToUse = new Dictionary<SyntaxNode, ISymbol>();
bool hasLocationsInMetadata = false;
var symbols = FindChangeSignatureReferencesAsync(declaredSymbol, context.Solution, cancellationToken).WaitAndGetResult(cancellationToken);
foreach (var symbol in symbols)
{
if (symbol.Definition.Kind == SymbolKind.Method &&
((symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertyGet || (symbol.Definition as IMethodSymbol).MethodKind == MethodKind.PropertySet))
{
continue;
}
if (symbol.Definition.Kind == SymbolKind.NamedType)
{
continue;
}
if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata))
{
hasLocationsInMetadata = true;
continue;
}
var symbolWithSyntacticParameters = symbol.Definition;
var symbolWithSemanticParameters = symbol.Definition;
var includeDefinitionLocations = true;
if (symbol.Definition.Kind == SymbolKind.Field)
{
includeDefinitionLocations = false;
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Event)
{
var eventSymbol = symbolWithSyntacticParameters as IEventSymbol;
var type = eventSymbol.Type as INamedTypeSymbol;
if (type != null && type.DelegateInvokeMethod != null)
{
symbolWithSemanticParameters = type.DelegateInvokeMethod;
}
else
{
continue;
}
}
if (symbolWithSyntacticParameters.Kind == SymbolKind.Method)
{
var methodSymbol = symbolWithSyntacticParameters as IMethodSymbol;
if (methodSymbol.MethodKind == MethodKind.DelegateInvoke)
{
symbolWithSyntacticParameters = methodSymbol.ContainingType;
}
if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName &&
methodSymbol.ContainingType != null &&
methodSymbol.ContainingType.IsDelegateType())
{
includeDefinitionLocations = false;
}
}
// Find and annotate all the relevant definitions
if (includeDefinitionLocations)
{
foreach (var def in symbolWithSyntacticParameters.Locations)
{
DocumentId documentId;
SyntaxNode nodeToUpdate;
if (!TryGetNodeWithEditableSignatureOrAttributes(def, updatedSolution, out nodeToUpdate, out documentId))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId))
{
nodesToUpdate.Add(documentId, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters);
}
}
// Find and annotate all the relevant references
foreach (var location in symbol.Locations)
{
if (location.Location.IsInMetadata)
{
hasLocationsInMetadata = true;
continue;
}
DocumentId documentId2;
SyntaxNode nodeToUpdate2;
if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, updatedSolution, out nodeToUpdate2, out documentId2))
{
continue;
}
if (!nodesToUpdate.ContainsKey(documentId2))
{
nodesToUpdate.Add(documentId2, new List<SyntaxNode>());
}
AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters);
}
}
if (hasLocationsInMetadata)
{
var notificationService = context.Solution.Workspace.Services.GetService<INotificationService>();
if (!notificationService.ConfirmMessageBox(FeaturesResources.ThisSymbolHasRelatedDefinitionsOrReferencesInMetadata, severity: NotificationSeverity.Warning))
{
return false;
}
}
// Construct all the relevant syntax trees from the base solution
var updatedRoots = new Dictionary<DocumentId, SyntaxNode>();
foreach (var docId in nodesToUpdate.Keys)
{
var doc = updatedSolution.GetDocument(docId);
var updater = doc.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
var root = doc.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var nodes = nodesToUpdate[docId];
var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) =>
{
return updater.ChangeSignature(doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, CreateCompensatingSignatureChange(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken);
});
var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation);
var formattedRoot = Formatter.FormatAsync(
newRoot,
changeSignatureFormattingAnnotation,
doc.Project.Solution.Workspace,
options: null,
rules: GetFormattingRules(doc),
cancellationToken: CancellationToken.None).WaitAndGetResult(CancellationToken.None);
updatedRoots[docId] = formattedRoot;
}
// Update the documents using the updated syntax trees
foreach (var docId in nodesToUpdate.Keys)
{
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(docId, updatedRoots[docId]);
}
return true;
}
private void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters)
{
nodesToUpdate[documentId].Add(nodeToUpdate);
ISymbol sym;
if (definitionToUse.TryGetValue(nodeToUpdate, out sym) && sym != symbolWithSemanticParameters)
{
Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters.");
}
definitionToUse[nodeToUpdate] = symbolWithSemanticParameters;
}
private bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId)
{
var tree = location.SourceTree;
documentId = solution.GetDocumentId(tree);
var document = solution.GetDocument(documentId);
var root = tree.GetRoot();
SyntaxNode node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);
var updater = document.Project.LanguageServices.GetService<AbstractChangeSignatureService>();
nodeToUpdate = updater.FindNodeToUpdate(document, node);
return nodeToUpdate != null;
}
protected static List<IUnifiedArgumentSyntax> PermuteArguments(
Document document,
ISymbol declarationSymbol,
List<IUnifiedArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
// 1. Determine which parameters are permutable
var declarationParameters = declarationSymbol.GetParameters().ToList();
var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod);
var argumentsToPermute = arguments.Take(declarationParametersToPermute.Count).ToList();
// 2. Create an argument to parameter map, and a parameter to index map for the sort.
var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>();
var parameterToIndexMap = new Dictionary<IParameterSymbol, int>();
for (int i = 0; i < declarationParametersToPermute.Count; i++)
{
var decl = declarationParametersToPermute[i];
var arg = argumentsToPermute[i];
argumentToParameterMap[arg] = decl;
var originalIndex = declarationParameters.IndexOf(decl);
var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex);
// If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke).
parameterToIndexMap[decl] = updatedIndex.HasValue ? updatedIndex.Value : -1;
}
// 3. Sort the arguments that need to be reordered
argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); });
// 4. Add names to arguments where necessary.
var newArguments = new List<IUnifiedArgumentSyntax>();
int expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0);
bool seenNamedArgument = false;
foreach (var argument in argumentsToPermute)
{
var param = argumentToParameterMap[argument];
var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param));
if (!actualIndex.HasValue)
{
continue;
}
if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed)
{
newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation));
seenNamedArgument = true;
}
else
{
newArguments.Add(argument);
}
seenNamedArgument |= argument.IsNamed;
expectedIndex++;
}
// 5. Add the remaining arguments. These will already have names or be params arguments, but may have been removed.
bool removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null;
for (int i = declarationParametersToPermute.Count; i < arguments.Count; i++)
{
if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Count)
{
break;
}
if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName()))
{
newArguments.Add(arguments[i]);
}
}
return newArguments;
}
private static SignatureChange CreateCompensatingSignatureChange(ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (declarationSymbol.GetParameters().Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Count)
{
var origStuff = updatedSignature.OriginalConfiguration.ToListOfParameters();
var newStuff = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var realStuff = declarationSymbol.GetParameters();
var bonusParameters = realStuff.Skip(origStuff.Count);
origStuff.AddRange(bonusParameters);
newStuff.AddRange(bonusParameters);
var newOrigParams = ParameterConfiguration.Create(origStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
var newUpdatedParams = ParameterConfiguration.Create(newStuff, updatedSignature.OriginalConfiguration.ThisParameter != null);
updatedSignature = new SignatureChange(newOrigParams, newUpdatedParams);
}
return updatedSignature;
}
private static List<IParameterSymbol> GetParametersToPermute(
List<IUnifiedArgumentSyntax> arguments,
List<IParameterSymbol> originalParameters,
bool isReducedExtensionMethod)
{
int position = -1 + (isReducedExtensionMethod ? 1 : 0);
var parametersToPermute = new List<IParameterSymbol>();
foreach (var argument in arguments)
{
if (argument.IsNamed)
{
var name = argument.GetName();
// TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>);
var match = originalParameters.FirstOrDefault(p => p.Name == name);
if (match == null || originalParameters.IndexOf(match) <= position)
{
break;
}
else
{
position = originalParameters.IndexOf(match);
parametersToPermute.Add(match);
}
}
else
{
position++;
if (position >= originalParameters.Count)
{
break;
}
parametersToPermute.Add(originalParameters[position]);
}
}
return parametersToPermute;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Text.Analyzers.IdentifiersShouldBeSpelledCorrectlyAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Text.Analyzers.UnitTests
{
public class IdentifiersShouldBeSpelledCorrectlyTests
{
public enum DictionaryType
{
Xml,
Dic,
}
public static IEnumerable<object[]> MisspelledMembers
=> new[]
{
new object[] { CreateTypeWithConstructor("<?>Clazz", isStatic: false), "Clazz", "Clazz.Clazz()" },
new object[] { CreateTypeWithConstructor("<?>Clazz", isStatic: true), "Clazz", "Clazz.Clazz()" },
new object[] { CreateTypeWithField("Program", "<?>_fild"), "fild", "Program._fild" },
new object[] { CreateTypeWithEvent("Program", "<?>Evt"), "Evt", "Program.Evt" },
new object[] { CreateTypeWithProperty("Program", "<?>Naem"), "Naem", "Program.Naem" },
new object[] { CreateTypeWithMethod("Program", "<?>SomeMathod"), "Mathod", "Program.SomeMathod()" },
};
public static IEnumerable<object[]> UnmeaningfulMembers
=> new[]
{
new object[] { CreateTypeWithConstructor("<?>A", isStatic: false), "A" },
new object[] { CreateTypeWithConstructor("<?>B", isStatic: false), "B" },
new object[] { CreateTypeWithField("Program", "<?>_c"), "c" },
new object[] { CreateTypeWithEvent("Program", "<?>D"), "D" },
new object[] { CreateTypeWithProperty("Program", "<?>E"), "E" },
new object[] { CreateTypeWithMethod("Program", "<?>F"), "F" },
};
public static IEnumerable<object[]> MisspelledMemberParameters
=> new[]
{
new object[] { CreateTypeWithConstructor("Program", false, "int <?>yourNaem"), "Naem", "yourNaem", "Program.Program(int)" },
new object[] { CreateTypeWithMethod("Program", "Method", "int <?>yourNaem"), "Naem", "yourNaem", "Program.Method(int)" },
new object[] { CreateTypeWithIndexer("Program", "int <?>yourNaem"), "Naem", "yourNaem", "Program.this[int]" },
};
[Theory]
[InlineData("namespace Bar { }")]
[InlineData("class Program { }")]
[InlineData("class Program { void Member() { } }")]
[InlineData("class Program { int _variable = 1; }")]
[InlineData("class Program { void Member(string name) { } }")]
[InlineData("class Program { delegate int GetNumber(string name); }")]
[InlineData("class Program<TResource> { }")]
public async Task NoMisspellings_Verify_NoDiagnostics(string source)
{
await VerifyCSharpAsync(source);
}
[Fact]
public async Task MisspellingAllowedByGlobalXmlDictionary_Verify_NoDiagnostics()
{
var source = "class Clazz { }";
var dictionary = CreateXmlDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingAllowedByGlobalDicDictionary_Verify_NoDiagnostics()
{
var source = "class Clazz { }";
var dictionary = CreateDicDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingsAllowedByMultipleGlobalDictionaries_Verify_NoDiagnostics()
{
var source = @"class Clazz { const string Naem = ""foo""; }";
var xmlDictionary = CreateXmlDictionary(new[] { "clazz" });
var dicDictionary = CreateDicDictionary(new[] { "naem" });
await VerifyCSharpAsync(source, new[] { xmlDictionary, dicDictionary });
}
[Fact]
public async Task CorrectWordDisallowedByGlobalXmlDictionary_Verify_EmitsDiagnostic()
{
var source = "class Program { }";
var dictionary = CreateXmlDictionary(null, new[] { "program" });
await VerifyCSharpAsync(
source,
dictionary,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule)
.WithLocation(1, 7)
.WithArguments("Program", "Program"));
}
// [Fact]
// public void MisspellingAllowedByProjectDictionary_Verify_NoDiagnostics()
// {
// var testFile = new TestFile("AssemblyA", "class Clazz {}");
// var dictionary = CreateDicDictionary(new[] { "clazz" });
// VerifyDiagnostics(testFile, null, GetProjectAdditionalFiles("AssemblyA", dictionary));
// }
// [Fact]
// public void MisspellingAllowedByDifferentProjectDictionary_Verify_EmitsDiagnostic()
// {
// var testFile = new AutoTestFile("AssemblyA", "class <?>Clazz {}", GetTypeRule("Clazz", "Clazz"));
// var dictionary = CreateDicDictionary(new[] { "clazz" });
// VerifyDiagnostics(testFile, null, GetProjectAdditionalFiles("AssemblyB", dictionary));
// }
// [Fact(Skip = "Assembly names are disabled for now")]
// public void AssemblyMisspelled_Verify_EmitsDiagnostic()
// {
// var testFile = new TestFile("MyAssambly", "class Program { }");
// VerifyDiagnostics(testFile, GetResult(SpellingAnalyzer.AssemblyRule, "Assambly", "MyAssambly"));
// }
// [Fact(Skip = "Unmeaningful rules disabled for now")]
// public void AssemblyUnmeaningful_Verify_EmitsDiagnostic()
// {
// var testFile = new TestFile("A", "class Program { }");
// VerifyDiagnostics(testFile, GetResult(SpellingAnalyzer.AssemblyMoreMeaningfulNameRule, "A"));
// }
// [Fact]
// public void NamespaceMisspelled_Verify_EmitsDiagnostic()
// {
// var testFile = new AutoTestFile("namespace Tests.<?>MyNarmspace { }", GetNamespaceRule("Narmspace", "Tests.MyNarmspace"));
// VerifyDiagnostics(testFile);
// }
// [Fact(Skip = "Unmeaningful rules disabled for now")]
// public void NamespaceUnmeaningful_Verify_EmitsDiagnostic()
// {
// var testFile = new AutoTestFile("namespace Tests.<|A|> { }", new Rule(SpellingAnalyzer.NamespaceMoreMeaningfulNameRule));
// VerifyDiagnostics(testFile);
// }
// [Theory]
// [InlineData("namespace MyNamespace { class <?>MyClazz { } }", "Clazz", "MyNamespace.MyClazz")]
// [InlineData("namespace MyNamespace { struct <?>MyStroct { } }", "Stroct", "MyNamespace.MyStroct")]
// [InlineData("namespace MyNamespace { enum <?>MyEnim { } }", "Enim", "MyNamespace.MyEnim")]
// [InlineData("namespace MyNamespace { interface <?>IMyFase { } }", "Fase", "MyNamespace.IMyFase")]
// [InlineData("namespace MyNamespace { delegate int <?>MyDelegete(); }", "Delegete", "MyNamespace.MyDelegete")]
// public void TypeMisspelled_Verify_EmitsDiagnostic(string source, string misspelling, string typeName)
// {
// var testFile = new AutoTestFile(source, GetTypeRule(misspelling, typeName));
// VerifyDiagnostics(testFile);
// }
// [Theory(Skip = "Unmeaningful rules disabled for now")]
// [InlineData("class <?>A { }", "A")]
// [InlineData("struct <?>B { }", "B")]
// [InlineData("enum <?>C { }", "C")]
// [InlineData("interface <?>ID { }", "D")]
// [InlineData("delegate int <?>E();", "E")]
// public void TypeUnmeaningful_Verify_EmitsDiagnostic(string source, string typeName)
// {
// var testFile = new AutoTestFile(source, GetTypeUnmeaningfulRule(typeName));
// VerifyDiagnostics(testFile);
// }
// [Theory]
// [MemberData(nameof(MisspelledMembers))]
// public void MemberMisspelled_Verify_EmitsDiagnostic(string source, string misspelling, string memberName)
// {
// var testFile = new AutoTestFile(source, GetMemberRule(misspelling, memberName));
// VerifyDiagnostics(testFile);
// }
// [Fact]
// public void MemberOverrideMisspelled_Verify_EmitsDiagnosticOnlyAtDefinition()
// {
// var source = @"
// abstract class Parent
// {
// protected abstract string <?>Naem { get; }
// public abstract int <?>Mathod();
// }
// class Child : Parent
// {
// protected override string Naem => ""child"";
// public override int Mathod() => 0;
// }
// class Grandchild : Child
// {
// protected override string Naem => ""grandchild"";
// public override int Mathod() => 1;
// }";
// var testFile = new AutoTestFile(
// source,
// GetMemberRule("Naem", "Parent.Naem"),
// GetMemberRule("Mathod", "Parent.Mathod()"));
// VerifyDiagnostics(testFile);
// }
// [Theory(Skip = "Unmeaningful rules disabled for now")]
// [MemberData(nameof(UnmeaningfulMembers))]
// public void MemberUnmeaningful_Verify_EmitsDiagnostic(string source, string memberName)
// {
// var testFile = new AutoTestFile(source, GetMemberUnmeaningfulRule(memberName));
// VerifyDiagnostics(testFile);
// }
// [Fact]
// public void VariableMisspelled_Verify_EmitsDiagnostic()
// {
// var source = @"
// class Program
// {
// public Program()
// {
// var <?>myVoriable = 5;
// }
// }";
// var testFile = new AutoTestFile(source, GetVariableRule("Voriable", "myVoriable"));
// VerifyDiagnostics(testFile);
// }
// [Theory]
// [MemberData(nameof(MisspelledMemberParameters))]
// public void MemberParameterMisspelled_Verify_EmitsDiagnostic(string source, string misspelling, string parameterName, string memberName)
// {
// var testFile = new AutoTestFile(source, GetMemberParameterRule(memberName, misspelling, parameterName));
// VerifyDiagnostics(testFile);
// }
// [Fact(Skip = "Unmeaningful rules disabled for now")]
// public void MemberParameterUnmeaningful_Verify_EmitsDiagnostic()
// {
// var source = @"
// class Program
// {
// public void Method(string <?>a)
// {
// }
// public string this[int <?>i] => null;
// }";
// var testFile = new AutoTestFile(
// source,
// GetMemberParameterUnmeaningfulRule("Program.Method(string)", "a"),
// GetMemberParameterUnmeaningfulRule("Program.this[int]", "i"));
// VerifyDiagnostics(testFile);
// }
// [Fact]
// public void DelegateParameterMisspelled_Verify_EmitsDiagnostic()
// {
// var testFile = new AutoTestFile(
// "delegate void MyDelegate(string <?>firstNaem);",
// GetDelegateParameterRule("MyDelegate", "Naem", "firstNaem"));
// VerifyDiagnostics(testFile);
// }
// [Fact(Skip = "Unmeaningful rules disabled for now")]
// public void DelegateParameterUnmeaningful_Verify_EmitsDiagnostic()
// {
// var testFile = new AutoTestFile(
// "delegate void MyDelegate(string <?>a);",
// GetDelegateParameterUnmeaningfulRule("MyDelegate", "a"));
// VerifyDiagnostics(testFile);
// }
// [Theory]
// [InlineData("class MyClass<TCorrect, <?>TWroong> { }", "MyClass<TCorrect, TWroong>", "Wroong", "TWroong")]
// [InlineData("struct MyStructure<<?>TWroong> { }", "MyStructure<TWroong>", "Wroong", "TWroong")]
// [InlineData("interface IInterface<<?>TWroong> { }", "IInterface<TWroong>", "Wroong", "TWroong")]
// [InlineData("delegate int MyDelegate<<?>TWroong>();", "MyDelegate<TWroong>", "Wroong", "TWroong")]
// public void TypeTypeParameterMisspelled_Verify_EmitsDiagnostic(string source, string typeName, string misspelling, string typeParameterName)
// {
// var testFile = new AutoTestFile(source, GetTypeTypeParameterRule(typeName, misspelling, typeParameterName));
// VerifyDiagnostics(testFile);
// }
// [Theory(Skip = "Unmeaningful rules disabled for now")]
// [InlineData("class MyClass<<?>A> { }", "MyClass<A>", "A")]
// [InlineData("struct MyStructure<<?>B> { }", "MyStructure<B>", "B")]
// [InlineData("interface IInterface<<?>C> { }", "IInterface<C>", "C")]
// [InlineData("delegate int MyDelegate<<?>D>();", "MyDelegate<D>", "D")]
// public void TypeTypeParameterUnmeaningful_Verify_EmitsDiagnostic(string source, string typeName, string typeParameterName)
// {
// var testFile = new AutoTestFile(source, GetTypeTypeParameterUnmeaningfulRule(typeName, typeParameterName));
// VerifyDiagnostics(testFile);
// }
// [Fact]
// public void MethodTypeParameterMisspelled_Verify_EmitsDiagnostic()
// {
// var source = @"
// class Program
// {
// void Method<<?>TTipe>(TTipe item)
// {
// }
// }";
// var testFile = new AutoTestFile(source, GetMethodTypeParameterRule("Program.Method<TTipe>(TTipe)", "Tipe", "TTipe"));
// VerifyDiagnostics(testFile);
// }
// [Fact(Skip = "Unmeaningful rules disabled for now")]
// public void MethodTypeParameterUnmeaningful_Verify_EmitsDiagnostic()
// {
// var source = @"
// class Program
// {
// void Method<<?>TA>(TA parameter)
// {
// }
// }";
// var testFile = new AutoTestFile(source, GetMethodTypeParameterUnmeaningfulRule("Program.Method<TA>(TA)", "TA"));
// VerifyDiagnostics(testFile);
// }
// [Fact]
// public void MisspellingContainsOnlyCapitalizedLetters_Verify_NoDiagnostics()
// {
// var testFile = new TestFile("class FCCA { }");
// VerifyDiagnostics(testFile);
// }
// [Theory]
// [InlineData("0x0")]
// [InlineData("0xDEADBEEF")]
// public void MisspellingStartsWithADigit_Verify_NoDiagnostics(string misspelling)
// {
// var testFile = new TestFile($"enum Name {{ My{misspelling} }}");
// VerifyDiagnostics(testFile);
// }
// [Fact]
// public void MalformedXmlDictionary_Verify_EmitsDiagnostic()
// {
// var contents = @"<?xml version=""1.0"" encoding=""utf-8""?>
// <Dictionary>
// <Words>
// <Recognized>
// <Word>okay</Word>
// <word>bad</Word> <!-- xml tags are case-sensitive -->
// </Recognized>
// </Words>
// </Dictionary>";
// var dictionary = new TestAdditionalDocument("CodeAnalysisDictionary.xml", contents);
// VerifyDiagnostics(
// new TestFile("class Program { }"),
// dictionary,
// GetFileParseResult(
// "CodeAnalysisDictionary.xml",
// "The 'word' start tag on line 6 position 14 does not match the end tag of 'Word'. Line 6, position 24."));
// }
private Task VerifyCSharpAsync(string source, params DiagnosticResult[] expected)
=> VerifyCSharpAsync(source, Array.Empty<AdditionalText>(), expected);
private Task VerifyCSharpAsync(string source, AdditionalText additionalText, params DiagnosticResult[] expected)
=> VerifyCSharpAsync(source, new[] { additionalText }, expected);
private async Task VerifyCSharpAsync(string source, AdditionalText[] additionalTexts, params DiagnosticResult[] expected)
{
var csharpTest = new VerifyCS.Test
{
TestState =
{
Sources = { source },
AdditionalFilesFactories = { () => additionalTexts.Select(x => (x.Path, x.GetText())) }
}
};
csharpTest.ExpectedDiagnostics.AddRange(expected);
await csharpTest.RunAsync();
}
private static AdditionalText CreateXmlDictionary(IEnumerable<string> recognizedWords, IEnumerable<string> unrecognizedWords = null) =>
CreateXmlDictionary("CodeAnalysisDictionary.xml", recognizedWords, unrecognizedWords);
private static AdditionalText CreateXmlDictionary(string filename, IEnumerable<string> recognizedWords, IEnumerable<string> unrecognizedWords = null)
{
var contents = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<Dictionary>
<Words>
<Recognized>{CreateXml(recognizedWords)}</Recognized>
<Unrecognized>{CreateXml(unrecognizedWords)}</Unrecognized>
</Words>
</Dictionary>";
return new TestAdditionalDocument(filename, contents);
static string CreateXml(IEnumerable<string> words) =>
string.Join(Environment.NewLine, words?.Select(x => $"<Word>{x}</Word>") ?? Enumerable.Empty<string>());
}
private static TestAdditionalDocument CreateDicDictionary(IEnumerable<string> recognizedWords)
{
var contents = string.Join(Environment.NewLine, recognizedWords);
return new TestAdditionalDocument("CustomDictionary.dic", contents);
}
private static string CreateTypeWithConstructor(string typeName, bool isStatic, string parameter = "")
{
return $@"
#pragma warning disable {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}
class {typeName.TrimStart(new[] { '<', '?', '>' })}
#pragma warning restore {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}
{{
{(isStatic ? "static " : string.Empty)}{typeName}({parameter}) {{ }}
}}";
}
private static string CreateTypeWithMethod(string typeName, string methodName, string parameter = "")
=> $"class {typeName} {{ void {methodName}({parameter}) {{ }} }}";
private static string CreateTypeWithIndexer(string typeName, string parameter)
=> $"class {typeName} {{ int this[{parameter}] => 0; }}";
private static string CreateTypeWithProperty(string typeName, string propertyName)
=> $"class {typeName} {{ string {propertyName} {{ get; }} }}";
private static string CreateTypeWithField(string typeName, string fieldName)
=> $"class {typeName} {{ private string {fieldName}; }}";
private static string CreateTypeWithEvent(string typeName, string eventName)
{
return $@"using System;
class {typeName} {{ event EventHandler<string> {eventName}; }}";
}
}
}
| |
using System.Collections.Generic;
namespace Irony.Parsing
{
//Scanner class. The Scanner's function is to transform a stream of characters into aggregates/words or lexemes,
// like identifier, number, literal, etc.
public class Scanner
{
public Scanner(Parser parser)
{
Parser = parser;
Data = parser.Language.ScannerData;
_grammar = parser.Language.Grammar;
//create token streams
var tokenStream = GetUnfilteredTokens();
//chain all token filters
Context.TokenFilters.Clear();
_grammar.CreateTokenFilters(Data.Language, Context.TokenFilters);
foreach (var filter in Context.TokenFilters)
{
tokenStream = filter.BeginFiltering(Context, tokenStream);
}
Context.FilteredTokens = tokenStream.GetEnumerator();
}
internal void Reset()
{
}
public Token GetToken()
{
//get new token from pipeline
if (!Context.FilteredTokens.MoveNext()) return null;
var token = Context.FilteredTokens.Current;
if (Context.Status == ParserStatus.Previewing)
Context.PreviewTokens.Push(token);
else
Context.CurrentParseTree.Tokens.Add(token);
return token;
}
//This is iterator method, so it returns immediately when called directly
// returns unfiltered, "raw" token stream
private IEnumerable<Token> GetUnfilteredTokens()
{
//We don't do "while(!_source.EOF())... because on EOF() we need to continue and produce EOF token
while (true)
{
Context.PreviousToken = Context.CurrentToken;
Context.CurrentToken = null;
NextToken();
Context.OnTokenCreated();
yield return Context.CurrentToken;
//Don't yield break, continue returning EOF
} //while
} // method
#region Error recovery
//Simply skip until whitespace or delimiter character
private bool Recover()
{
var src = Context.Source;
src.PreviewPosition++;
while (!Context.Source.EOF())
{
if (_grammar.IsWhitespaceOrDelimiter(src.PreviewChar))
{
src.Position = src.PreviewPosition;
return true;
}
src.PreviewPosition++;
}
return false;
}
#endregion
#region Properties and Fields: Data, _source
public readonly ScannerData Data;
public readonly Parser Parser;
private readonly Grammar _grammar;
//buffered tokens can come from expanding a multi-token, when Terminal.TryMatch() returns several tokens packed into one token
private ParsingContext Context
{
get { return Parser.Context; }
}
#endregion
#region Scanning tokens
private void NextToken()
{
//1. Check if there are buffered tokens
if (Context.BufferedTokens.Count > 0)
{
Context.CurrentToken = Context.BufferedTokens.Pop();
return;
}
//2. Skip whitespace.
_grammar.SkipWhitespace(Context.Source);
//3. That's the token start, calc location (line and column)
Context.Source.Position = Context.Source.PreviewPosition;
//4. Check for EOF
if (Context.Source.EOF())
{
Context.CurrentToken = new Token(_grammar.Eof, Context.Source.Location, string.Empty, _grammar.Eof.Name);
;
return;
}
//5. Actually scan the source text and construct a new token
ScanToken();
} //method
//Scans the source text and constructs a new token
private void ScanToken()
{
if (!MatchNonGrammarTerminals() && !MatchRegularTerminals())
{
//we are in error already; try to match ANY terminal and let the parser report an error
MatchAllTerminals(); //try to match any terminal out there
}
var token = Context.CurrentToken;
//If we have normal token then return it
if (token != null && !token.IsError())
{
var src = Context.Source;
//set position to point after the result token
src.PreviewPosition = src.Position + token.Length;
src.Position = src.PreviewPosition;
return;
}
//we have an error: either error token or no token at all
if (token == null) //if no token then create error token
Context.CurrentToken = Context.CreateErrorToken(Resources.ErrInvalidChar, Context.Source.PreviewChar);
Recover();
}
private bool MatchNonGrammarTerminals()
{
TerminalList terms;
if (!Data.NonGrammarTerminalsLookup.TryGetValue(Context.Source.PreviewChar, out terms))
return false;
foreach (var term in terms)
{
Context.Source.PreviewPosition = Context.Source.Location.Position;
Context.CurrentToken = term.TryMatch(Context, Context.Source);
if (Context.CurrentToken != null)
term.OnValidateToken(Context);
if (Context.CurrentToken != null)
{
//check if we need to fire LineStart token before this token;
// we do it only if the token is not a comment; comments should be ignored by the outline logic
var token = Context.CurrentToken;
if (token.Category == TokenCategory.Content && NeedLineStartToken(token.Location))
{
Context.BufferedTokens.Push(token); //buffer current token; we'll eject LineStart instead
Context.Source.Location = token.Location; //set it back to the start of the token
Context.CurrentToken = Context.Source.CreateToken(_grammar.LineStartTerminal);
//generate LineStart
Context.PreviousLineStart = Context.Source.Location; //update LineStart
}
return true;
} //if
} //foreach term
Context.Source.PreviewPosition = Context.Source.Location.Position;
return false;
}
private bool NeedLineStartToken(SourceLocation forLocation)
{
return _grammar.LanguageFlags.IsSet(LanguageFlags.EmitLineStartToken) &&
forLocation.Line > Context.PreviousLineStart.Line;
}
private bool MatchRegularTerminals()
{
//We need to eject LineStart BEFORE we try to produce a real token; this LineStart token should reach
// the parser, make it change the state and with it to change the set of expected tokens. So when we
// finally move to scan the real token, the expected terminal set is correct.
if (NeedLineStartToken(Context.Source.Location))
{
Context.CurrentToken = Context.Source.CreateToken(_grammar.LineStartTerminal);
Context.PreviousLineStart = Context.Source.Location;
return true;
}
//Find matching terminal
// First, try terminals with explicit "first-char" prefixes, selected by current char in source
ComputeCurrentTerminals();
//If we have more than one candidate; let grammar method select
if (Context.CurrentTerminals.Count > 1)
_grammar.OnScannerSelectTerminal(Context);
MatchTerminals();
//If we don't have a token from terminals, try Grammar's method
if (Context.CurrentToken == null)
Context.CurrentToken = _grammar.TryMatch(Context, Context.Source);
if (Context.CurrentToken is MultiToken)
UnpackMultiToken();
return Context.CurrentToken != null;
} //method
// This method is a last attempt by scanner to match ANY terminal, after regular matching (by input char) had failed.
// Likely this will produce some token which is invalid for current parser state (for ex, identifier where a number
// is expected); in this case the parser will report an error as "Error: expected number".
// if this matching fails, the scanner will produce an error as "unexpected character."
private bool MatchAllTerminals()
{
Context.CurrentTerminals.Clear();
Context.CurrentTerminals.AddRange(Data.Language.GrammarData.Terminals);
MatchTerminals();
if (Context.CurrentToken is MultiToken)
UnpackMultiToken();
return Context.CurrentToken != null;
}
//If token is MultiToken then push all its child tokens into _bufferdTokens and return the first token in buffer
private void UnpackMultiToken()
{
var mtoken = Context.CurrentToken as MultiToken;
if (mtoken == null) return;
for (var i = mtoken.ChildTokens.Count - 1; i >= 0; i--)
Context.BufferedTokens.Push(mtoken.ChildTokens[i]);
Context.CurrentToken = Context.BufferedTokens.Pop();
}
private void ComputeCurrentTerminals()
{
Context.CurrentTerminals.Clear();
TerminalList termsForCurrentChar;
if (!Data.TerminalsLookup.TryGetValue(Context.Source.PreviewChar, out termsForCurrentChar))
termsForCurrentChar = Data.NoPrefixTerminals;
//if we are recovering, previewing or there's no parser state, then return list as is
if (Context.Status == ParserStatus.Recovering || Context.Status == ParserStatus.Previewing
|| Context.CurrentParserState == null ||
_grammar.LanguageFlags.IsSet(LanguageFlags.DisableScannerParserLink)
|| Context.Mode == ParseMode.VsLineScan)
{
Context.CurrentTerminals.AddRange(termsForCurrentChar);
return;
}
// Try filtering terms by checking with parser which terms it expects;
var parserState = Context.CurrentParserState;
foreach (var term in termsForCurrentChar)
{
//Note that we check the OutputTerminal with parser, not the term itself;
//in most cases it is the same as term, but not always
if (parserState.ExpectedTerminals.Contains(term.OutputTerminal) ||
_grammar.NonGrammarTerminals.Contains(term))
Context.CurrentTerminals.Add(term);
}
} //method
private void MatchTerminals()
{
Token priorToken = null;
for (var i = 0; i < Context.CurrentTerminals.Count; i++)
{
var term = Context.CurrentTerminals[i];
// If we have priorToken from prior term in the list, check if prior term has higher priority than this term;
// if term.Priority is lower then we don't need to check anymore, higher priority (in prior token) wins
// Note that terminals in the list are sorted in descending priority order
if (priorToken != null && priorToken.Terminal.Priority > term.Priority)
return;
//Reset source position and try to match
Context.Source.PreviewPosition = Context.Source.Location.Position;
var token = term.TryMatch(Context, Context.Source);
if (token == null) continue;
//skip it if it is shorter than previous token
if (priorToken != null && !priorToken.IsError() && (token.Length < priorToken.Length))
continue;
Context.CurrentToken = token; //now it becomes current token
term.OnValidateToken(Context); //validate it
if (Context.CurrentToken != null)
priorToken = Context.CurrentToken;
}
} //method
#endregion
#region VS Integration methods
//Use this method for VS integration; VS language package requires scanner that returns tokens one-by-one.
// Start and End positions required by this scanner may be derived from Token :
// start=token.Location.Position; end=start + token.Length;
public Token VsReadToken(ref int state)
{
Context.VsLineScanState.Value = state;
if (Context.Source.EOF()) return null;
if (state == 0)
NextToken();
else
{
var term = Data.MultilineTerminals[Context.VsLineScanState.TerminalIndex - 1];
Context.CurrentToken = term.TryMatch(Context, Context.Source);
}
//set state value from context
state = Context.VsLineScanState.Value;
if (Context.CurrentToken != null && Context.CurrentToken.Terminal == _grammar.Eof)
return null;
return Context.CurrentToken;
}
public void VsSetSource(string text, int offset)
{
var line = Context.Source == null ? 0 : Context.Source.Location.Line;
var newLoc = new SourceLocation(offset, line + 1, 0);
Context.Source = new SourceStream(text, Context.Language.Grammar.CaseSensitive, Context.TabWidth, newLoc);
}
#endregion
#region TokenPreview
//Preview mode allows custom code in grammar to help parser decide on appropriate action in case of conflict
// Preview process is simply searching for particular tokens in "preview set", and finding out which of the
// tokens will come first.
// In preview mode, tokens returned by FetchToken are collected in _previewTokens list; after finishing preview
// the scanner "rolls back" to original position - either by directly restoring the position, or moving the preview
// tokens into _bufferedTokens list, so that they will read again by parser in normal mode.
// See c# grammar sample for an example of using preview methods
private SourceLocation _previewStartLocation;
//Switches Scanner into preview mode
public void BeginPreview()
{
Context.Status = ParserStatus.Previewing;
_previewStartLocation = Context.Source.Location;
Context.PreviewTokens.Clear();
}
//Ends preview mode
public void EndPreview(bool keepPreviewTokens)
{
if (keepPreviewTokens)
{
//insert previewed tokens into buffered list, so we don't recreate them again
while (Context.PreviewTokens.Count > 0)
Context.BufferedTokens.Push(Context.PreviewTokens.Pop());
}
else
Context.SetSourceLocation(_previewStartLocation);
Context.PreviewTokens.Clear();
Context.Status = ParserStatus.Parsing;
}
#endregion
} //class
} //namespace
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal abstract class PlaceholderLocalSymbol : EELocalSymbolBase
{
private readonly MethodSymbol _method;
private readonly string _name;
private readonly TypeSymbol _type;
internal readonly string DisplayName;
internal PlaceholderLocalSymbol(MethodSymbol method, string name, string displayName, TypeSymbol type)
{
_method = method;
_name = name;
_type = type;
this.DisplayName = displayName;
}
internal static LocalSymbol Create(
TypeNameDecoder<PEModuleSymbol, TypeSymbol> typeNameDecoder,
MethodSymbol containingMethod,
AssemblySymbol sourceAssembly,
Alias alias)
{
var typeName = alias.Type;
Debug.Assert(typeName.Length > 0);
var type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName);
Debug.Assert((object)type != null);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(alias.CustomTypeInfoId, alias.CustomTypeInfo, out dynamicFlags, out tupleElementNames);
if (dynamicFlags != null)
{
type = DecodeDynamicTypes(type, sourceAssembly, dynamicFlags);
}
if (tupleElementNames != null)
{
type = TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, sourceAssembly, tupleElementNames.AsImmutable());
}
var name = alias.FullName;
var displayName = alias.Name;
switch (alias.Kind)
{
case DkmClrAliasKind.Exception:
return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName);
case DkmClrAliasKind.StowedException:
return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName);
case DkmClrAliasKind.ReturnValue:
{
int index;
PseudoVariableUtilities.TryParseReturnValueIndex(name, out index);
Debug.Assert(index >= 0);
return new ReturnValueLocalSymbol(containingMethod, name, displayName, type, index);
}
case DkmClrAliasKind.ObjectId:
return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: false);
case DkmClrAliasKind.Variable:
return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: true);
default:
throw ExceptionUtilities.UnexpectedValue(alias.Kind);
}
}
internal override LocalDeclarationKind DeclarationKind
{
get { return LocalDeclarationKind.RegularVariable; }
}
internal override SyntaxToken IdentifierToken
{
get { throw ExceptionUtilities.Unreachable; }
}
public override TypeSymbol Type
{
get { return _type; }
}
internal override bool IsPinned
{
get { return false; }
}
internal override bool IsCompilerGenerated
{
get { return true; }
}
internal override RefKind RefKind
{
get { return RefKind.None; }
}
public override Symbol ContainingSymbol
{
get { return _method; }
}
public override ImmutableArray<Location> Locations
{
get { return NoLocations; }
}
public override string Name
{
get { return _name; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { return ImmutableArray<SyntaxReference>.Empty; }
}
internal abstract override bool IsWritable { get; }
internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap)
{
// Placeholders should be rewritten (as method calls)
// rather than copied as locals to the target method.
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Rewrite the local reference as a call to a synthesized method.
/// </summary>
internal abstract BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics);
internal static BoundExpression ConvertToLocalType(CSharpCompilation compilation, BoundExpression expr, TypeSymbol type, DiagnosticBag diagnostics)
{
if (type.IsPointerType())
{
var syntax = expr.Syntax;
var intPtrType = compilation.GetSpecialType(SpecialType.System_IntPtr);
Binder.ReportUseSiteDiagnostics(intPtrType, diagnostics, syntax);
MethodSymbol conversionMethod;
if (Binder.TryGetSpecialTypeMember(compilation, SpecialMember.System_IntPtr__op_Explicit_ToPointer, syntax, diagnostics, out conversionMethod))
{
var temp = ConvertToLocalTypeHelper(compilation, expr, intPtrType, diagnostics);
expr = BoundCall.Synthesized(
syntax,
receiverOpt: null,
method: conversionMethod,
arg0: temp);
}
else
{
return new BoundBadExpression(
syntax,
LookupResultKind.Empty,
ImmutableArray<Symbol>.Empty,
ImmutableArray.Create<BoundNode>(expr),
type);
}
}
return ConvertToLocalTypeHelper(compilation, expr, type, diagnostics);
}
private static BoundExpression ConvertToLocalTypeHelper(CSharpCompilation compilation, BoundExpression expr, TypeSymbol type, DiagnosticBag diagnostics)
{
// NOTE: This conversion can fail if some of the types involved are from not-yet-loaded modules.
// For example, if System.Exception hasn't been loaded, then this call will fail for $stowedexception.
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var conversion = compilation.Conversions.ClassifyConversionFromExpression(expr, type, ref useSiteDiagnostics);
diagnostics.Add(expr.Syntax, useSiteDiagnostics);
Debug.Assert(conversion.IsValid || diagnostics.HasAnyErrors());
return BoundConversion.Synthesized(
expr.Syntax,
expr,
conversion,
@checked: false,
explicitCastInCode: false,
constantValueOpt: null,
type: type,
hasErrors: !conversion.IsValid);
}
internal static MethodSymbol GetIntrinsicMethod(CSharpCompilation compilation, string methodName)
{
var type = compilation.GetTypeByMetadataName(ExpressionCompilerConstants.IntrinsicAssemblyTypeMetadataName);
var members = type.GetMembers(methodName);
Debug.Assert(members.Length == 1);
return (MethodSymbol)members[0];
}
private static TypeSymbol DecodeDynamicTypes(TypeSymbol type, AssemblySymbol sourceAssembly, ReadOnlyCollection<byte> bytes)
{
var builder = ArrayBuilder<bool>.GetInstance();
DynamicFlagsCustomTypeInfo.CopyTo(bytes, builder);
var dynamicType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(
type,
sourceAssembly,
RefKind.None,
builder.ToImmutableAndFree(),
checkLength: false);
Debug.Assert((object)dynamicType != null);
Debug.Assert(dynamicType != type);
return dynamicType;
}
}
}
| |
// 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.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.NetworkInformation.Tests
{
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Ping class not supported on UWP. See dotnet/corefx #19583")]
public class PingTest
{
private class FinalizingPing : Ping
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingPing();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private static void PingResultValidator(PingReply pingReply, IPAddress localIpAddress)
{
if (pingReply.Status == IPStatus.TimedOut)
{
// Workaround OSX ping6 bug, refer issue #15018
Assert.Equal(AddressFamily.InterNetworkV6, localIpAddress.AddressFamily);
Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.OSX));
return;
}
Assert.Equal(IPStatus.Success, pingReply.Status);
Assert.True(pingReply.Address.Equals(localIpAddress));
}
[Fact]
public async Task SendPingAsync_InvalidArgs()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
Ping p = new Ping();
// Null address
AssertExtensions.Throws<ArgumentNullException>("address", () => { p.SendPingAsync((IPAddress)null); });
AssertExtensions.Throws<ArgumentNullException>("hostNameOrAddress", () => { p.SendPingAsync((string)null); });
AssertExtensions.Throws<ArgumentNullException>("address", () => { p.SendAsync((IPAddress)null, null); });
AssertExtensions.Throws<ArgumentNullException>("hostNameOrAddress", () => { p.SendAsync((string)null, null); });
AssertExtensions.Throws<ArgumentNullException>("address", () => { p.Send((IPAddress)null); });
AssertExtensions.Throws<ArgumentNullException>("hostNameOrAddress", () => { p.Send((string)null); });
// Invalid address
AssertExtensions.Throws<ArgumentException>("address", () => { p.SendPingAsync(IPAddress.Any); });
AssertExtensions.Throws<ArgumentException>("address", () => { p.SendPingAsync(IPAddress.IPv6Any); });
AssertExtensions.Throws<ArgumentException>("address", () => { p.SendAsync(IPAddress.Any, null); });
AssertExtensions.Throws<ArgumentException>("address", () => { p.SendAsync(IPAddress.IPv6Any, null); });
AssertExtensions.Throws<ArgumentException>("address", () => { p.Send(IPAddress.Any); });
AssertExtensions.Throws<ArgumentException>("address", () => { p.Send(IPAddress.IPv6Any); });
// Negative timeout
AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(localIpAddress, -1); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(TestSettings.LocalHost, -1); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(localIpAddress, -1, null); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(TestSettings.LocalHost, -1, null); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { p.Send(localIpAddress, -1); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { p.Send(TestSettings.LocalHost, -1); });
// Null byte[]
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { p.SendPingAsync(localIpAddress, 0, null); });
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 0, null); });
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { p.SendAsync(localIpAddress, 0, null, null); });
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { p.SendAsync(TestSettings.LocalHost, 0, null, null); });
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { p.Send(localIpAddress, 0, null); });
AssertExtensions.Throws<ArgumentNullException>("buffer", () => { p.Send(TestSettings.LocalHost, 0, null); });
// Too large byte[]
AssertExtensions.Throws<ArgumentException>("buffer", () => { p.SendPingAsync(localIpAddress, 1, new byte[65501]); });
AssertExtensions.Throws<ArgumentException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 1, new byte[65501]); });
AssertExtensions.Throws<ArgumentException>("buffer", () => { p.SendAsync(localIpAddress, 1, new byte[65501], null); });
AssertExtensions.Throws<ArgumentException>("buffer", () => { p.SendAsync(TestSettings.LocalHost, 1, new byte[65501], null); });
AssertExtensions.Throws<ArgumentException>("buffer", () => { p.Send(localIpAddress, 1, new byte[65501]); });
AssertExtensions.Throws<ArgumentException>("buffer", () => { p.Send(TestSettings.LocalHost, 1, new byte[65501]); });
}
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public void SendPingWithIPAddress(AddressFamily addressFamily)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
SendBatchPing(
(ping) => ping.Send(localIpAddress),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public async Task SendPingAsyncWithIPAddress(AddressFamily addressFamily)
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public void SendPingWithIPAddress_AddressAsString(AddressFamily addressFamily)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
SendBatchPing(
(ping) => ping.Send(localIpAddress.ToString()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
public async Task SendPingAsyncWithIPAddress_AddressAsString()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress.ToString()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
[ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public void SendPingWithIPAddressAndTimeout()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
[ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public async Task SendPingAsyncWithIPAddressAndTimeout()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public void SendPingWithIPAddressAndTimeoutAndBuffer()
{
byte[] buffer = TestSettings.PayloadAsBytes;
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public async Task SendPingAsyncWithIPAddressAndTimeoutAndBuffer()
{
byte[] buffer = TestSettings.PayloadAsBytes;
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public void SendPingWithIPAddressAndTimeoutAndBuffer_Unix()
{
byte[] buffer = TestSettings.PayloadAsBytes;
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public async Task SendPingAsyncWithIPAddressAndTimeoutAndBuffer_Unix()
{
byte[] buffer = TestSettings.PayloadAsBytes;
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public void SendPingWithIPAddressAndTimeoutAndBufferAndPingOptions()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
var options = new PingOptions();
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout, buffer, options),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
Assert.InRange(pingReply.RoundtripTime, 0, long.MaxValue);
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
var options = new PingOptions();
byte[] buffer = TestSettings.PayloadAsBytes;
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, options),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
Assert.InRange(pingReply.RoundtripTime, 0, long.MaxValue);
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public void SendPingWithIPAddressAndTimeoutAndBufferAndPingOptions_Unix(AddressFamily addressFamily)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions_Unix(AddressFamily addressFamily)
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
byte[] buffer = TestSettings.PayloadAsBytes;
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[Fact]
public void SendPingWithHost()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
public async Task SendPingAsyncWithHost()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
public void SendPingWithHostAndTimeout()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
public async Task SendPingAsyncWithHostAndTimeout()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public void SendPingWithHostAndTimeoutAndBuffer()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public async Task SendPingAsyncWithHostAndTimeoutAndBuffer()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
byte[] buffer = TestSettings.PayloadAsBytes;
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public void SendPingWithHostAndTimeoutAndBuffer_Unix()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public async Task SendPingAsyncWithHostAndTimeoutAndBuffer_Unix()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
byte[] buffer = TestSettings.PayloadAsBytes;
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public void SendPingWithHostAndTimeoutAndBufferAndPingOptions()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public async Task SendPingAsyncWithHostAndTimeoutAndBufferAndPingOptions()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
byte[] buffer = TestSettings.PayloadAsBytes;
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public void SendPingWithHostAndTimeoutAndBufferAndPingOptions_Unix()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
[Fact]
public async Task SendPingAsyncWithHostAndTimeoutAndBufferAndPingOptions_Unix()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
byte[] buffer = TestSettings.PayloadAsBytes;
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
{
Assert.Equal(buffer, pingReply.Buffer);
}
else
{
Assert.Equal(Array.Empty<byte>(), pingReply.Buffer);
}
});
}
[Fact]
public static async Task SendPings_ReuseInstance_Hostname()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
using (Ping p = new Ping())
{
for (int i = 0; i < 3; i++)
{
PingReply pingReply = await p.SendPingAsync(TestSettings.LocalHost);
PingResultValidator(pingReply, localIpAddress);
}
}
}
[Fact]
public static async Task Sends_ReuseInstance_Hostname()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
using (Ping p = new Ping())
{
for (int i = 0; i < 3; i++)
{
PingReply pingReply = p.Send(TestSettings.LocalHost);
PingResultValidator(pingReply, localIpAddress);
}
}
}
[Fact]
public static async Task SendAsyncs_ReuseInstance_Hostname()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
using (Ping p = new Ping())
{
TaskCompletionSource<bool> tcs = null;
PingCompletedEventArgs ea = null;
p.PingCompleted += (s, e) =>
{
ea = e;
tcs.TrySetResult(true);
};
Action reset = () =>
{
ea = null;
tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
};
// Several normal iterations
for (int i = 0; i < 3; i++)
{
reset();
p.SendAsync(TestSettings.LocalHost, null);
await tcs.Task;
Assert.NotNull(ea);
PingResultValidator(ea.Reply, localIpAddress);
}
// Several canceled iterations
for (int i = 0; i < 3; i++)
{
reset();
p.SendAsync(TestSettings.LocalHost, null);
p.SendAsyncCancel(); // will block until operation can be started again
await tcs.Task;
bool cancelled = ea.Cancelled;
Exception error = ea.Error;
PingReply reply = ea.Reply;
Assert.True(cancelled ^ (error != null) ^ (reply != null),
"Cancelled: " + cancelled +
(error == null ? "" : (Environment.NewLine + "Error Message: " + error.Message + Environment.NewLine + "Error Inner Exception: " + error.InnerException)) +
(reply == null ? "" : (Environment.NewLine + "Reply Address: " + reply.Address + Environment.NewLine + "Reply Status: " + reply.Status)));
}
}
}
[Fact]
public static void Ping_DisposeAfterSend_Success()
{
Ping p = new Ping();
p.Send(TestSettings.LocalHost);
p.Dispose();
}
[Fact]
public static async Task PingAsync_DisposeAfterSend_Success()
{
Ping p = new Ping();
await p.SendPingAsync(TestSettings.LocalHost);
p.Dispose();
}
[Fact]
public static void Ping_DisposeMultipletimes_Success()
{
Ping p = new Ping();
p.Dispose();
p.Dispose();
}
[Fact]
public static void Ping_SendAfterDispose_ThrowsSynchronously()
{
Ping p = new Ping();
p.Dispose();
Assert.Throws<ObjectDisposedException>(() => { p.Send(TestSettings.LocalHost); });
}
[Fact]
public static void PingAsync_SendAfterDispose_ThrowsSynchronously()
{
Ping p = new Ping();
p.Dispose();
Assert.Throws<ObjectDisposedException>(() => { p.SendPingAsync(TestSettings.LocalHost); });
}
private static readonly int s_pingcount = 4;
private static void SendBatchPing(Func<Ping, PingReply> sendPing, Action<PingReply> pingResultValidator)
{
for (int i = 0; i < s_pingcount; i++)
{
SendPing(sendPing, pingResultValidator);
}
}
private static Task SendBatchPingAsync(Func<Ping, Task<PingReply>> sendPing, Action<PingReply> pingResultValidator)
{
// create several concurrent pings
Task[] pingTasks = new Task[s_pingcount];
for (int i = 0; i < s_pingcount; i++)
{
pingTasks[i] = SendPingAsync(sendPing, pingResultValidator);
}
return Task.WhenAll(pingTasks);
}
private static void SendPing(Func<Ping, PingReply> sendPing, Action<PingReply> pingResultValidator)
{
var pingResult = sendPing(new Ping());
pingResultValidator(pingResult);
}
private static async Task SendPingAsync(Func<Ping, Task<PingReply>> sendPing, Action<PingReply> pingResultValidator)
{
var pingResult = await sendPing(new Ping());
pingResultValidator(pingResult);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "GC has different behavior on Mono")]
public void CanBeFinalized()
{
FinalizingPing.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingPing.WasFinalized);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.