context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal static class TypeManager
{
// The RuntimeBinder uses a global lock when Binding that keeps this dictionary safe.
private static readonly Dictionary<(Assembly, Assembly), bool> s_internalsVisibleToCache =
new Dictionary<(Assembly, Assembly), bool>();
private static readonly StdTypeVarColl s_stvcMethod = new StdTypeVarColl();
private sealed class StdTypeVarColl
{
private readonly List<TypeParameterType> prgptvs;
public StdTypeVarColl()
{
prgptvs = new List<TypeParameterType>();
}
////////////////////////////////////////////////////////////////////////////////
// Get the standard type variable (eg, !0, !1, or !!0, !!1).
//
// iv is the index.
// pbsm is the containing symbol manager
// fMeth designates whether this is a method type var or class type var
//
// The standard class type variables are useful during emit, but not for type
// comparison when binding. The standard method type variables are useful during
// binding for signature comparison.
public TypeParameterType GetTypeVarSym(int iv, bool fMeth)
{
Debug.Assert(iv >= 0);
TypeParameterType tpt;
if (iv >= prgptvs.Count)
{
TypeParameterSymbol pTypeParameter = new TypeParameterSymbol();
pTypeParameter.SetIsMethodTypeParameter(fMeth);
pTypeParameter.SetIndexInOwnParameters(iv);
pTypeParameter.SetIndexInTotalParameters(iv);
pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE);
tpt = GetTypeParameter(pTypeParameter);
prgptvs.Add(tpt);
}
else
{
tpt = prgptvs[iv];
}
Debug.Assert(tpt != null);
return tpt;
}
}
public static ArrayType GetArray(CType elementType, int args, bool isSZArray)
{
Debug.Assert(args > 0 && args < 32767);
Debug.Assert(args == 1 || !isSZArray);
int rankNum = isSZArray ? 0 : args;
// See if we already have an array type of this element type and rank.
ArrayType pArray = TypeTable.LookupArray(elementType, rankNum);
if (pArray == null)
{
// No existing array symbol. Create a new one.
pArray = new ArrayType(elementType, args, isSZArray);
TypeTable.InsertArray(elementType, rankNum, pArray);
}
Debug.Assert(pArray.Rank == args);
Debug.Assert(pArray.ElementType == elementType);
return pArray;
}
public static AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs)
{
Debug.Assert(atsOuter == null || atsOuter.OwningAggregate == agg.Parent, "");
if (typeArgs == null)
{
typeArgs = TypeArray.Empty;
}
Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count);
AggregateType pAggregate = TypeTable.LookupAggregate(agg, atsOuter, typeArgs);
if (pAggregate == null)
{
pAggregate = new AggregateType(agg, typeArgs, atsOuter);
Debug.Assert(!pAggregate.ConstraintError.HasValue);
TypeTable.InsertAggregate(agg, atsOuter, typeArgs, pAggregate);
}
Debug.Assert(pAggregate.OwningAggregate == agg);
Debug.Assert(pAggregate.TypeArgsThis != null && pAggregate.TypeArgsAll != null);
Debug.Assert(pAggregate.TypeArgsThis == typeArgs);
return pAggregate;
}
public static AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll)
{
Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count);
if (typeArgsAll.Count == 0)
return agg.getThisType();
AggregateSymbol aggOuter = agg.GetOuterAgg();
if (aggOuter == null)
return GetAggregate(agg, null, typeArgsAll);
int cvarOuter = aggOuter.GetTypeVarsAll().Count;
Debug.Assert(cvarOuter <= typeArgsAll.Count);
TypeArray typeArgsOuter = TypeArray.Allocate(cvarOuter, typeArgsAll, 0);
TypeArray typeArgsInner = TypeArray.Allocate(agg.GetTypeVars().Count, typeArgsAll, cvarOuter);
AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter);
return GetAggregate(agg, atsOuter, typeArgsInner);
}
public static PointerType GetPointer(CType baseType)
{
PointerType pPointer = TypeTable.LookupPointer(baseType);
if (pPointer == null)
{
// No existing type. Create a new one.
pPointer = new PointerType(baseType);
TypeTable.InsertPointer(baseType, pPointer);
}
Debug.Assert(pPointer.ReferentType == baseType);
return pPointer;
}
public static NullableType GetNullable(CType pUnderlyingType)
{
Debug.Assert(!(pUnderlyingType is NullableType), "Attempt to make nullable of nullable");
NullableType pNullableType = TypeTable.LookupNullable(pUnderlyingType);
if (pNullableType == null)
{
pNullableType = new NullableType(pUnderlyingType);
TypeTable.InsertNullable(pUnderlyingType, pNullableType);
}
return pNullableType;
}
public static ParameterModifierType GetParameterModifier(CType paramType, bool isOut)
{
ParameterModifierType pParamModifier = TypeTable.LookupParameterModifier(paramType, isOut);
if (pParamModifier == null)
{
// No existing parammod symbol. Create a new one.
pParamModifier = new ParameterModifierType(paramType, isOut);
TypeTable.InsertParameterModifier(paramType, isOut, pParamModifier);
}
Debug.Assert(pParamModifier.ParameterType == paramType);
return pParamModifier;
}
public static AggregateSymbol GetNullable() => GetPredefAgg(PredefinedType.PT_G_OPTIONAL);
private static CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, bool denormMeth)
{
Debug.Assert(typeSrc != null);
SubstContext ctx = new SubstContext(typeArgsCls, typeArgsMeth, denormMeth);
return ctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
public static AggregateType SubstType(AggregateType typeSrc, TypeArray typeArgsCls)
{
Debug.Assert(typeSrc != null);
SubstContext ctx = new SubstContext(typeArgsCls, null, false);
return ctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
private static CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth) =>
SubstType(typeSrc, typeArgsCls, typeArgsMeth, false);
public static TypeArray SubstTypeArray(TypeArray taSrc, SubstContext ctx)
{
if (taSrc != null && taSrc.Count != 0 && ctx != null && !ctx.IsNop)
{
CType[] srcs = taSrc.Items;
for (int i = 0; i < srcs.Length; i++)
{
CType src = srcs[i];
CType dst = SubstTypeCore(src, ctx);
if (src != dst)
{
CType[] dsts = new CType[srcs.Length];
Array.Copy(srcs, 0, dsts, 0, i);
dsts[i] = dst;
while (++i < srcs.Length)
{
dsts[i] = SubstTypeCore(srcs[i], ctx);
}
return TypeArray.Allocate(dsts);
}
}
}
return taSrc;
}
public static TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
=> taSrc == null || taSrc.Count == 0
? taSrc
: SubstTypeArray(taSrc, new SubstContext(typeArgsCls, typeArgsMeth, false));
public static TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls) => SubstTypeArray(taSrc, typeArgsCls, null);
private static AggregateType SubstTypeCore(AggregateType type, SubstContext ctx)
{
TypeArray args = type.TypeArgsAll;
if (args.Count > 0)
{
TypeArray typeArgs = SubstTypeArray(args, ctx);
if (args != typeArgs)
{
return GetAggregate(type.OwningAggregate, typeArgs);
}
}
return type;
}
private static CType SubstTypeCore(CType type, SubstContext pctx)
{
CType typeSrc;
CType typeDst;
switch (type.TypeKind)
{
default:
Debug.Fail("Unknown type kind");
return type;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_ArgumentListType:
return type;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType mod = (ParameterModifierType)type;
typeDst = SubstTypeCore(typeSrc = mod.ParameterType, pctx);
return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, mod.IsOut);
case TypeKind.TK_ArrayType:
var arr = (ArrayType)type;
typeDst = SubstTypeCore(typeSrc = arr.ElementType, pctx);
return (typeDst == typeSrc) ? type : GetArray(typeDst, arr.Rank, arr.IsSZArray);
case TypeKind.TK_PointerType:
typeDst = SubstTypeCore(typeSrc = ((PointerType)type).ReferentType, pctx);
return (typeDst == typeSrc) ? type : GetPointer(typeDst);
case TypeKind.TK_NullableType:
typeDst = SubstTypeCore(typeSrc = ((NullableType)type).UnderlyingType, pctx);
return (typeDst == typeSrc) ? type : GetNullable(typeDst);
case TypeKind.TK_AggregateType:
return SubstTypeCore((AggregateType)type, pctx);
case TypeKind.TK_TypeParameterType:
{
TypeParameterSymbol tvs = ((TypeParameterType)type).Symbol;
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if (pctx.DenormMeth && tvs.parent != null)
{
return type;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
if (index < pctx.MethodTypes.Length)
{
Debug.Assert(pctx.MethodTypes != null);
return pctx.MethodTypes[index];
}
return type;
}
return index < pctx.ClassTypes.Length ? pctx.ClassTypes[index] : type;
}
}
}
public static bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, bool denormMeth)
{
if (typeDst.Equals(typeSrc))
{
Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, denormMeth)));
return true;
}
SubstContext ctx = new SubstContext(typeArgsCls, typeArgsMeth, denormMeth);
return !ctx.IsNop && SubstEqualTypesCore(typeDst, typeSrc, ctx);
}
public static bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
// Handle the simple common cases first.
if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc)))
{
// The following assertion is not always true and indicates a problem where
// the signature of override method does not match the one inherited from
// the base class. The method match we have found does not take the type
// arguments of the base class into account. So actually we are not overriding
// the method that we "intend" to.
// Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst));
return true;
}
if (taDst.Count != taSrc.Count)
return false;
if (taDst.Count == 0)
return true;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, true);
if (ctx.IsNop)
{
return false;
}
for (int i = 0; i < taDst.Count; i++)
{
if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx))
return false;
}
return true;
}
private static bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx)
{
LRecurse: // Label used for "tail" recursion.
if (typeDst == typeSrc || typeDst.Equals(typeSrc))
{
return true;
}
switch (typeSrc.TypeKind)
{
default:
Debug.Fail("Bad Symbol kind in SubstEqualTypesCore");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeDst.TypeKind != typeSrc.TypeKind);
return false;
case TypeKind.TK_ArrayType:
ArrayType arrSrc = (ArrayType)typeSrc;
if (!(typeDst is ArrayType arrDst) || arrDst.Rank != arrSrc.Rank || arrDst.IsSZArray != arrSrc.IsSZArray)
return false;
goto LCheckBases;
case TypeKind.TK_ParameterModifierType:
if (!(typeDst is ParameterModifierType modDest) || modDest.IsOut != ((ParameterModifierType)typeSrc).IsOut)
{
return false;
}
goto LCheckBases;
case TypeKind.TK_PointerType:
case TypeKind.TK_NullableType:
if (typeDst.TypeKind != typeSrc.TypeKind)
return false;
LCheckBases:
typeSrc = typeSrc.BaseOrParameterOrElementType;
typeDst = typeDst.BaseOrParameterOrElementType;
goto LRecurse;
case TypeKind.TK_AggregateType:
if (!(typeDst is AggregateType atsDst))
return false;
{ // BLOCK
AggregateType atsSrc = (AggregateType)typeSrc;
if (atsSrc.OwningAggregate != atsDst.OwningAggregate)
return false;
Debug.Assert(atsSrc.TypeArgsAll.Count == atsDst.TypeArgsAll.Count);
// All the args must unify.
for (int i = 0; i < atsSrc.TypeArgsAll.Count; i++)
{
if (!SubstEqualTypesCore(atsDst.TypeArgsAll[i], atsSrc.TypeArgsAll[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_TypeParameterType:
{ // BLOCK
TypeParameterSymbol tvs = ((TypeParameterType)typeSrc).Symbol;
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if (pctx.DenormMeth && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == index);
Debug.Assert(tvs.GetIndexInTotalParameters() < pctx.MethodTypes.Length);
if (index < pctx.MethodTypes.Length)
{
return typeDst == pctx.MethodTypes[index];
}
}
else
{
Debug.Assert(index < pctx.ClassTypes.Length);
if (index < pctx.ClassTypes.Length)
{
return typeDst == pctx.ClassTypes[index];
}
}
}
return false;
}
}
public static bool TypeContainsType(CType type, CType typeFind)
{
LRecurse: // Label used for "tail" recursion.
if (type == typeFind || type.Equals(typeFind))
return true;
switch (type.TypeKind)
{
default:
Debug.Fail("Bad Symbol kind in TypeContainsType");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeFind.TypeKind != type.TypeKind);
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.BaseOrParameterOrElementType;
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.TypeArgsAll.Count; i++)
{
if (TypeContainsType(ats.TypeArgsAll[i], typeFind))
return true;
}
}
return false;
case TypeKind.TK_TypeParameterType:
return false;
}
}
public static bool TypeContainsTyVars(CType type, TypeArray typeVars)
{
LRecurse: // Label used for "tail" recursion.
switch (type.TypeKind)
{
default:
Debug.Fail("Bad Symbol kind in TypeContainsTyVars");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.BaseOrParameterOrElementType;
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.TypeArgsAll.Count; i++)
{
if (TypeContainsTyVars(ats.TypeArgsAll[i], typeVars))
{
return true;
}
}
}
return false;
case TypeKind.TK_TypeParameterType:
if (typeVars != null && typeVars.Count > 0)
{
int ivar = ((TypeParameterType)type).IndexInTotalParameters;
return ivar < typeVars.Count && type == typeVars[ivar];
}
return true;
}
}
public static AggregateSymbol GetPredefAgg(PredefinedType pt) => PredefinedTypes.GetPredefinedAggregate(pt);
public static AggregateType SubstType(AggregateType typeSrc, SubstContext ctx) =>
ctx == null || ctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, ctx);
public static CType SubstType(CType typeSrc, SubstContext pctx) =>
pctx == null || pctx.IsNop ? typeSrc : SubstTypeCore(typeSrc, pctx);
public static CType SubstType(CType typeSrc, AggregateType atsCls) => SubstType(typeSrc, atsCls, null);
public static CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth) =>
SubstType(typeSrc, atsCls?.TypeArgsAll, typeArgsMeth);
public static CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth) =>
SubstType(typeSrc, (typeCls as AggregateType)?.TypeArgsAll, typeArgsMeth);
public static TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth) =>
SubstTypeArray(taSrc, atsCls?.TypeArgsAll, typeArgsMeth);
public static TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls) => SubstTypeArray(taSrc, atsCls, null);
private static bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth) =>
SubstEqualTypes(typeDst, typeSrc, (typeCls as AggregateType)?.TypeArgsAll, typeArgsMeth, false);
public static bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls) => SubstEqualTypes(typeDst, typeSrc, typeCls, null);
public static TypeParameterType GetStdMethTypeVar(int iv) => s_stvcMethod.GetTypeVarSym(iv, true);
// These are singletons for each.
public static TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol)
{
Debug.Assert(pSymbol.GetTypeParameterType() == null); // Should have been checked first before creating
return new TypeParameterType(pSymbol);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal static CType GetBestAccessibleType(AggregateSymbol context, CType typeSrc)
{
// This method implements the "best accessible type" algorithm for determining the type
// of untyped arguments in the runtime binder. It is also used in method type inference
// to fix type arguments to types that are accessible.
// The new type is returned in an out parameter. The result will be true (and the out param
// non-null) only when the algorithm could find a suitable accessible type.
Debug.Assert(typeSrc != null);
Debug.Assert(!(typeSrc is ParameterModifierType));
Debug.Assert(!(typeSrc is PointerType));
if (CSemanticChecker.CheckTypeAccess(typeSrc, context))
{
// If we already have an accessible type, then use it.
return typeSrc;
}
// These guys have no accessibility concerns.
Debug.Assert(!(typeSrc is VoidType) && !(typeSrc is TypeParameterType));
if (typeSrc is AggregateType aggSrc)
{
while (true)
{
if ((aggSrc.IsInterfaceType || aggSrc.IsDelegateType) && TryVarianceAdjustmentToGetAccessibleType(context, aggSrc, out CType typeDst))
{
// If we have an interface or delegate type, then it can potentially be varied by its type arguments
// to produce an accessible type, and if that's the case, then return that.
// Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo>
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return typeDst;
}
// We have an AggregateType, so recurse on its base class.
AggregateType baseType = aggSrc.BaseClass;
if (baseType == null)
{
// This happens with interfaces, for instance. But in that case, the
// conversion to object does exist, is an implicit reference conversion,
// and is guaranteed to be accessible, so we will use it.
return GetPredefAgg(PredefinedType.PT_OBJECT).getThisType();
}
if (CSemanticChecker.CheckTypeAccess(baseType, context))
{
return baseType;
}
// baseType is always an AggregateType, so no need for logic of other types.
aggSrc = baseType;
}
}
if (typeSrc is ArrayType arrSrc)
{
if (TryArrayVarianceAdjustmentToGetAccessibleType(context, arrSrc, out CType typeDst))
{
// Similarly to the interface and delegate case, arrays are covariant in their element type and
// so we can potentially produce an array type that is accessible.
// Example: PrivateConcreteFoo[] --> PublicAbstractFoo[]
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return typeDst;
}
// We have an inaccessible array type for which we could not earlier find a better array type
// with a covariant conversion, so the best we can do is System.Array.
return GetPredefAgg(PredefinedType.PT_ARRAY).getThisType();
}
Debug.Assert(typeSrc is NullableType);
// We have an inaccessible nullable type, which means that the best we can do is System.ValueType.
return GetPredefAgg(PredefinedType.PT_VALUE).getThisType();
}
private static bool TryVarianceAdjustmentToGetAccessibleType(AggregateSymbol context, AggregateType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
Debug.Assert(typeSrc.IsInterfaceType || typeSrc.IsDelegateType);
typeDst = null;
AggregateSymbol aggSym = typeSrc.OwningAggregate;
AggregateType aggOpenType = aggSym.getThisType();
if (!CSemanticChecker.CheckTypeAccess(aggOpenType, context))
{
// if the aggregate symbol itself is not accessible, then forget it, there is no
// variance that will help us arrive at an accessible type.
return false;
}
TypeArray typeArgs = typeSrc.TypeArgsThis;
TypeArray typeParams = aggOpenType.TypeArgsThis;
CType[] newTypeArgsTemp = new CType[typeArgs.Count];
for (int i = 0; i < newTypeArgsTemp.Length; i++)
{
CType typeArg = typeArgs[i];
if (CSemanticChecker.CheckTypeAccess(typeArg, context))
{
// we have an accessible argument, this position is not a problem.
newTypeArgsTemp[i] = typeArg;
continue;
}
if (!typeArg.IsReferenceType || !((TypeParameterType)typeParams[i]).Covariant)
{
// This guy is inaccessible, and we are not going to be able to vary him, so we need to fail.
return false;
}
newTypeArgsTemp[i] = GetBestAccessibleType(context, typeArg);
// now we either have a value type (which must be accessible due to the above
// check, OR we have an inaccessible type (which must be a ref type). In either
// case, the recursion worked out and we are OK to vary this argument.
}
TypeArray newTypeArgs = TypeArray.Allocate(newTypeArgsTemp);
CType intermediateType = GetAggregate(aggSym, typeSrc.OuterType, newTypeArgs);
// All type arguments were varied successfully, which means now we must be accessible. But we could
// have violated constraints. Let's check that out.
if (!TypeBind.CheckConstraints(intermediateType, CheckConstraintsFlags.NoErrors))
{
return false;
}
typeDst = intermediateType;
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return true;
}
private static bool TryArrayVarianceAdjustmentToGetAccessibleType(AggregateSymbol context, ArrayType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
// We are here because we have an array type with an inaccessible element type. If possible,
// we should create a new array type that has an accessible element type for which a
// conversion exists.
CType elementType = typeSrc.ElementType;
// Covariant array conversions exist for reference types only.
if (elementType.IsReferenceType)
{
CType destElement = GetBestAccessibleType(context, elementType);
typeDst = GetArray(destElement, typeSrc.Rank, typeSrc.IsSZArray);
Debug.Assert(CSemanticChecker.CheckTypeAccess(typeDst, context));
return true;
}
typeDst = null;
return false;
}
internal static bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck)
{
RuntimeBinder.EnsureLockIsTaken();
(Assembly, Assembly) key = (assemblyThatDefinesAttribute, assemblyToCheck);
if (!s_internalsVisibleToCache.TryGetValue(key, out bool result))
{
// Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery.
// If we don't have that (we're in low trust), then we are going to effectively turn off
// InternalsVisibleTo. The alternative is to crash when this happens.
try
{
AssemblyName assyName = assemblyToCheck.GetName();
foreach (Attribute attr in assemblyThatDefinesAttribute.GetCustomAttributes())
{
if (attr is InternalsVisibleToAttribute ivta &&
AssemblyName.ReferenceMatchesDefinition(new AssemblyName(ivta.AssemblyName), assyName))
{
result = true;
break;
}
}
}
catch (SecurityException)
{
result = false;
}
s_internalsVisibleToCache[key] = result;
}
return result;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class HighPriorityProcessor : IdleProcessor
{
private readonly IncrementalAnalyzerProcessor _processor;
private readonly ImmutableArray<IIncrementalAnalyzer> _analyzers;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
// whether this processor is running or not
private Task _running;
public HighPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
ImmutableArray<IIncrementalAnalyzer> analyzers,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, backOffTimeSpanInMs, shutdownToken)
{
_processor = processor;
_analyzers = analyzers;
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
Start();
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
// we only put workitem in high priority queue if there is a text change.
// this is to prevent things like opening a file, changing in other files keep enqueuing
// expensive high priority work.
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
// check whether given item is for active document, otherwise, nothing to do here
if (_processor._documentTracker == null ||
_processor._documentTracker.GetActiveDocument() != item.DocumentId)
{
return;
}
// we need to clone due to waiter
EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile")));
}
private void EnqueueActiveFileItem(WorkItem item)
{
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_ActiveFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator);
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _workItemQueue.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
// okay, there must be at least one item in the map
// see whether we have work item for the document
WorkItem workItem;
CancellationTokenSource documentCancellation;
Contract.ThrowIfFalse(GetNextWorkItem(out workItem, out documentCancellation));
var solution = _processor.CurrentSolution;
// okay now we have work to do
await ProcessDocumentAsync(solution, _analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation)
{
// GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail.
var documentId = _processor._documentTracker.GetActiveDocument();
if (documentId != null)
{
if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
{
return true;
}
}
return _workItemQueue.TryTakeAnyWork(
preferableProjectId: null,
dependencyGraph: _processor.DependencyGraph,
analyzerService: _processor.DiagnosticAnalyzerService,
workItem: out workItem,
source: out documentCancellation);
}
private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = solution.GetDocument(documentId);
if (document != null)
{
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
public void Shutdown()
{
_workItemQueue.Dispose();
}
}
}
}
}
}
| |
using System.Collections.Generic;
using bv.common.Core;
using eidss.model.Enums;
namespace eidss.model.Reports
{
public interface IReportFactory
{
void ResetLanguage();
#region Common Human Reports
[MenuReportCustomization]
void HumAggregateCase(AggregateReportParameters aggrParams);
[MenuReportCustomization]
void HumAggregateCaseSummary(AggregateSummaryReportParameters aggrParams);
[MenuReportCustomization]
void HumCaseInvestigation(long caseId, long epiId, long csId, long diagnosisId);
[MenuReportCustomization(Forbidden = new[] { CustomizationPackage.Tanzania})]
void HumUrgentyNotification(long caseId);
[MenuReportCustomization(CustomizationPackage.Tanzania)]
void HumUrgentyNotificationTanzania(long caseId);
[MenuReportCustomization(CustomizationPackage.DTRA)]
void HumUrgentyNotificationDTRA(long caseId);
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumDiagnosisToChangedDiagnosis", 400)]
[MenuReportCustomization(Forbidden = new[] {CustomizationPackage.Azerbaijan})]
void HumDiagnosisToChangedDiagnosis();
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumMonthlyMorbidityAndMortality", 390)]
[MenuReportCustomization(Forbidden = new[] {CustomizationPackage.Azerbaijan})]
void HumMonthlyMorbidityAndMortality();
#endregion
#region Common Veterinary reports
[MenuReportCustomization]
void VetAggregateCase(AggregateReportParameters aggrParams);
[MenuReportCustomization]
void VetAggregateCaseSummary(AggregateSummaryReportParameters aggrParams);
[MenuReportCustomization]
void VetAggregateCaseActions(AggregateActionsParameters aggrParams);
[MenuReportCustomization]
void VetAggregateCaseActionsSummary(AggregateActionsSummaryParameters aggrParams);
[MenuReportCustomization]
void VetAvianInvestigation(long caseId, long diagnosisId, bool includeMap);
[MenuReportCustomization]
void VetLivestockInvestigation(long caseId, long diagnosisId, bool includeMap);
[MenuReportCustomization]
void VetActiveSurveillanceSampleCollected(long id);
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetSamplesCount", 1310)]
[MenuReportCustomization(
Forbidden = new[]
{
CustomizationPackage.DTRA, CustomizationPackage.Georgia,
CustomizationPackage.Azerbaijan, CustomizationPackage.Thailand,
CustomizationPackage.Armenia
})]
void VetSamplesCount();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetSamplesReportBySampleType", 1320)]
[MenuReportCustomization(
Forbidden = new[]
{
CustomizationPackage.DTRA, CustomizationPackage.Georgia,
CustomizationPackage.Azerbaijan, CustomizationPackage.Thailand,
CustomizationPackage.Armenia
})]
void VetSamplesBySampleType();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetSamplesReportBySampleTypesWithinRegions", 1330)]
[MenuReportCustomization(
Forbidden = new[]
{
CustomizationPackage.DTRA, CustomizationPackage.Georgia,
CustomizationPackage.Azerbaijan, CustomizationPackage.Thailand,
CustomizationPackage.Armenia
})]
void VetSamplesBySampleTypesWithinRegions();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetYearlySituation", 1340)]
[MenuReportCustomization(Forbidden = new[] {CustomizationPackage.Azerbaijan, CustomizationPackage.Thailand})]
void VetYearlySituation();
[MenuReportDescription(ReportSubMenu.Vet, "ReportsActiveSurveillance", 1350)]
[MenuReportCustomization(Forbidden = new[] {CustomizationPackage.Azerbaijan, CustomizationPackage.Thailand})]
void VetActiveSurveillance();
#endregion
#region Common Syndromic Surviellance
[MenuReportDescription(ReportSubMenu.Aberration, "ReportsHumAberrationAnalysis", 60000, (int) MenuIconsSmall.HumanAberrationReport)]
[MenuReportCustomization(AbsentInWeb = true, Forbidden = new[] {CustomizationPackage.Azerbaijan})]
void HumAberrationAnalysis();
[MenuReportDescription(ReportSubMenu.Aberration, "ReportsVetAberrationAnalysis", 60001, (int) MenuIconsSmall.VetAberrationReport)]
[MenuReportCustomization(AbsentInWeb = true, Forbidden = new[] {CustomizationPackage.Thailand, CustomizationPackage.Azerbaijan})]
void VetAberrationAnalysis();
[MenuReportDescription(ReportSubMenu.Aberration, "ReportsSyndrAberrationAnalysis", 60002, (int) MenuIconsSmall.BssAberrationReport)]
[MenuReportCustomization(AbsentInWeb = true,
Forbidden = new[] {CustomizationPackage.Thailand, CustomizationPackage.Armenia, CustomizationPackage.Azerbaijan})]
void SyndrAberrationAnalysis();
[MenuReportDescription(ReportSubMenu.Aberration, "ReportsILISyndrAberrationAnalysis", 6000, (int) MenuIconsSmall.BssAggregateList)]
[MenuReportCustomization(AbsentInWeb = true,
Forbidden = new[] {CustomizationPackage.Thailand, CustomizationPackage.Armenia, CustomizationPackage.Azerbaijan})]
void ILISyndrAberrationAnalysis();
#endregion
#region Common Lab module reports
[MenuReportCustomization]
void LimSampleTransfer(long id);
[MenuReportCustomization]
void LimTestResult(long id, long csId, long typeId);
[MenuReportCustomization]
void LimTest(long id, bool isHuman);
[MenuReportCustomization]
void LimBatchTest(long id, long typeId);
[MenuReportCustomization]
void LimSample(long id);
[MenuReportCustomization]
void LimContainerContent(long? contId, long? freeserId);
[MenuReportCustomization]
void LimAccessionIn(long caseId);
[MenuReportCustomization]
void LimSampleDestruction(IEnumerable<long> sampleId);
#endregion
#region Other reports
[MenuReportCustomization]
void Outbreak(long id);
[MenuReportCustomization]
void VectorSurveillanceSessionSummary(long id);
[MenuReportDescription(ReportSubMenu.Admin, "ReportsAdmEventLog", 100)]
[MenuReportCustomization]
void AdmEventLog();
#endregion
#region Human GG reports
[MenuReportDescription(ReportSubMenu.Human, "ReportsJournal60BReportCard", 320)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void Hum60BJournal();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "ReportsHumInfectiousDiseaseMonthV4", 370,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumMonthInfectiousDiseaseV4();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "ReportsHumInfectiousDiseaseMonthV5", 343,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumMonthInfectiousDiseaseV5();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "ReportsHumInfectiousDiseaseMonthV6", 333,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumMonthInfectiousDiseaseV6();
[MenuReportDescription(ReportSubMenu.Human, "ReportsHumInfectiousDiseaseMonthV61", 333,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumMonthInfectiousDiseaseV61();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "HumInfectiousDiseaseIntermediateMonthV4", 380,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumIntermediateMonthInfectiousDiseaseV4();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "HumInfectiousDiseaseIntermediateMonthV5", 345,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumIntermediateMonthInfectiousDiseaseV5();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "HumInfectiousDiseaseIntermediateMonthV6", 335,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumIntermediateMonthInfectiousDiseaseV6();
[MenuReportDescription(ReportSubMenu.Human, "HumInfectiousDiseaseIntermediateMonthV61", 340,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase})]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumIntermediateMonthInfectiousDiseaseV61();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "ReportsHumInfectiousDiseaseYear", 350)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumAnnualInfectiousDisease();
[MenuReportDescription(ReportSubMenu.HumanGGOldRevision, "HumInfectiousDiseaseIntermediateYear", 360)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumIntermediateAnnualInfectiousDisease();
#endregion
#region Lab GG reports
[MenuReportDescription(ReportSubMenu.Lab, "VetLaboratoryResearchResult", 440)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void VetLaboratoryResearchResult();
[MenuReportDescription(ReportSubMenu.Lab, "ReportsHumSerologyResearchCard", 410)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
[ForbiddenDataGroup(PersonalDataGroup.Human_PersonName, PersonalDataGroup.Human_PersonAge)]
void HumSerologyResearchCard();
[MenuReportDescription(ReportSubMenu.Lab, "ReportsHumMicrobiologyResearchCard", 420)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
[ForbiddenDataGroup(PersonalDataGroup.Human_PersonName, PersonalDataGroup.Human_PersonAge)]
void HumMicrobiologyResearchCard();
[MenuReportDescription(ReportSubMenu.Lab, "HumAntibioticResistanceCard", 430)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumAntibioticResistanceCard();
[MenuReportDescription(ReportSubMenu.Lab, "HumAntibioticResistanceCardLma", 450)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void HumAntibioticResistanceCardLma();
#endregion
#region Vet GG reports
[MenuReportDescription(ReportSubMenu.Vet, "ReportsVetRabiesBulletinEurope", 1335)]
[MenuReportCustomization(CustomizationPackage.Georgia)]
void VetRabiesBulletinEurope();
#endregion
#region Human AZ reports
[MenuReportDescription(ReportSubMenu.Human, "HumFormN1A3", 260)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumFormN1A3();
[MenuReportDescription(ReportSubMenu.Human, "HumFormN1A4", 270)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumFormN1A4();
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
[MenuReportDescription(ReportSubMenu.Human, "HumDataQualityIndicators", 280,
PermissionObjects = new[] {EIDSSPermissionObject.CanSignReport},
PermissionActions = new[] {PermissionHelper.Execute})]
void HumDataQualityIndicators();
[MenuReportDescription(ReportSubMenu.Human, "HumComparativeReport", 320)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumComparativeAZReport();
[MenuReportDescription(ReportSubMenu.Human, "HumExternalComparativeReport", 330)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumExternalComparativeReport();
[MenuReportDescription(ReportSubMenu.Human, "HumSummaryByRayonDiagnosisAgeGroups", 340)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumSummaryByRayonDiagnosisAgeGroups();
[MenuReportDescription(ReportSubMenu.Human, "HumMainIndicatorsOfAFPSurveillance", 360)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumMainIndicatorsOfAFPSurveillance();
[MenuReportDescription(ReportSubMenu.Human, "HumAdditionalIndicatorsOfAFPSurveillance", 370)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumAdditionalIndicatorsOfAFPSurveillance();
[MenuReportDescription(ReportSubMenu.Human, "HumWhoMeaslesRubellaReport", 380)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumWhoMeaslesRubellaReport();
#endregion
#region Lab AZ reports
[MenuReportDescription(ReportSubMenu.Lab, "AssignmentLabDiagnosticAZ", 360,
PermissionObjects = new[] {EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Select})]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void AssignmentLabDiagnosticAZ();
[MenuReportDescription(ReportSubMenu.Lab, "LabTestingResultsAZ", 370)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void LabTestingResultsAZ();
#endregion
#region Veterinary AZ reports
[MenuReportDescription(ReportSubMenu.Vet, "VeterinaryFormVet1", 440, PermissionObjects = new []{EIDSSPermissionObject.VetCase})]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void VeterinaryFormVet1();
[MenuReportDescription(ReportSubMenu.Vet, "VeterinaryFormVet1A", 450,
PermissionObjects =
new[]
{
EIDSSPermissionObject.VetCase, EIDSSPermissionObject.AccessToVetAggregateAction,
EIDSSPermissionObject.MonitoringSession
})]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void VeterinaryFormVet1A();
[MenuReportDescription(ReportSubMenu.Vet, "VeterinarySummaryAZ", 460,
PermissionObjects =
new[]
{
EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase,
EIDSSPermissionObject.AccessToVetAggregateAction
})]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void VeterinarySummaryAZ();
[MenuReportDescription(ReportSubMenu.Vet, "VeterinaryLaboratoriesAZ", 470)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void VeterinaryLaboratoriesAZ();
[MenuReportDescription(ReportSubMenu.Vet, "VeterinaryCasesReport", 480)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void VeterinaryCasesReportAZ();
#endregion
#region Zoonotic AZ reports
[MenuReportDescription(ReportSubMenu.Zoonotic, "ZoonoticComparativeAZ", 360)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void ZoonoticComparativeAZ();
#endregion
#region Simplified AZ reports
[MenuReportDescription(ReportSubMenu.Simplified, "HumDataQualityIndicatorsRayons", 290)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumDataQualityIndicatorsRayons();
[MenuReportDescription(ReportSubMenu.Simplified, "HumBorderRayonsComparativeReport", 300,
PermissionObjects = new[] {EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Insert})]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumBorderRayonsComparativeReport();
[MenuReportDescription(ReportSubMenu.Simplified, "HumComparativeReportOfTwoYears", 310,
PermissionObjects = new[] {EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Insert})]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumComparativeReportOfTwoYears();
[MenuReportDescription(ReportSubMenu.Simplified, "HumTuberculosisCasesTested", 350,
PermissionObjects = new[] {EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Insert})]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void HumTuberculosisCasesTested();
// note: dublicate of ZoonoticComparativeAZ in menu "Simplified"
[MenuReportDescription(ReportSubMenu.Simplified, "ZoonoticComparativeAZ", 360)]
[MenuReportCustomization(CustomizationPackage.Azerbaijan)]
void SimplifiedComparativeAZ();
#endregion
#region TH reports
[MenuReportDescription(ReportSubMenu.Human, "HumComparativeReportOfSeveralYearsTH", 100,
PermissionObjects = new[] {EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Insert})]
[MenuReportCustomization(CustomizationPackage.Thailand)]
void HumComparativeReportOfSeveralYearsTH();
[MenuReportDescription(ReportSubMenu.Human, "HumReportedCasesDeathsByProvinceMonthTH", 200,
PermissionObjects = new[] {EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Insert})]
[MenuReportCustomization(CustomizationPackage.Thailand)]
void HumReportedCasesDeathsByProvinceMonthTH();
[MenuReportDescription(ReportSubMenu.Human, "HumNumberOfCasesDeathsMorbidityMortalityTH", 300,
PermissionObjects = new[] {EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Insert})]
[MenuReportCustomization(CustomizationPackage.Thailand)]
void HumNumberOfCasesDeathsMorbidityMortalityTH();
#endregion
#region ARM reports
[MenuReportDescription(ReportSubMenu.Human, "HumFormN85", 500,
PermissionObjects = new[] {EIDSSPermissionObject.AccessToHumanAggregateCase, EIDSSPermissionObject.HumanCase},
PermissionActions = new[] {PermissionHelper.Insert})]
[MenuReportCustomization(CustomizationPackage.Armenia)]
void HumFormN85();
#endregion
#region IQ reports
[MenuReportDescription(ReportSubMenu.Human, "WeeklySituationDiseasesByDistricts", 610)]
[MenuReportCustomization(CustomizationPackage.Iraq)]
void WeeklySituationDiseasesByDistricts();
[MenuReportDescription(ReportSubMenu.Human, "MonthlySituationDiseasesByDistricts", 620)]
[MenuReportCustomization(CustomizationPackage.Iraq)]
void MonthlySituationDiseasesByDistricts();
[MenuReportDescription(ReportSubMenu.Human, "WeeklySituationDiseasesByAgeGroupAndSex", 630)]
[MenuReportCustomization(CustomizationPackage.Iraq)]
void WeeklySituationDiseasesByAgeGroupAndSex();
[MenuReportDescription(ReportSubMenu.Human, "MonthlySituationDiseasesByAgeGroupAndSex", 640)]
[MenuReportCustomization(CustomizationPackage.Iraq)]
void MonthlySituationDiseasesByAgeGroupAndSex();
[MenuReportDescription(ReportSubMenu.Human, "HumComparativeIQReport", 650)]
[MenuReportCustomization(CustomizationPackage.Iraq)]
void HumComparativeIQReport();
#endregion
#region Human KZ reports
[MenuReportDescription(ReportSubMenu.Human, "HumInfectiousParasiticKZ", 500)]
[MenuReportCustomization(CustomizationPackage.KazakhstanMoH)]
void HumInfectiousParasiticKZ();
#endregion
#region Veterinary KZ reports
[MenuReportDescription(ReportSubMenu.Vet, "VetCountryPlannedDiagnosticTestsReport", 450)]
[MenuReportCustomization(CustomizationPackage.KazakhstanMoA)]
void VetCountryPlannedDiagnosticTests();
[MenuReportDescription(ReportSubMenu.Vet, "VetRegionPlannedDiagnosticTestsReport", 460)]
[MenuReportCustomization(CustomizationPackage.KazakhstanMoA)]
void VetOblastPlannedDiagnosticTests();
[MenuReportDescription(ReportSubMenu.Vet, "VetCountryPreventiveMeasuresReport", 470)]
[MenuReportCustomization(CustomizationPackage.KazakhstanMoA)]
void VetCountryPreventiveMeasures();
[MenuReportDescription(ReportSubMenu.Vet, "VetRegionPreventiveMeasuresReport", 480)]
[MenuReportCustomization(CustomizationPackage.KazakhstanMoA)]
void VetOblastPreventiveMeasures();
[MenuReportDescription(ReportSubMenu.Vet, "VetCountryProphilacticMeasuresReport", 490)]
[MenuReportCustomization(CustomizationPackage.KazakhstanMoA)]
void VetCountrySanitaryMeasures();
[MenuReportDescription(ReportSubMenu.Vet, "VetRegionProphilacticMeasuresReport", 500)]
[MenuReportCustomization(CustomizationPackage.KazakhstanMoA)]
void VetOblastSanitaryMeasures();
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace SmartFighter {
public static class GameMode {
public const int Story = 2;
public const int Arcade = 3;
public const int Versus = 4;
public const int Casual = 5;
public const int BattleLounge = 6;
public const int Ranked = 7;
public const int Training = 8;
public const int CFN = 9;
public const int BattleSettings = 10;
public const int Shop = 11;
public const int Options = 12;
public const int Challenge = 13;
public const int Log = 14;
public const int Informations = 15;
public const int Gallery = 17;
}
public static class VersusMode {
public const int PvP = 0;
public const int PvAI = 1;
public const int AIvP = 2;
}
public static class MatchResult {
public const int Player1 = 0;
public const int Player2 = 1;
public const int Draw = -1;
public const int Unknown = -100;
}
public static class RoundResult {
public const int Unknown = 0;
public const int Loss = 1;
public const int Win = 2;
public const int CrticalArt = 3;
public const int EX = 4;
public const int Chip = 5;
public const int Perfect = 6;
public const int TimeOut = 7;
public const int DoubleKO = 8;
}
public delegate void ScoresUpdatedHandler();
public class GameState {
private class Game {
public string id;
public int roundCount;
public int roundTimer;
public string player1;
public string player2;
public int result = MatchResult.Unknown;
public Game(string id, string player1, string player2, int rounds, int timer) {
this.id = id;
this.player1 = player1;
this.player2 = player2;
roundCount = rounds;
roundTimer = timer;
}
}
public int gameMode = -1;
public int versusMode = -1;
public int roundCount = 0;
public int roundTimer = 0;
public string player1Id;
public string player2Id;
public int player1Score = 0;
public int player2Score = 0;
public string player1Character = null;
public string player2Character = null;
public event ScoresUpdatedHandler ScoresUpdatedEvent;
private Game currentGame;
private bool gameStarted;
public bool isInVersus() {
return gameMode == GameMode.Versus && versusMode == VersusMode.PvP;
}
public bool isGameStarted() {
return gameStarted;
}
public void startGame() {
if (isInVersus()) {
currentGame = new Game(Guid.NewGuid().ToString("N"), player1Id, player2Id, roundCount, roundTimer);
gameStarted = true;
}
}
public void setCharacters(string player1, string player2) {
var regex = new Regex("[A-Z0-9]{3}");
if (isInVersus() && regex.IsMatch(player1) && regex.IsMatch(player2)) {
player1Character = player1;
player2Character = player2;
} else {
player1Character = null;
player2Character = null;
}
}
public void setMatchResults(int result) {
if (isGameStarted()) {
if (currentGame.player1 != null && currentGame.player2 != null) {
currentGame.result = result;
Logger.Instance.log("SET MATCH {0} --> {1} ({2} vs. {3})", currentGame.id, result, currentGame.player1, currentGame.player2);
if (result == MatchResult.Player1) {
player1Score++;
}
if (result == MatchResult.Player2) {
player2Score++;
}
ScoresUpdatedEvent();
ApiQueue.registerGame(currentGame.id, currentGame.player1, currentGame.player2, result, DateTime.UtcNow, player1Character, player2Character);
} else {
currentGame = null;
}
gameStarted = false;
}
}
public void setRoundResults(int[] player1, int[] player2) {
if (player1.Length != player2.Length) {
return;
}
if (isInVersus() && currentGame != null) {
if (currentGame.result == MatchResult.Unknown) {
return;
}
List<Api.Round> rounds = new List<Api.Round>();
Logger.Instance.log("*** Match {0} ***", currentGame.id);
Logger.Instance.log("- Winner: {0}", getWinnerString(currentGame.result));
Logger.Instance.log("- Rounds:");
int score1 = 0;
int score2 = 0;
int scoreMax = roundCount / 2 + 1;
for (int index = 0; index < player1.Length; index++) {
int status1 = player1[index];
int status2 = player2[index];
if (status1 != RoundResult.Unknown && status1 != RoundResult.Loss) {
score1++;
}
if (status2 != RoundResult.Unknown && status2 != RoundResult.Loss) {
score2++;
}
Logger.Instance.log(" * {0} | {1}", getRoundCode(status1), getRoundCode(status2));
rounds.Add(new Api.Round(getRoundResult(status1, status2), status1, status2));
if (score1 >= scoreMax || score2 >= scoreMax) {
break;
}
}
ApiQueue.registerRounds(currentGame.id, rounds.ToArray());
currentGame = null;
}
}
private int getRoundResult(int player1, int player2) {
if (player1 == RoundResult.DoubleKO || (player1 == RoundResult.TimeOut && player2 == RoundResult.TimeOut)) {
return MatchResult.Draw;
}
if (player1 == RoundResult.Loss) {
return MatchResult.Player2;
}
return MatchResult.Player1;
}
private string getWinnerString(int result) {
if (result == MatchResult.Player1) {
return "Player 1";
}
if (result == MatchResult.Player2) {
return "Player 2";
}
if (result == MatchResult.Draw) {
return "Draw";
}
return "Unknonw";
}
public string getRoundCode(int result) {
if (result == RoundResult.Loss) {
return " ";
}
if (result == RoundResult.Win) {
return " V";
}
if (result == RoundResult.CrticalArt) {
return "CA";
}
if (result == RoundResult.EX) {
return "EX";
}
if (result == RoundResult.Chip) {
return " C";
}
if (result == RoundResult.Perfect) {
return " P";
}
if (result == RoundResult.TimeOut) {
return " T";
}
if (result == RoundResult.DoubleKO) {
return " D";
}
return " ?";
}
public void resetScores() {
player1Score = 0;
player2Score = 0;
}
}
}
| |
// Copyright 2022 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 gcsv = Google.Cloud.Speech.V1;
using sys = System;
namespace Google.Cloud.Speech.V1
{
/// <summary>Resource name for the <c>CustomClass</c> resource.</summary>
public sealed partial class CustomClassName : gax::IResourceName, sys::IEquatable<CustomClassName>
{
/// <summary>The possible contents of <see cref="CustomClassName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/customClasses/{custom_class}</c>
/// .
/// </summary>
ProjectLocationCustomClass = 1,
}
private static gax::PathTemplate s_projectLocationCustomClass = new gax::PathTemplate("projects/{project}/locations/{location}/customClasses/{custom_class}");
/// <summary>Creates a <see cref="CustomClassName"/> 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="CustomClassName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomClassName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomClassName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomClassName"/> with the pattern
/// <c>projects/{project}/locations/{location}/customClasses/{custom_class}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customClassId">The <c>CustomClass</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CustomClassName"/> constructed from the provided ids.</returns>
public static CustomClassName FromProjectLocationCustomClass(string projectId, string locationId, string customClassId) =>
new CustomClassName(ResourceNameType.ProjectLocationCustomClass, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), customClassId: gax::GaxPreconditions.CheckNotNullOrEmpty(customClassId, nameof(customClassId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomClassName"/> with pattern
/// <c>projects/{project}/locations/{location}/customClasses/{custom_class}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customClassId">The <c>CustomClass</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomClassName"/> with pattern
/// <c>projects/{project}/locations/{location}/customClasses/{custom_class}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string customClassId) =>
FormatProjectLocationCustomClass(projectId, locationId, customClassId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomClassName"/> with pattern
/// <c>projects/{project}/locations/{location}/customClasses/{custom_class}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customClassId">The <c>CustomClass</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomClassName"/> with pattern
/// <c>projects/{project}/locations/{location}/customClasses/{custom_class}</c>.
/// </returns>
public static string FormatProjectLocationCustomClass(string projectId, string locationId, string customClassId) =>
s_projectLocationCustomClass.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customClassId, nameof(customClassId)));
/// <summary>Parses the given resource name string into a new <see cref="CustomClassName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/customClasses/{custom_class}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customClassName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomClassName"/> if successful.</returns>
public static CustomClassName Parse(string customClassName) => Parse(customClassName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomClassName"/> 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>projects/{project}/locations/{location}/customClasses/{custom_class}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customClassName">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="CustomClassName"/> if successful.</returns>
public static CustomClassName Parse(string customClassName, bool allowUnparsed) =>
TryParse(customClassName, allowUnparsed, out CustomClassName 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="CustomClassName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/customClasses/{custom_class}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customClassName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomClassName"/>, 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 customClassName, out CustomClassName result) =>
TryParse(customClassName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomClassName"/> 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>projects/{project}/locations/{location}/customClasses/{custom_class}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customClassName">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="CustomClassName"/>, 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 customClassName, bool allowUnparsed, out CustomClassName result)
{
gax::GaxPreconditions.CheckNotNull(customClassName, nameof(customClassName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationCustomClass.TryParseName(customClassName, out resourceName))
{
result = FromProjectLocationCustomClass(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customClassName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomClassName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customClassId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomClassId = customClassId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomClassName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/customClasses/{custom_class}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customClassId">The <c>CustomClass</c> ID. Must not be <c>null</c> or empty.</param>
public CustomClassName(string projectId, string locationId, string customClassId) : this(ResourceNameType.ProjectLocationCustomClass, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), customClassId: gax::GaxPreconditions.CheckNotNullOrEmpty(customClassId, nameof(customClassId)))
{
}
/// <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>CustomClass</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomClassId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { 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.ProjectLocationCustomClass: return s_projectLocationCustomClass.Expand(ProjectId, LocationId, CustomClassId);
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 CustomClassName);
/// <inheritdoc/>
public bool Equals(CustomClassName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomClassName a, CustomClassName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomClassName a, CustomClassName b) => !(a == b);
}
/// <summary>Resource name for the <c>PhraseSet</c> resource.</summary>
public sealed partial class PhraseSetName : gax::IResourceName, sys::IEquatable<PhraseSetName>
{
/// <summary>The possible contents of <see cref="PhraseSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c>.
/// </summary>
ProjectLocationPhraseSet = 1,
}
private static gax::PathTemplate s_projectLocationPhraseSet = new gax::PathTemplate("projects/{project}/locations/{location}/phraseSets/{phrase_set}");
/// <summary>Creates a <see cref="PhraseSetName"/> 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="PhraseSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static PhraseSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PhraseSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PhraseSetName"/> with the pattern
/// <c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="phraseSetId">The <c>PhraseSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PhraseSetName"/> constructed from the provided ids.</returns>
public static PhraseSetName FromProjectLocationPhraseSet(string projectId, string locationId, string phraseSetId) =>
new PhraseSetName(ResourceNameType.ProjectLocationPhraseSet, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), phraseSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(phraseSetId, nameof(phraseSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PhraseSetName"/> with pattern
/// <c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="phraseSetId">The <c>PhraseSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PhraseSetName"/> with pattern
/// <c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string phraseSetId) =>
FormatProjectLocationPhraseSet(projectId, locationId, phraseSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PhraseSetName"/> with pattern
/// <c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="phraseSetId">The <c>PhraseSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PhraseSetName"/> with pattern
/// <c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c>.
/// </returns>
public static string FormatProjectLocationPhraseSet(string projectId, string locationId, string phraseSetId) =>
s_projectLocationPhraseSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(phraseSetId, nameof(phraseSetId)));
/// <summary>Parses the given resource name string into a new <see cref="PhraseSetName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="phraseSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PhraseSetName"/> if successful.</returns>
public static PhraseSetName Parse(string phraseSetName) => Parse(phraseSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PhraseSetName"/> 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>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="phraseSetName">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="PhraseSetName"/> if successful.</returns>
public static PhraseSetName Parse(string phraseSetName, bool allowUnparsed) =>
TryParse(phraseSetName, allowUnparsed, out PhraseSetName 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="PhraseSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="phraseSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PhraseSetName"/>, 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 phraseSetName, out PhraseSetName result) => TryParse(phraseSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PhraseSetName"/> 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>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="phraseSetName">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="PhraseSetName"/>, 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 phraseSetName, bool allowUnparsed, out PhraseSetName result)
{
gax::GaxPreconditions.CheckNotNull(phraseSetName, nameof(phraseSetName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationPhraseSet.TryParseName(phraseSetName, out resourceName))
{
result = FromProjectLocationPhraseSet(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(phraseSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PhraseSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string phraseSetId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
PhraseSetId = phraseSetId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PhraseSetName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/phraseSets/{phrase_set}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="phraseSetId">The <c>PhraseSet</c> ID. Must not be <c>null</c> or empty.</param>
public PhraseSetName(string projectId, string locationId, string phraseSetId) : this(ResourceNameType.ProjectLocationPhraseSet, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), phraseSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(phraseSetId, nameof(phraseSetId)))
{
}
/// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>PhraseSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string PhraseSetId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { 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.ProjectLocationPhraseSet: return s_projectLocationPhraseSet.Expand(ProjectId, LocationId, PhraseSetId);
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 PhraseSetName);
/// <inheritdoc/>
public bool Equals(PhraseSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PhraseSetName a, PhraseSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PhraseSetName a, PhraseSetName b) => !(a == b);
}
public partial class CustomClass
{
/// <summary>
/// <see cref="gcsv::CustomClassName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::CustomClassName CustomClassName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::CustomClassName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class PhraseSet
{
/// <summary>
/// <see cref="gcsv::PhraseSetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::PhraseSetName PhraseSetName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::PhraseSetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class SpeechAdaptation
{
/// <summary>
/// <see cref="PhraseSetName"/>-typed view over the <see cref="PhraseSetReferences"/> resource name property.
/// </summary>
public gax::ResourceNameList<PhraseSetName> PhraseSetReferencesAsPhraseSetNames
{
get => new gax::ResourceNameList<PhraseSetName>(PhraseSetReferences, s => string.IsNullOrEmpty(s) ? null : PhraseSetName.Parse(s, allowUnparsed: true));
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using EspaceClient.FrontOffice.Infrastructure.Services.Captcha;
namespace EspaceClient.FrontOffice.Infrastructure.Services.Implementations.Captcha
{
/// <summary>
/// Summary description for CaptchaImage.
/// </summary>
public class CaptchaImage : IDisposable, ICaptchaImage
{
// Internal properties.
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;
// For generating random numbers.
private Random random = new Random();
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width and height.
// ====================================================================
public Bitmap GenerateImage(string s, int width, int height)
{
return GenerateImage(s, width, height, null);
}
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width, height and font family.
// ====================================================================
public Bitmap GenerateImage(string s, int width, int height, string familyName)
{
this.text = s;
this.SetDimensions(width, height);
if (familyName != null)
this.SetFamilyName(familyName);
this.GenerateImage();
return this.image;
}
//
// Returns a string of six random digits.
//
public string GenerateRandomCode(long lenght = 6)
{
string s = "";
for (long i = 0; i < lenght; i++)
s = String.Concat(s, this.random.Next(10).ToString());
return s;
}
// ====================================================================
// This member overrides Object.Finalize.
// ====================================================================
~CaptchaImage()
{
Dispose(false);
}
// ====================================================================
// Releases all resources used by this object.
// ====================================================================
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
// ====================================================================
// Custom Dispose method to clean up unmanaged resources.
// ====================================================================
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Dispose of the bitmap.
if (this.image != null)
this.image.Dispose();
}
}
// ====================================================================
// Sets the image width and height.
// ====================================================================
private void SetDimensions(int width, int height)
{
// Check the width and height.
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}
// ====================================================================
// Sets the font used for the image text.
// ====================================================================
private void SetFamilyName(string familyName)
{
// If the named font is not installed, default to a system font.
try
{
Font font = new Font(this.familyName, 12F);
this.familyName = familyName;
font.Dispose();
}
catch
{
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
}
}
// ====================================================================
// Creates the bitmap image.
// ====================================================================
private void GenerateImage()
{
// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);
// Create a graphics object for drawing.
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
// Fill in the background.
HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
g.FillRectangle(hatchBrush, rect);
// Set up the text font.
SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.
do
{
fontSize--;
font = new Font(this.familyName, fontSize, FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width > rect.Width);
// Set up the text format.
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
// Create a path using the text and warp it randomly.
GraphicsPath path = new GraphicsPath();
path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);
float v = 4F;
PointF[] points =
{
new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
// Draw the text.
hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
g.FillPath(hatchBrush, path);
// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}
// Clean up.
font.Dispose();
hatchBrush.Dispose();
g.Dispose();
// Set the image.
this.image = bitmap;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.IO.FileSystem.Tests
{
public class DirectoryInfo_CreateSubDirectory : FileSystemTest
{
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFileName();
File.Create(Path.Combine(TestDirectory, path)).Dispose();
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
string path = GetTestFileName();
DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path));
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName);
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFileName();
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName);
}
[Fact]
public void Conflicting_Parent_Directory()
{
string path = Path.Combine(TestDirectory, GetTestFileName(), "c");
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void ValidPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOServices.AddTrailingSlashIfNeeded(component);
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithoutTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = component;
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test");
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.GetRandomFileName() + "!@#$%^&";
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
[ActiveIssue(2402)]
public void WindowsWhiteSpaceAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixWhiteSpaceAsPath_Allowed()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
[ActiveIssue(2403)]
public void WindowsNonSignificantTrailingWhiteSpace()
{
// Windows will remove all nonsignificant whitespace in a path
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path + component);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(Path.Combine(TestDirectory, path), IOServices.RemoveTrailingSlash(result.FullName));
});
//{ // Directory.CreateDirectory curtails trailing tab and newline characters
// string filePath = IOServices.RemoveTrailingSlash(GetTestFilePath());
// DirectoryInfo result = Directory.CreateDirectory(filePath + "\n");
// Assert.Equal(filePath, IOServices.RemoveTrailingSlash(result.FullName));
//}
//{ // DirectoryInfo.CreateSubdirectory throws an ArgumentException when there are newline or tab characters anywhere in a file name
// string fileName = IOServices.RemoveTrailingSlash(GetTestFileName());
// DirectoryInfo parentDir = new DirectoryInfo(TestDirectory);
// Assert.Throws<ArgumentException>(() => parentDir.CreateSubdirectory(fileName + "\n"));
//}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixNonSignificantTrailingWhiteSpace()
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.Name) + component;
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathSubdirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(@"\\?\" + GetTestFilePath());
Assert.True(testDir.Exists);
DirectoryInfo subDir = testDir.CreateSubdirectory("Foo");
Assert.True(subDir.Exists);
Assert.StartsWith(@"\\?\", subDir.FullName);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//"));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Concurrency;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Configuration;
using RunState = Orleans.Configuration.StreamLifecycleOptions.RunState;
namespace Orleans.Streams
{
internal class PersistentStreamPullingManager : SystemTarget, IPersistentStreamPullingManager, IStreamQueueBalanceListener
{
private static readonly TimeSpan QUEUES_PRINT_PERIOD = TimeSpan.FromMinutes(5);
private readonly Dictionary<QueueId, PersistentStreamPullingAgent> queuesToAgentsMap;
private readonly string streamProviderName;
private readonly IStreamProviderRuntime providerRuntime;
private readonly IStreamPubSub pubSub;
private readonly StreamPullingAgentOptions options;
private readonly AsyncSerialExecutor nonReentrancyGuarantor; // for non-reentrant execution of queue change notifications.
private readonly ILogger logger;
private readonly ILoggerFactory loggerFactory;
private int latestRingNotificationSequenceNumber;
private int latestCommandNumber;
private IQueueAdapter queueAdapter;
private readonly IQueueAdapterCache queueAdapterCache;
private IStreamQueueBalancer queueBalancer;
private readonly IQueueAdapterFactory adapterFactory;
private RunState managerState;
private IDisposable queuePrintTimer;
private int NumberRunningAgents { get { return queuesToAgentsMap.Count; } }
internal PersistentStreamPullingManager(
GrainId id,
string strProviderName,
IStreamProviderRuntime runtime,
IStreamPubSub streamPubSub,
IQueueAdapterFactory adapterFactory,
IStreamQueueBalancer streamQueueBalancer,
StreamPullingAgentOptions options,
ILoggerFactory loggerFactory)
: base(id, runtime.ExecutingSiloAddress, loggerFactory)
{
if (string.IsNullOrWhiteSpace(strProviderName))
{
throw new ArgumentNullException("strProviderName");
}
if (runtime == null)
{
throw new ArgumentNullException("runtime", "IStreamProviderRuntime runtime reference should not be null");
}
if (streamPubSub == null)
{
throw new ArgumentNullException("streamPubSub", "StreamPubSub reference should not be null");
}
if (streamQueueBalancer == null)
{
throw new ArgumentNullException("streamQueueBalancer", "IStreamQueueBalancer streamQueueBalancer reference should not be null");
}
queuesToAgentsMap = new Dictionary<QueueId, PersistentStreamPullingAgent>();
streamProviderName = strProviderName;
providerRuntime = runtime;
pubSub = streamPubSub;
this.options = options;
nonReentrancyGuarantor = new AsyncSerialExecutor();
latestRingNotificationSequenceNumber = 0;
latestCommandNumber = 0;
queueBalancer = streamQueueBalancer;
this.adapterFactory = adapterFactory;
queueAdapterCache = adapterFactory.GetQueueAdapterCache();
logger = loggerFactory.CreateLogger($"{GetType().FullName}-{streamProviderName}");
Log(ErrorCode.PersistentStreamPullingManager_01, "Created {0} for Stream Provider {1}.", GetType().Name, streamProviderName);
this.loggerFactory = loggerFactory;
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_PULLING_AGENTS, strProviderName), () => queuesToAgentsMap.Count);
}
public async Task Initialize(Immutable<IQueueAdapter> qAdapter)
{
if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
Log(ErrorCode.PersistentStreamPullingManager_02, "Init.");
// Remove cast once we cleanup
queueAdapter = qAdapter.Value;
await this.queueBalancer.Initialize(this.adapterFactory.GetStreamQueueMapper());
queueBalancer.SubscribeToQueueDistributionChangeEvents(this);
List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList();
Log(ErrorCode.PersistentStreamPullingManager_03, String.Format("Initialize: I am now responsible for {0} queues: {1}.", myQueues.Count, PrintQueues(myQueues)));
queuePrintTimer = this.RegisterTimer(AsyncTimerCallback, null, QUEUES_PRINT_PERIOD, QUEUES_PRINT_PERIOD);
managerState = RunState.Initialized;
}
public async Task Stop()
{
await StopAgents();
if (queuePrintTimer != null)
{
queuePrintTimer.Dispose();
this.queuePrintTimer = null;
}
(this.queueBalancer as IDisposable)?.Dispose();
this.queueBalancer = null;
}
public async Task StartAgents()
{
managerState = RunState.AgentsStarted;
List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList();
Log(ErrorCode.PersistentStreamPullingManager_Starting, "Starting agents for {0} queues: {1}", myQueues.Count, PrintQueues(myQueues));
await AddNewQueues(myQueues, true);
Log(ErrorCode.PersistentStreamPullingManager_Started, "Started agents.");
}
public async Task StopAgents()
{
managerState = RunState.AgentsStopped;
List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.ToList();
Log(ErrorCode.PersistentStreamPullingManager_Stopping, "Stopping agents for {0} queues: {1}", queuesToRemove.Count, PrintQueues(queuesToRemove));
await RemoveQueues(queuesToRemove);
Log(ErrorCode.PersistentStreamPullingManager_Stopped, "Stopped agents.");
}
#region Management of queues
/// <summary>
/// Actions to take when the queue distribution changes due to a failure or a join.
/// Since this pulling manager is system target and queue distribution change notifications
/// are delivered to it as grain method calls, notifications are not reentrant. To simplify
/// notification handling we execute them serially, in a non-reentrant way. We also supress
/// and don't execute an older notification if a newer one was already delivered.
/// </summary>
public Task QueueDistributionChangeNotification()
{
return this.ScheduleTask(() => this.HandleQueueDistributionChangeNotification());
}
public Task HandleQueueDistributionChangeNotification()
{
latestRingNotificationSequenceNumber++;
int notificationSeqNumber = latestRingNotificationSequenceNumber;
Log(ErrorCode.PersistentStreamPullingManager_04,
"Got QueueChangeNotification number {0} from the queue balancer. managerState = {1}", notificationSeqNumber, managerState);
if (managerState == RunState.AgentsStopped)
{
return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them.
}
return nonReentrancyGuarantor.AddNext(() =>
{
// skip execution of an older/previous notification since already got a newer range update notification.
if (notificationSeqNumber < latestRingNotificationSequenceNumber)
{
Log(ErrorCode.PersistentStreamPullingManager_05,
"Skipping execution of QueueChangeNotification number {0} from the queue allocator since already received a later notification " +
"(already have notification number {1}).",
notificationSeqNumber, latestRingNotificationSequenceNumber);
return Task.CompletedTask;
}
if (managerState == RunState.AgentsStopped)
{
return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them.
}
return QueueDistributionChangeNotification(notificationSeqNumber);
});
}
private async Task QueueDistributionChangeNotification(int notificationSeqNumber)
{
HashSet<QueueId> currentQueues = queueBalancer.GetMyQueues().ToSet();
Log(ErrorCode.PersistentStreamPullingManager_06,
"Executing QueueChangeNotification number {0}. Queue balancer says I should now own {1} queues: {2}", notificationSeqNumber, currentQueues.Count, PrintQueues(currentQueues));
try
{
Task t1 = AddNewQueues(currentQueues, false);
List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.Where(queueId => !currentQueues.Contains(queueId)).ToList();
Task t2 = RemoveQueues(queuesToRemove);
await Task.WhenAll(t1, t2);
}
finally
{
Log(ErrorCode.PersistentStreamPullingManager_16,
"Done Executing QueueChangeNotification number {0}. I now own {1} queues: {2}", notificationSeqNumber, NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys));
}
}
/// <summary>
/// Take responsibility for a set of new queues that were assigned to me via a new range.
/// We first create one pulling agent for every new queue and store them in our internal data structure, then try to initialize the agents.
/// ERROR HANDLING:
/// The responsibility to handle initialization and shutdown failures is inside the Agents code.
/// The manager will call Initialize once and log an error. It will not call initialize again and will assume initialization has succeeded.
/// Same applies to shutdown.
/// </summary>
/// <param name="myQueues"></param>
/// <param name="failOnInit"></param>
/// <returns></returns>
private async Task AddNewQueues(IEnumerable<QueueId> myQueues, bool failOnInit)
{
// Create agents for queues in range that we don't yet have.
// First create them and store in local queuesToAgentsMap.
// Only after that Initialize them all.
var agents = new List<PersistentStreamPullingAgent>();
foreach (var queueId in myQueues.Where(queueId => !queuesToAgentsMap.ContainsKey(queueId)))
{
try
{
var agentId = GrainId.NewSystemTargetGrainIdByTypeCode(Constants.PULLING_AGENT_SYSTEM_TARGET_TYPE_CODE);
var agent = new PersistentStreamPullingAgent(agentId, streamProviderName, providerRuntime, this.loggerFactory, pubSub, queueId, this.options);
providerRuntime.RegisterSystemTarget(agent);
queuesToAgentsMap.Add(queueId, agent);
agents.Add(agent);
}
catch (Exception exc)
{
logger.Error(ErrorCode.PersistentStreamPullingManager_07, "Exception while creating PersistentStreamPullingAgent.", exc);
// What should we do? This error is not recoverable and considered a bug. But we don't want to bring the silo down.
// If this is when silo is starting and agent is initializing, fail the silo startup. Otherwise, just swallow to limit impact on other receivers.
if (failOnInit) throw;
}
}
try
{
var initTasks = new List<Task>();
foreach (var agent in agents)
{
initTasks.Add(InitAgent(agent));
}
await Task.WhenAll(initTasks);
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Initialize. No need to log again.
}
if (agents.Count > 0)
{
Log(ErrorCode.PersistentStreamPullingManager_08, "Added {0} new queues: {1}. Now own total of {2} queues: {3}",
agents.Count,
Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()),
NumberRunningAgents,
PrintQueues(queuesToAgentsMap.Keys));
}
}
private async Task InitAgent(PersistentStreamPullingAgent agent)
{
// Init the agent only after it was registered locally.
var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>();
var queueAdapterCacheAsImmutable = queueAdapterCache != null ? queueAdapterCache.AsImmutable() : new Immutable<IQueueAdapterCache>(null);
IStreamFailureHandler deliveryFailureHandler = await adapterFactory.GetDeliveryFailureHandler(agent.QueueId);
// Need to call it as a grain reference.
var task = OrleansTaskExtentions.SafeExecute(() => agentGrainRef.Initialize(queueAdapter.AsImmutable(), queueAdapterCacheAsImmutable, deliveryFailureHandler.AsImmutable()));
await task.LogException(logger, ErrorCode.PersistentStreamPullingManager_09, String.Format("PersistentStreamPullingAgent {0} failed to Initialize.", agent.QueueId));
}
private async Task RemoveQueues(List<QueueId> queuesToRemove)
{
if (queuesToRemove.Count == 0)
{
return;
}
// Stop the agents that for queues that are not in my range anymore.
var agents = new List<PersistentStreamPullingAgent>(queuesToRemove.Count);
Log(ErrorCode.PersistentStreamPullingManager_10, "About to remove {0} agents from my responsibility: {1}", queuesToRemove.Count, Utils.EnumerableToString(queuesToRemove, q => q.ToString()));
var removeTasks = new List<Task>();
foreach (var queueId in queuesToRemove)
{
PersistentStreamPullingAgent agent;
if (!queuesToAgentsMap.TryGetValue(queueId, out agent)) continue;
agents.Add(agent);
queuesToAgentsMap.Remove(queueId);
var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>();
var task = OrleansTaskExtentions.SafeExecute(agentGrainRef.Shutdown);
task = task.LogException(logger, ErrorCode.PersistentStreamPullingManager_11,
String.Format("PersistentStreamPullingAgent {0} failed to Shutdown.", agent.QueueId));
removeTasks.Add(task);
}
try
{
await Task.WhenAll(removeTasks);
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Shutdown. No need to log again.
}
foreach (var agent in agents)
{
try
{
providerRuntime.UnregisterSystemTarget(agent);
}
catch (Exception exc)
{
Log(ErrorCode.PersistentStreamPullingManager_12,
"Exception while UnRegisterSystemTarget of PersistentStreamPullingAgent {0}. Ignoring. Exc.Message = {1}.", ((ISystemTargetBase)agent).GrainId, exc.Message);
}
}
if (agents.Count > 0)
{
Log(ErrorCode.PersistentStreamPullingManager_10, "Removed {0} queues: {1}. Now own total of {2} queues: {3}",
agents.Count,
Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()),
NumberRunningAgents,
PrintQueues(queuesToAgentsMap.Keys));
}
}
#endregion
public async Task<object> ExecuteCommand(PersistentStreamProviderCommand command, object arg)
{
latestCommandNumber++;
int commandSeqNumber = latestCommandNumber;
try
{
Log(ErrorCode.PersistentStreamPullingManager_13,
String.Format("Got command {0}{1}: commandSeqNumber = {2}, managerState = {3}.",
command, arg != null ? " with arg " + arg : String.Empty, commandSeqNumber, managerState));
switch (command)
{
case PersistentStreamProviderCommand.StartAgents:
case PersistentStreamProviderCommand.StopAgents:
await QueueCommandForExecution(command, commandSeqNumber);
return null;
case PersistentStreamProviderCommand.GetAgentsState:
return managerState;
case PersistentStreamProviderCommand.GetNumberRunningAgents:
return NumberRunningAgents;
default:
throw new OrleansException(String.Format("PullingAgentManager does not support command {0}.", command));
}
}
finally
{
Log(ErrorCode.PersistentStreamPullingManager_15,
String.Format("Done executing command {0}: commandSeqNumber = {1}, managerState = {2}, num running agents = {3}.",
command, commandSeqNumber, managerState, NumberRunningAgents));
}
}
// Start and Stop commands are composite commands that take multiple turns.
// Ee don't wnat them to interleave with other concurrent Start/Stop commands, as well as not with QueueDistributionChangeNotification.
// Therefore, we serialize them all via the same nonReentrancyGuarantor.
private Task QueueCommandForExecution(PersistentStreamProviderCommand command, int commandSeqNumber)
{
return nonReentrancyGuarantor.AddNext(() =>
{
// skip execution of an older/previous command since already got a newer command.
if (commandSeqNumber < latestCommandNumber)
{
Log(ErrorCode.PersistentStreamPullingManager_15,
"Skipping execution of command number {0} since already received a later command (already have command number {1}).",
commandSeqNumber, latestCommandNumber);
return Task.CompletedTask;
}
switch (command)
{
case PersistentStreamProviderCommand.StartAgents:
return StartAgents();
case PersistentStreamProviderCommand.StopAgents:
return StopAgents();
default:
throw new OrleansException(String.Format("PullingAgentManager got unsupported command {0}", command));
}
});
}
private static string PrintQueues(ICollection<QueueId> myQueues)
{
return Utils.EnumerableToString(myQueues, q => q.ToString());
}
// Just print our queue assignment periodicaly, for easy monitoring.
private Task AsyncTimerCallback(object state)
{
Log(ErrorCode.PersistentStreamPullingManager_PeriodicPrint,
"I am responsible for a total of {0} queues on stream provider {1}: {2}.",
NumberRunningAgents, streamProviderName, PrintQueues(queuesToAgentsMap.Keys));
return Task.CompletedTask;
}
private void Log(ErrorCode logCode, string format, params object[] args)
{
logger.Info(logCode, format, args);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public sealed unsafe partial class HttpListenerRequest
{
private Uri _requestUri;
private ulong _requestId;
internal ulong _connectionId;
private SslStatus _sslStatus;
private string _rawUrl;
private string _cookedUrlHost;
private string _cookedUrlPath;
private string _cookedUrlQuery;
private long _contentLength;
private Stream _requestStream;
private string _httpMethod;
private bool? _keepAlive;
private Version _version;
private WebHeaderCollection _webHeaders;
private IPEndPoint _localEndPoint;
private IPEndPoint _remoteEndPoint;
private BoundaryType _boundaryType;
private ListenerClientCertState _clientCertState;
private X509Certificate2 _clientCertificate;
private int _clientCertificateError;
private RequestContextBase _memoryBlob;
private CookieCollection _cookies;
private HttpListenerContext _httpContext;
private bool _isDisposed = false;
internal const uint CertBoblSize = 1500;
private string _serviceName;
private object _lock = new object();
private enum SslStatus : byte
{
Insecure,
NoClientCert,
ClientCert
}
internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"httpContext:${httpContext} memoryBlob {((IntPtr)memoryBlob.RequestBlob)}");
NetEventSource.Associate(this, httpContext);
}
_httpContext = httpContext;
_memoryBlob = memoryBlob;
_boundaryType = BoundaryType.None;
// Set up some of these now to avoid refcounting on memory blob later.
_requestId = memoryBlob.RequestBlob->RequestId;
_connectionId = memoryBlob.RequestBlob->ConnectionId;
_sslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure :
memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert :
SslStatus.ClientCert;
if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0)
{
_rawUrl = Marshal.PtrToStringAnsi((IntPtr)memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength);
}
Interop.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl;
if (cookedUrl.pHost != null && cookedUrl.HostLength > 0)
{
_cookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2);
}
if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0)
{
_cookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2);
}
if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0)
{
_cookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2);
}
_version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion);
_clientCertState = ListenerClientCertState.NotInitialized;
_keepAlive = null;
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"RequestId:{RequestId} ConnectionId:{_connectionId} RawConnectionId:{memoryBlob.RequestBlob->RawConnectionId} UrlContext:{memoryBlob.RequestBlob->UrlContext} RawUrl:{_rawUrl} Version:{_version} Secure:{_sslStatus}");
NetEventSource.Info(this, $"httpContext:${httpContext} RequestUri:{RequestUri} Content-Length:{ContentLength64} HTTP Method:{HttpMethod}");
}
// Log headers
if (NetEventSource.IsEnabled)
{
StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n");
for (int i = 0; i < Headers.Count; i++)
{
sb.Append("\t");
sb.Append(Headers.GetKey(i));
sb.Append(" : ");
sb.Append(Headers.Get(i));
sb.Append("\n");
}
NetEventSource.Info(this, sb.ToString());
}
}
internal HttpListenerContext HttpListenerContext
{
get
{
return _httpContext;
}
}
// Note: RequestBuffer may get moved in memory. If you dereference a pointer from inside the RequestBuffer,
// you must use 'OriginalBlobAddress' below to adjust the location of the pointer to match the location of
// RequestBuffer.
internal byte[] RequestBuffer
{
get
{
CheckDisposed();
return _memoryBlob.RequestBuffer;
}
}
internal IntPtr OriginalBlobAddress
{
get
{
CheckDisposed();
return _memoryBlob.OriginalBlobAddress;
}
}
// Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be
// disposed.
internal void DetachBlob(RequestContextBase memoryBlob)
{
if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob)
{
_memoryBlob = null;
}
}
// Finalizes ownership of the memory blob. DetachBlob can't be called after this.
internal void ReleasePins()
{
_memoryBlob.ReleasePins();
}
internal ulong RequestId
{
get
{
return _requestId;
}
}
public Guid RequestTraceIdentifier
{
get
{
Guid guid = new Guid();
*(1 + (ulong*)&guid) = RequestId;
return guid;
}
}
public string[] AcceptTypes
{
get
{
return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.Accept));
}
}
public long ContentLength64
{
get
{
if (_boundaryType == BoundaryType.None)
{
string transferEncodingHeader = GetKnownHeader(HttpRequestHeader.TransferEncoding);
if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase))
{
_boundaryType = BoundaryType.Chunked;
_contentLength = -1;
}
else
{
_contentLength = 0;
_boundaryType = BoundaryType.ContentLength;
string length = GetKnownHeader(HttpRequestHeader.ContentLength);
if (length != null)
{
bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength);
if (!success)
{
_contentLength = 0;
_boundaryType = BoundaryType.Invalid;
}
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_contentLength:{_contentLength} _boundaryType:{_boundaryType}");
return _contentLength;
}
}
public string ContentType
{
get
{
return GetKnownHeader(HttpRequestHeader.ContentType);
}
}
public NameValueCollection Headers
{
get
{
if (_webHeaders == null)
{
_webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"webHeaders:{_webHeaders}");
return _webHeaders;
}
}
public string HttpMethod
{
get
{
if (_httpMethod == null)
{
_httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}");
return _httpMethod;
}
}
public Stream InputStream
{
get
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (_requestStream == null)
{
_requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return _requestStream;
}
}
public bool IsAuthenticated
{
get
{
IPrincipal user = HttpListenerContext.User;
return user != null && user.Identity != null && user.Identity.IsAuthenticated;
}
}
public bool IsLocal
{
get
{
return LocalEndPoint.Address.Equals(RemoteEndPoint.Address);
}
}
public bool IsSecureConnection
{
get
{
return _sslStatus != SslStatus.Insecure;
}
}
public bool IsWebSocketRequest
{
get
{
if (!WebSocketProtocolComponent.IsSupported)
{
return false;
}
bool foundConnectionUpgradeHeader = false;
if (string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Upgrade]))
{
return false;
}
foreach (string connection in this.Headers.GetValues(HttpKnownHeaderNames.Connection))
{
if (string.Compare(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase) == 0)
{
foundConnectionUpgradeHeader = true;
break;
}
}
if (!foundConnectionUpgradeHeader)
{
return false;
}
foreach (string upgrade in this.Headers.GetValues(HttpKnownHeaderNames.Upgrade))
{
if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
public NameValueCollection QueryString
{
get
{
NameValueCollection queryString = new NameValueCollection();
Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding);
return queryString;
}
}
public string RawUrl
{
get
{
return _rawUrl;
}
}
public string ServiceName
{
get { return _serviceName; }
internal set { _serviceName = value; }
}
public Uri Url
{
get
{
return RequestUri;
}
}
public Uri UrlReferrer
{
get
{
string referrer = GetKnownHeader(HttpRequestHeader.Referer);
if (referrer == null)
{
return null;
}
Uri urlReferrer;
bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out urlReferrer);
return success ? urlReferrer : null;
}
}
public string UserAgent
{
get
{
return GetKnownHeader(HttpRequestHeader.UserAgent);
}
}
public string UserHostAddress
{
get
{
return LocalEndPoint.ToString();
}
}
public string UserHostName
{
get
{
return GetKnownHeader(HttpRequestHeader.Host);
}
}
public string[] UserLanguages
{
get
{
return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.AcceptLanguage));
}
}
public int ClientCertificateError
{
get
{
if (_clientCertState == ListenerClientCertState.NotInitialized)
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "GetClientCertificate()/BeginGetClientCertificate()"));
else if (_clientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.Format(SR.net_listener_mustcompletecall, "GetClientCertificate()/BeginGetClientCertificate()"));
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ClientCertificateError:{_clientCertificateError}");
return _clientCertificateError;
}
}
internal X509Certificate2 ClientCertificate
{
set
{
_clientCertificate = value;
}
}
internal ListenerClientCertState ClientCertState
{
set
{
_clientCertState = value;
}
}
internal void SetClientCertificateError(int clientCertificateError)
{
_clientCertificateError = clientCertificateError;
}
public X509Certificate2 GetClientCertificate()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
ProcessClientCertificate();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{_clientCertificate}");
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return _clientCertificate;
}
public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
return AsyncProcessClientCertificate(requestCallback, state);
}
public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
X509Certificate2 clientCertificate = null;
try
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult;
if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (clientCertAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate)));
}
clientCertAsyncResult.EndCalled = true;
clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{_clientCertificate}");
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
return clientCertificate;
}
public Task<X509Certificate2> GetClientCertificateAsync()
{
return Task.Factory.FromAsync(
(callback, state) => ((HttpListenerRequest)state).BeginGetClientCertificate(callback, state),
iar => ((HttpListenerRequest)iar.AsyncState).EndGetClientCertificate(iar),
this);
}
public TransportContext TransportContext
{
get
{
return new HttpListenerRequestContext(this);
}
}
private CookieCollection ParseCookies(Uri uri, string setCookieHeader)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "uri:" + uri + " setCookieHeader:" + setCookieHeader);
CookieContainer container = new CookieContainer();
container.SetCookies(uri, setCookieHeader);
return container.GetCookies(uri);
}
public CookieCollection Cookies
{
get
{
if (_cookies == null)
{
string cookieString = GetKnownHeader(HttpRequestHeader.Cookie);
if (cookieString != null && cookieString.Length > 0)
{
_cookies = ParseCookies(RequestUri, cookieString);
}
if (_cookies == null)
{
_cookies = new CookieCollection();
}
}
return _cookies;
}
}
public Version ProtocolVersion
{
get
{
return _version;
}
}
public bool HasEntityBody
{
get
{
// accessing the ContentLength property delay creates m_BoundaryType
return (ContentLength64 > 0 && _boundaryType == BoundaryType.ContentLength) ||
_boundaryType == BoundaryType.Chunked || _boundaryType == BoundaryType.Multipart;
}
}
public bool KeepAlive
{
get
{
if (!_keepAlive.HasValue)
{
string header = Headers[HttpKnownHeaderNames.ProxyConnection];
if (string.IsNullOrEmpty(header))
{
header = GetKnownHeader(HttpRequestHeader.Connection);
}
if (string.IsNullOrEmpty(header))
{
if (ProtocolVersion >= HttpVersion.Version11)
{
_keepAlive = true;
}
else
{
header = GetKnownHeader(HttpRequestHeader.KeepAlive);
_keepAlive = !string.IsNullOrEmpty(header);
}
}
else
{
header = header.ToLower(CultureInfo.InvariantCulture);
_keepAlive =
header.IndexOf("close", StringComparison.InvariantCultureIgnoreCase) < 0 ||
header.IndexOf("keep-alive", StringComparison.InvariantCultureIgnoreCase) >= 0;
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_keepAlive=" + _keepAlive);
return _keepAlive.Value;
}
}
public IPEndPoint RemoteEndPoint
{
get
{
if (_remoteEndPoint == null)
{
_remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint);
return _remoteEndPoint;
}
}
public IPEndPoint LocalEndPoint
{
get
{
if (_localEndPoint == null)
{
_localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}");
return _localEndPoint;
}
}
//should only be called from httplistenercontext
internal void Close()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
RequestContextBase memoryBlob = _memoryBlob;
if (memoryBlob != null)
{
memoryBlob.Close();
_memoryBlob = null;
}
_isDisposed = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
private ListenerClientCertAsyncResult AsyncProcessClientCertificate(AsyncCallback requestCallback, object state)
{
if (_clientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()"));
_clientCertState = ListenerClientCertState.InProgress;
ListenerClientCertAsyncResult asyncResult = null;
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are requried at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, size);
try
{
while (true)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
asyncResult.RequestBlob,
size,
&bytesReceived,
asyncResult.NativeOverlapped);
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
size = bytesReceived + pClientCertInfo->CertEncodedSize;
asyncResult.Reset(size);
continue;
}
if (statusCode != Interop.HttpApi.ERROR_SUCCESS &&
statusCode != Interop.HttpApi.ERROR_IO_PENDING)
{
// someother bad error, possible return values are:
// ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED
// Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required.
throw new HttpListenerException((int)statusCode);
}
if (statusCode == Interop.HttpApi.ERROR_SUCCESS &&
HttpListener.SkipIOCPCallbackOnSuccess)
{
asyncResult.IOCompleted(statusCode, bytesReceived);
}
break;
}
}
catch
{
asyncResult?.InternalCleanup();
throw;
}
}
else
{
asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, 0);
asyncResult.InvokeCallback();
}
return asyncResult;
}
private void ProcessClientCertificate()
{
if (_clientCertState == ListenerClientCertState.InProgress)
throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()"));
_clientCertState = ListenerClientCertState.InProgress;
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
//--------------------------------------------------------------------
//When you configure the HTTP.SYS with a flag value 2
//which means require client certificates, when the client makes the
//initial SSL connection, server (HTTP.SYS) demands the client certificate
//
//Some apps may not want to demand the client cert at the beginning
//perhaps server the default.htm. In this case the HTTP.SYS is configured
//with a flag value other than 2, whcih means that the client certificate is
//optional.So initially when SSL is established HTTP.SYS won't ask for client
//certificate. This works fine for the default.htm in the case above
//However, if the app wants to demand a client certficate at a later time
//perhaps showing "YOUR ORDERS" page, then the server wans to demand
//Client certs. this will inturn makes HTTP.SYS to do the
//SEC_I_RENOGOTIATE through which the client cert demand is made
//
//THE BUG HERE IS THAT PRIOR TO QFE 4796, we call
//GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with
//flag = 2. Which means that apps using HTTPListener will not be able to
//demand a client cert at a later point
//
//The fix here is to demand the client cert when the channel is NOT INSECURE
//which means whether the client certs are requried at the beginning or not,
//if this is an SSL connection, Call HttpReceiveClientCertificate, thus
//starting the cert negotiation at that point
//
//NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get
//ERROR_NOT_FOUND - which means the client did not provide the cert
//If this is important, the server should respond with 403 forbidden
//HTTP.SYS will not do this for you automatically ***
//--------------------------------------------------------------------
if (_sslStatus != SslStatus.Insecure)
{
// at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate)
// the cert, though might or might not be there. try to retrieve it
// this number is the same that IIS decided to use
uint size = CertBoblSize;
while (true)
{
byte[] clientCertInfoBlob = new byte[checked((int)size)];
fixed (byte* pClientCertInfoBlob = &clientCertInfoBlob[0])
{
Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)pClientCertInfoBlob;
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size);
uint bytesReceived = 0;
uint statusCode =
Interop.HttpApi.HttpReceiveClientCertificate(
HttpListenerContext.RequestQueueHandle,
_connectionId,
(uint)Interop.HttpApi.HTTP_FLAGS.NONE,
pClientCertInfo,
size,
&bytesReceived,
null);
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived);
if (statusCode == Interop.HttpApi.ERROR_MORE_DATA)
{
size = bytesReceived + pClientCertInfo->CertEncodedSize;
continue;
}
else if (statusCode == Interop.HttpApi.ERROR_SUCCESS)
{
if (pClientCertInfo != null)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}");
if (pClientCertInfo->pCertEncoded != null)
{
try
{
byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
_clientCertificate = new X509Certificate2(certEncoded);
}
catch (CryptographicException exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CryptographicException={exception}");
}
catch (SecurityException exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SecurityException={exception}");
}
}
_clientCertificateError = (int)pClientCertInfo->CertFlags;
}
}
else
{
Debug.Assert(statusCode == Interop.HttpApi.ERROR_NOT_FOUND,
$"Call to Interop.HttpApi.HttpReceiveClientCertificate() failed with statusCode {statusCode}.");
}
}
break;
}
}
_clientCertState = ListenerClientCertState.Completed;
}
private string RequestScheme
{
get
{
return IsSecureConnection ? "https" : "http";
}
}
private Uri RequestUri
{
get
{
if (_requestUri == null)
{
_requestUri = HttpListenerRequestUriBuilder.GetRequestUri(
_rawUrl, RequestScheme, _cookedUrlHost, _cookedUrlPath, _cookedUrlQuery);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_requestUri:{_requestUri}");
return _requestUri;
}
}
private string GetKnownHeader(HttpRequestHeader header)
{
return Interop.HttpApi.GetKnownHeader(RequestBuffer, OriginalBlobAddress, (int)header);
}
internal ChannelBinding GetChannelBinding()
{
return HttpListenerContext.Listener.GetChannelBindingFromTls(_connectionId);
}
internal void CheckDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
#region Delegates
public delegate uint GenerateClientFlagsHandler(UUID userID, UUID objectIDID, bool fastCheck);
public delegate void SetBypassPermissionsHandler(bool value);
public delegate bool BypassPermissionsHandler();
public delegate bool PropagatePermissionsHandler();
public delegate bool RezObjectHandler(int landImpact, UUID owner, UUID objectID, Vector3 objectPosition, bool isTemp, Scene scene);
public delegate bool DeleteObjectHandler(UUID objectID, UUID deleter, Scene scene);
public delegate bool TakeObjectHandler(UUID objectID, UUID stealer, Scene scene);
public delegate bool TakeCopyObjectHandler(UUID objectID, UUID userID, Scene inScene);
public delegate bool DuplicateObjectHandler(int objectCount, UUID objectID, UUID owner, Scene scene, Vector3 objectPosition);
public delegate bool EditObjectHandler(UUID objectID, UUID editorID, Scene scene, uint requiredPermissionMask);
public delegate bool EditObjectInventoryHandler(UUID objectID, UUID editorID, Scene scene);
public delegate bool MoveObjectHandler(UUID objectID, UUID moverID, Scene scene);
public delegate bool ObjectEntryHandler(UUID objectID, bool enteringRegion, Vector3 newPoint, Scene scene);
public delegate bool ReturnObjectHandler(UUID objectID, UUID returnerID, Scene scene);
public delegate bool InstantMessageHandler(UUID user, UUID target, Scene startScene);
public delegate bool InventoryTransferHandler(UUID user, UUID target, Scene startScene);
public delegate bool ViewScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
public delegate bool ViewNotecardHandler(UUID script, UUID objectID, UUID user, Scene scene);
public delegate bool EditScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
public delegate bool EditNotecardHandler(UUID notecard, UUID objectID, UUID user, Scene scene);
public delegate bool RunScriptHandler(UUID script, UUID objectID, UUID user, Scene scene);
public delegate bool StartScriptHandler(SceneObjectPart part, UUID script, UUID user, Scene scene);
public delegate bool StopScriptHandler(SceneObjectPart part, UUID script, UUID user, Scene scene);
public delegate bool ResetScriptHandler(UUID prim, UUID script, UUID user, Scene scene);
public delegate bool TerraformLandHandler(UUID user, Vector3 position, Scene requestFromScene);
public delegate bool RunConsoleCommandHandler(UUID user, Scene requestFromScene);
public delegate bool IssueEstateCommandHandler(UUID user, Scene requestFromScene, bool ownerCommand);
public delegate bool IsGodHandler(UUID user, Scene requestFromScene);
public delegate bool EditParcelHandler(UUID user, ILandObject parcel, GroupPowers p, Scene scene);
public delegate bool SellParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool AbandonParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool ReclaimParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool DeedParcelHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool DeedObjectHandler(UUID user, UUID group, Scene scene);
public delegate bool BuyLandHandler(UUID user, ILandObject parcel, Scene scene);
public delegate bool LinkObjectHandler(UUID user, UUID objectID);
public delegate bool DelinkObjectHandler(UUID user, UUID objectID);
public delegate bool CreateObjectInventoryHandler(int invType, UUID objectID, UUID userID);
public delegate bool CopyObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool DeleteObjectInventoryHandler(UUID itemID, UUID objectID, UUID userID);
public delegate bool CreateUserInventoryHandler(int invType, UUID userID);
public delegate bool EditUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool CopyUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool DeleteUserInventoryHandler(UUID itemID, UUID userID);
public delegate bool TeleportHandler(UUID userID, Scene scene);
public delegate bool UseObjectReturnHandler(ILandObject parcel, uint type, IClientAPI client, UUID scriptOwnerID, List<SceneObjectGroup> retlist, Scene scene);
public delegate bool ControlPrimMediaHandler(UUID userID, UUID primID, int face);
public delegate bool InteractWithPrimMediaHandler(UUID userID, UUID primID, int face);
#endregion
public class ScenePermissions
{
private Scene m_scene;
public ScenePermissions(Scene scene)
{
m_scene = scene;
}
#region Events
public event GenerateClientFlagsHandler OnGenerateClientFlags;
public event SetBypassPermissionsHandler OnSetBypassPermissions;
public event BypassPermissionsHandler OnBypassPermissions;
public event PropagatePermissionsHandler OnPropagatePermissions;
public event RezObjectHandler OnRezObject;
public event DeleteObjectHandler OnDeleteObject;
public event TakeObjectHandler OnTakeObject;
public event TakeCopyObjectHandler OnTakeCopyObject;
public event DuplicateObjectHandler OnDuplicateObject;
public event EditObjectHandler OnEditObject;
public event EditObjectInventoryHandler OnEditObjectInventory;
public event MoveObjectHandler OnMoveObject;
public event ObjectEntryHandler OnObjectEntry;
public event ReturnObjectHandler OnReturnObject;
public event InstantMessageHandler OnInstantMessage;
public event InventoryTransferHandler OnInventoryTransfer;
public event ViewScriptHandler OnViewScript;
public event ViewNotecardHandler OnViewNotecard;
public event EditScriptHandler OnEditScript;
public event EditNotecardHandler OnEditNotecard;
public event RunScriptHandler OnRunScript;
public event StartScriptHandler OnStartScript;
public event StopScriptHandler OnStopScript;
public event ResetScriptHandler OnResetScript;
public event TerraformLandHandler OnTerraformLand;
public event RunConsoleCommandHandler OnRunConsoleCommand;
public event IssueEstateCommandHandler OnIssueEstateCommand;
public event IsGodHandler OnIsGod;
public event EditParcelHandler OnEditParcel;
// public event SellParcelHandler OnSellParcel;
public event AbandonParcelHandler OnAbandonParcel;
public event ReclaimParcelHandler OnReclaimParcel;
public event DeedParcelHandler OnDeedParcel;
public event DeedObjectHandler OnDeedObject;
public event BuyLandHandler OnBuyLand;
public event LinkObjectHandler OnLinkObject;
public event DelinkObjectHandler OnDelinkObject;
public event CreateObjectInventoryHandler OnCreateObjectInventory;
public event CopyObjectInventoryHandler OnCopyObjectInventory;
public event DeleteObjectInventoryHandler OnDeleteObjectInventory;
public event CreateUserInventoryHandler OnCreateUserInventory;
public event EditUserInventoryHandler OnEditUserInventory;
public event CopyUserInventoryHandler OnCopyUserInventory;
public event DeleteUserInventoryHandler OnDeleteUserInventory;
public event TeleportHandler OnTeleport;
public event UseObjectReturnHandler OnUseObjectReturn;
public event ControlPrimMediaHandler OnControlPrimMedia;
public event InteractWithPrimMediaHandler OnInteractWithPrimMedia;
#endregion
#region Object Permission Checks
public uint GenerateClientFlags(UUID userID, UUID objectID, bool fastCheck)
{
SceneObjectPart part=m_scene.GetSceneObjectPart(objectID);
if (part == null)
return 0;
// libomv will moan about PrimFlags.ObjectYouOfficer being
// obsolete...
#pragma warning disable 0612
uint perms=(uint)part.GetEffectiveObjectFlags() |
(uint)PrimFlags.ObjectModify |
(uint)PrimFlags.ObjectCopy |
(uint)PrimFlags.ObjectMove |
(uint)PrimFlags.ObjectTransfer |
(uint)PrimFlags.ObjectYouOwner |
(uint)PrimFlags.ObjectAnyOwner |
(uint)PrimFlags.ObjectOwnerModify |
(uint)PrimFlags.ObjectYouOfficer;
#pragma warning restore 0612
GenerateClientFlagsHandler handlerGenerateClientFlags =
OnGenerateClientFlags;
if (handlerGenerateClientFlags != null)
{
Delegate[] list = handlerGenerateClientFlags.GetInvocationList();
foreach (GenerateClientFlagsHandler check in list)
{
perms &= check(userID, objectID, fastCheck);
}
}
return perms;
}
public void SetBypassPermissions(bool value)
{
SetBypassPermissionsHandler handler = OnSetBypassPermissions;
if (handler != null)
handler(value);
}
public bool BypassPermissions()
{
BypassPermissionsHandler handler = OnBypassPermissions;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (BypassPermissionsHandler h in list)
{
if (h() == false)
return false;
}
}
return true;
}
// Minimum functionality: if the GenerateClientFlagsHandler is not set, there is no permissions module available.
public bool IsAvailable()
{
return (OnGenerateClientFlags != null);
}
public bool PropagatePermissions()
{
PropagatePermissionsHandler handler = OnPropagatePermissions;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (PropagatePermissionsHandler h in list)
{
if (h() == false)
return false;
}
}
return true;
}
#region REZ OBJECT
public bool CanRezObject(int landImpact, UUID owner, UUID objectID, Vector3 objectPosition, bool isTemp)
{
RezObjectHandler handler = OnRezObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RezObjectHandler h in list)
{
if (h(landImpact, owner, objectID, objectPosition, isTemp, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region DELETE OBJECT
public bool CanDeleteObject(UUID objectID, UUID deleter)
{
DeleteObjectHandler handler = OnDeleteObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteObjectHandler h in list)
{
if (h(objectID, deleter, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region TAKE OBJECT
public bool CanTakeObject(UUID objectID, UUID AvatarTakingUUID)
{
TakeObjectHandler handler = OnTakeObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TakeObjectHandler h in list)
{
if (h(objectID, AvatarTakingUUID, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region TAKE COPY OBJECT
public bool CanTakeCopyObject(UUID objectID, UUID userID)
{
TakeCopyObjectHandler handler = OnTakeCopyObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TakeCopyObjectHandler h in list)
{
if (h(objectID, userID, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region DUPLICATE OBJECT
public bool CanDuplicateObject(int objectCount, UUID objectID, UUID owner, Vector3 objectPosition)
{
DuplicateObjectHandler handler = OnDuplicateObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DuplicateObjectHandler h in list)
{
if (h(objectCount, objectID, owner, m_scene, objectPosition) == false)
return false;
}
}
return true;
}
#endregion
#region EDIT OBJECT
public bool CanEditObject(UUID objectID, UUID editorID, uint requiredPermissionMask)
{
EditObjectHandler handler = OnEditObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectHandler h in list)
{
if (h(objectID, editorID, m_scene, requiredPermissionMask) == false)
return false;
}
}
return true;
}
public bool CanEditObjectInventory(UUID objectID, UUID editorID)
{
EditObjectInventoryHandler handler = OnEditObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditObjectInventoryHandler h in list)
{
if (h(objectID, editorID, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region MOVE OBJECT
public bool CanMoveObject(UUID objectID, UUID moverID)
{
MoveObjectHandler handler = OnMoveObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (MoveObjectHandler h in list)
{
if (h(objectID, moverID, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region OBJECT ENTRY
public bool CanObjectEntry(UUID objectID, bool enteringRegion, Vector3 newPoint)
{
ObjectEntryHandler handler = OnObjectEntry;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ObjectEntryHandler h in list)
{
if (h(objectID, enteringRegion, newPoint, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region RETURN OBJECT
public bool CanReturnObject(UUID objectID, UUID returnerID)
{
ReturnObjectHandler handler = OnReturnObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ReturnObjectHandler h in list)
{
if (h(objectID, returnerID, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region INSTANT MESSAGE
public bool CanInstantMessage(UUID user, UUID target)
{
InstantMessageHandler handler = OnInstantMessage;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InstantMessageHandler h in list)
{
if (h(user, target, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region INVENTORY TRANSFER
public bool CanInventoryTransfer(UUID user, UUID target)
{
InventoryTransferHandler handler = OnInventoryTransfer;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InventoryTransferHandler h in list)
{
if (h(user, target, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region VIEW SCRIPT
public bool CanViewScript(UUID script, UUID objectID, UUID user)
{
ViewScriptHandler handler = OnViewScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ViewScriptHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
public bool CanViewNotecard(UUID script, UUID objectID, UUID user)
{
ViewNotecardHandler handler = OnViewNotecard;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ViewNotecardHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region EDIT SCRIPT
public bool CanEditScript(UUID script, UUID objectID, UUID user)
{
EditScriptHandler handler = OnEditScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditScriptHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
public bool CanEditNotecard(UUID script, UUID objectID, UUID user)
{
EditNotecardHandler handler = OnEditNotecard;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditNotecardHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region RUN SCRIPT (When Script Placed in Object)
public bool CanRunScript(UUID script, UUID objectID, UUID user)
{
RunScriptHandler handler = OnRunScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RunScriptHandler h in list)
{
if (h(script, objectID, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region START SCRIPT (When Script run box is Checked after placed in object)
public bool CanStartScript(SceneObjectPart part, UUID script, UUID user)
{
StartScriptHandler handler = OnStartScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (StartScriptHandler h in list)
{
if (h(part, script, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region STOP SCRIPT (When Script run box is unchecked after placed in object)
public bool CanStopScript(SceneObjectPart part, UUID script, UUID user)
{
StopScriptHandler handler = OnStopScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (StopScriptHandler h in list)
{
if (h(part, script, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region RESET SCRIPT
public bool CanResetScript(UUID prim, UUID script, UUID user)
{
ResetScriptHandler handler = OnResetScript;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ResetScriptHandler h in list)
{
if (h(prim, script, user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region TERRAFORM LAND
public bool CanTerraformLand(UUID user, Vector3 pos)
{
TerraformLandHandler handler = OnTerraformLand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TerraformLandHandler h in list)
{
if (h(user, pos, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region RUN CONSOLE COMMAND
public bool CanRunConsoleCommand(UUID user)
{
RunConsoleCommandHandler handler = OnRunConsoleCommand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (RunConsoleCommandHandler h in list)
{
if (h(user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region CAN ISSUE ESTATE COMMAND
public bool CanIssueEstateCommand(UUID user, bool ownerCommand)
{
IssueEstateCommandHandler handler = OnIssueEstateCommand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IssueEstateCommandHandler h in list)
{
if (h(user, m_scene, ownerCommand) == false)
return false;
}
}
return true;
}
#endregion
#region CAN BE GODLIKE
public bool IsGod(UUID user)
{
IsGodHandler handler = OnIsGod;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (IsGodHandler h in list)
{
if (h(user, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region EDIT PARCEL
public bool CanEditParcel(UUID user, ILandObject parcel, GroupPowers p)
{
EditParcelHandler handler = OnEditParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditParcelHandler h in list)
{
if (h(user, parcel, p, m_scene) == false)
return false;
}
}
return true;
}
#endregion
#region ABANDON PARCEL
public bool CanAbandonParcel(UUID user, ILandObject parcel)
{
AbandonParcelHandler handler = OnAbandonParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (AbandonParcelHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
#endregion
public bool CanReclaimParcel(UUID user, ILandObject parcel)
{
ReclaimParcelHandler handler = OnReclaimParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ReclaimParcelHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
public bool CanDeedParcel(UUID user, ILandObject parcel)
{
DeedParcelHandler handler = OnDeedParcel;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeedParcelHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
public bool CanDeedObject(UUID user, UUID group)
{
DeedObjectHandler handler = OnDeedObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeedObjectHandler h in list)
{
if (h(user, group, m_scene) == false)
return false;
}
}
return true;
}
public bool CanBuyLand(UUID user, ILandObject parcel)
{
BuyLandHandler handler = OnBuyLand;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (BuyLandHandler h in list)
{
if (h(user, parcel, m_scene) == false)
return false;
}
}
return true;
}
public bool CanLinkObject(UUID user, UUID objectID)
{
LinkObjectHandler handler = OnLinkObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (LinkObjectHandler h in list)
{
if (h(user, objectID) == false)
return false;
}
}
return true;
}
public bool CanDelinkObject(UUID user, UUID objectID)
{
DelinkObjectHandler handler = OnDelinkObject;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DelinkObjectHandler h in list)
{
if (h(user, objectID) == false)
return false;
}
}
return true;
}
#endregion
/// Check whether the specified user is allowed to directly create the given inventory type in a prim's
/// inventory (e.g. the New Script button in the 1.21 Linden Lab client).
/// </summary>
/// <param name="invType"></param>
/// <param name="objectID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCreateObjectInventory(int invType, UUID objectID, UUID userID)
{
CreateObjectInventoryHandler handler = OnCreateObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CreateObjectInventoryHandler h in list)
{
if (h(invType, objectID, userID) == false)
return false;
}
}
return true;
}
public bool CanCopyObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
CopyObjectInventoryHandler handler = OnCopyObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CopyObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
public bool CanDeleteObjectInventory(UUID itemID, UUID objectID, UUID userID)
{
DeleteObjectInventoryHandler handler = OnDeleteObjectInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteObjectInventoryHandler h in list)
{
if (h(itemID, objectID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to create the given inventory type in their inventory.
/// </summary>
/// <param name="invType"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCreateUserInventory(int invType, UUID userID)
{
CreateUserInventoryHandler handler = OnCreateUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CreateUserInventoryHandler h in list)
{
if (h(invType, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to edit the given inventory item within their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanEditUserInventory(UUID itemID, UUID userID)
{
EditUserInventoryHandler handler = OnEditUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (EditUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to copy the given inventory item from their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanCopyUserInventory(UUID itemID, UUID userID)
{
CopyUserInventoryHandler handler = OnCopyUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (CopyUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
/// <summary>
/// Check whether the specified user is allowed to edit the given inventory item within their own inventory.
/// </summary>
/// <param name="itemID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public bool CanDeleteUserInventory(UUID itemID, UUID userID)
{
DeleteUserInventoryHandler handler = OnDeleteUserInventory;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (DeleteUserInventoryHandler h in list)
{
if (h(itemID, userID) == false)
return false;
}
}
return true;
}
public bool CanTeleport(UUID userID)
{
TeleportHandler handler = OnTeleport;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (TeleportHandler h in list)
{
if (h(userID, m_scene) == false)
return false;
}
}
return true;
}
public bool CanUseObjectReturn(ILandObject parcel, uint type, IClientAPI client, UUID scriptOwnerID, List<SceneObjectGroup> retlist)
{
UseObjectReturnHandler handler = OnUseObjectReturn;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (UseObjectReturnHandler h in list)
{
if (h(parcel, type, client, scriptOwnerID, retlist, m_scene) == false)
return false;
}
}
return true;
}
public bool CanControlPrimMedia(UUID userID, UUID primID, int face)
{
ControlPrimMediaHandler handler = OnControlPrimMedia;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (ControlPrimMediaHandler h in list)
{
if (h(userID, primID, face) == false)
return false;
}
}
return true;
}
public bool CanInteractWithPrimMedia(UUID userID, UUID primID, int face)
{
InteractWithPrimMediaHandler handler = OnInteractWithPrimMedia;
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
foreach (InteractWithPrimMediaHandler h in list)
{
if (h(userID, primID, face) == false)
return false;
}
}
return true;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using ServiceStack.Text.Json;
using ServiceStack.Text.Jsv;
namespace ServiceStack.Text.Common
{
public static class JsWriter
{
public const string TypeAttr = "__type";
public const char MapStartChar = '{';
public const char MapKeySeperator = ':';
public const char ItemSeperator = ',';
public const char MapEndChar = '}';
public const string MapNullValue = "\"\"";
public const string EmptyMap = "{}";
public const char ListStartChar = '[';
public const char ListEndChar = ']';
public const char ReturnChar = '\r';
public const char LineFeedChar = '\n';
public const char QuoteChar = '"';
public const string QuoteString = "\"";
public const string EscapedQuoteString = "\\\"";
public const string ItemSeperatorString = ",";
public const string MapKeySeperatorString = ":";
public static readonly char[] CsvChars = new[] { ItemSeperator, QuoteChar };
public static readonly char[] EscapeChars = new[] { QuoteChar, MapKeySeperator, ItemSeperator, MapStartChar, MapEndChar, ListStartChar, ListEndChar, ReturnChar, LineFeedChar };
private const int LengthFromLargestChar = '}' + 1;
private static readonly bool[] EscapeCharFlags = new bool[LengthFromLargestChar];
static JsWriter()
{
foreach (var escapeChar in EscapeChars)
{
EscapeCharFlags[escapeChar] = true;
}
var loadConfig = JsConfig.TextCase; //force load
}
public static void WriteDynamic(Action callback)
{
JsState.IsWritingDynamic = true;
try
{
callback();
}
finally
{
JsState.IsWritingDynamic = false;
}
}
/// <summary>
/// micro optimizations: using flags instead of value.IndexOfAny(EscapeChars)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool HasAnyEscapeChars(string value)
{
var len = value.Length;
for (var i = 0; i < len; i++)
{
var c = value[i];
if (c >= LengthFromLargestChar || !EscapeCharFlags[c]) continue;
return true;
}
return false;
}
internal static void WriteItemSeperatorIfRanOnce(TextWriter writer, ref bool ranOnce)
{
if (ranOnce)
writer.Write(ItemSeperator);
else
ranOnce = true;
}
internal static bool ShouldUseDefaultToStringMethod(Type type)
{
var underlyingType = Nullable.GetUnderlyingType(type) ?? type;
switch (underlyingType.GetTypeCode())
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.DateTime:
return true;
}
return underlyingType == typeof(Guid);
}
public static ITypeSerializer GetTypeSerializer<TSerializer>()
{
if (typeof(TSerializer) == typeof(JsvTypeSerializer))
return JsvTypeSerializer.Instance;
if (typeof(TSerializer) == typeof(JsonTypeSerializer))
return JsonTypeSerializer.Instance;
throw new NotSupportedException(typeof(TSerializer).Name);
}
public static void WriteEnumFlags(TextWriter writer, object enumFlagValue)
{
if (enumFlagValue == null) return;
var typeCode = Enum.GetUnderlyingType(enumFlagValue.GetType()).GetTypeCode();
switch (typeCode)
{
case TypeCode.SByte:
writer.Write((sbyte)enumFlagValue);
break;
case TypeCode.Byte:
writer.Write((byte)enumFlagValue);
break;
case TypeCode.Int16:
writer.Write((short)enumFlagValue);
break;
case TypeCode.UInt16:
writer.Write((ushort)enumFlagValue);
break;
case TypeCode.Int32:
writer.Write((int)enumFlagValue);
break;
case TypeCode.UInt32:
writer.Write((uint)enumFlagValue);
break;
case TypeCode.Int64:
writer.Write((long)enumFlagValue);
break;
case TypeCode.UInt64:
writer.Write((ulong)enumFlagValue);
break;
default:
writer.Write((int)enumFlagValue);
break;
}
}
public static bool ShouldAllowRuntimeType(Type type)
{
if (!JsState.IsRuntimeType)
return true;
if (JsConfig.AllowRuntimeType?.Invoke(type) == true)
return true;
var allowAttributesNamed = JsConfig.AllowRuntimeTypeWithAttributesNamed;
if (allowAttributesNamed?.Count > 0)
{
var oAttrs = type.AllAttributes();
foreach (var oAttr in oAttrs)
{
if (!(oAttr is Attribute attr)) continue;
if (allowAttributesNamed.Contains(attr.GetType().Name))
return true;
}
}
var allowInterfacesNamed = JsConfig.AllowRuntimeTypeWithInterfacesNamed;
if (allowInterfacesNamed?.Count > 0)
{
var interfaces = type.GetInterfaces();
foreach (var interfaceType in interfaces)
{
if (allowInterfacesNamed.Contains(interfaceType.Name))
return true;
}
}
return false;
}
public static void AssertAllowedRuntimeType(Type type)
{
if (!ShouldAllowRuntimeType(type))
throw new NotSupportedException($"{type.Name} is not an allowed Runtime Type. Whitelist Type with [RuntimeSerializable] or IRuntimeSerializable.");
}
}
public class JsWriter<TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
public JsWriter()
{
this.SpecialTypes = new Dictionary<Type, WriteObjectDelegate>
{
{ typeof(Uri), Serializer.WriteObjectString },
{ typeof(Type), WriteType },
{ typeof(Exception), Serializer.WriteException },
};
}
public WriteObjectDelegate GetValueTypeToStringMethod(Type type)
{
var underlyingType = Nullable.GetUnderlyingType(type);
var isNullable = underlyingType != null;
if (underlyingType == null)
underlyingType = type;
if (!underlyingType.IsEnum)
{
var typeCode = underlyingType.GetTypeCode();
if (typeCode == TypeCode.Char)
return Serializer.WriteChar;
if (typeCode == TypeCode.Int32)
return Serializer.WriteInt32;
if (typeCode == TypeCode.Int64)
return Serializer.WriteInt64;
if (typeCode == TypeCode.UInt64)
return Serializer.WriteUInt64;
if (typeCode == TypeCode.UInt32)
return Serializer.WriteUInt32;
if (typeCode == TypeCode.Byte)
return Serializer.WriteByte;
if (typeCode == TypeCode.SByte)
return Serializer.WriteSByte;
if (typeCode == TypeCode.Int16)
return Serializer.WriteInt16;
if (typeCode == TypeCode.UInt16)
return Serializer.WriteUInt16;
if (typeCode == TypeCode.Boolean)
return Serializer.WriteBool;
if (typeCode == TypeCode.Single)
return Serializer.WriteFloat;
if (typeCode == TypeCode.Double)
return Serializer.WriteDouble;
if (typeCode == TypeCode.Decimal)
return Serializer.WriteDecimal;
if (typeCode == TypeCode.DateTime)
if (isNullable)
return Serializer.WriteNullableDateTime;
else
return Serializer.WriteDateTime;
if (type == typeof(DateTimeOffset))
return Serializer.WriteDateTimeOffset;
if (type == typeof(DateTimeOffset?))
return Serializer.WriteNullableDateTimeOffset;
if (type == typeof(TimeSpan))
return Serializer.WriteTimeSpan;
if (type == typeof(TimeSpan?))
return Serializer.WriteNullableTimeSpan;
if (type == typeof(Guid))
return Serializer.WriteGuid;
if (type == typeof(Guid?))
return Serializer.WriteNullableGuid;
}
else
{
if (underlyingType.IsEnum)
{
return Serializer.WriteEnum;
}
}
if (type.HasInterface(typeof(IFormattable)))
return Serializer.WriteFormattableObjectString;
if (type.HasInterface(typeof(IValueWriter)))
return WriteValue;
return Serializer.WriteObjectString;
}
public WriteObjectDelegate GetWriteFn<T>()
{
if (typeof(T) == typeof(string))
{
return Serializer.WriteObjectString;
}
WriteObjectDelegate ret = null;
var onSerializingFn = JsConfig<T>.OnSerializingFn;
if (onSerializingFn != null)
{
var writeFn = GetCoreWriteFn<T>();
ret = (w, x) => writeFn(w, onSerializingFn((T)x));
}
if (JsConfig<T>.HasSerializeFn)
{
ret = JsConfig<T>.WriteFn<TSerializer>;
}
if (ret == null)
{
ret = GetCoreWriteFn<T>();
}
var onSerializedFn = JsConfig<T>.OnSerializedFn;
if (onSerializedFn != null)
{
var writerFunc = ret;
ret = (w, x) =>
{
writerFunc(w, x);
onSerializedFn((T)x);
};
}
return ret;
}
public void WriteValue(TextWriter writer, object value)
{
var valueWriter = (IValueWriter)value;
valueWriter.WriteTo(Serializer, writer);
}
private WriteObjectDelegate GetCoreWriteFn<T>()
{
if (typeof(T).IsValueType && !JsConfig.TreatAsRefType(typeof(T)) || JsConfig<T>.HasSerializeFn)
{
return JsConfig<T>.HasSerializeFn
? JsConfig<T>.WriteFn<TSerializer>
: GetValueTypeToStringMethod(typeof(T));
}
var specialWriteFn = GetSpecialWriteFn(typeof(T));
if (specialWriteFn != null)
{
return specialWriteFn;
}
if (typeof(T).IsArray)
{
if (typeof(T) == typeof(byte[]))
return (w, x) => WriteLists.WriteBytes(Serializer, w, x);
if (typeof(T) == typeof(string[]))
return (w, x) => WriteLists.WriteStringArray(Serializer, w, x);
if (typeof(T) == typeof(int[]))
return WriteListsOfElements<int, TSerializer>.WriteGenericArrayValueType;
if (typeof(T) == typeof(long[]))
return WriteListsOfElements<long, TSerializer>.WriteGenericArrayValueType;
var elementType = typeof(T).GetElementType();
var writeFn = WriteListsOfElements<TSerializer>.GetGenericWriteArray(elementType);
return writeFn;
}
if (typeof(T).HasGenericType() ||
typeof(T).HasInterface(typeof(IDictionary<string, object>))) // is ExpandoObject?
{
if (typeof(T).IsOrHasGenericInterfaceTypeOf(typeof(IList<>)))
return WriteLists<T, TSerializer>.Write;
var mapInterface = typeof(T).GetTypeWithGenericTypeDefinitionOf(typeof(IDictionary<,>));
if (mapInterface != null)
{
var mapTypeArgs = mapInterface.GetGenericArguments();
var writeFn = WriteDictionary<TSerializer>.GetWriteGenericDictionary(
mapTypeArgs[0], mapTypeArgs[1]);
var keyWriteFn = Serializer.GetWriteFn(mapTypeArgs[0]);
var valueWriteFn = typeof(JsonObject).IsAssignableFrom(typeof(T))
? JsonObject.WriteValue
: Serializer.GetWriteFn(mapTypeArgs[1]);
return (w, x) => writeFn(w, x, keyWriteFn, valueWriteFn);
}
}
var enumerableInterface = typeof(T).GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>));
if (enumerableInterface != null)
{
var elementType = enumerableInterface.GetGenericArguments()[0];
var writeFn = WriteListsOfElements<TSerializer>.GetGenericWriteEnumerable(elementType);
return writeFn;
}
var isDictionary = typeof(T) != typeof(IEnumerable) && typeof(T) != typeof(ICollection)
&& (typeof(T).IsAssignableFrom(typeof(IDictionary)) || typeof(T).HasInterface(typeof(IDictionary)));
if (isDictionary)
{
return WriteDictionary<TSerializer>.WriteIDictionary;
}
var isEnumerable = typeof(T).IsAssignableFrom(typeof(IEnumerable))
|| typeof(T).HasInterface(typeof(IEnumerable));
if (isEnumerable)
{
return WriteListsOfElements<TSerializer>.WriteIEnumerable;
}
if (typeof(T).HasInterface(typeof(IValueWriter)))
return WriteValue;
if (typeof(T).IsClass || typeof(T).IsInterface || JsConfig.TreatAsRefType(typeof(T)))
{
var typeToStringMethod = WriteType<T, TSerializer>.Write;
if (typeToStringMethod != null)
{
return typeToStringMethod;
}
}
return Serializer.WriteBuiltIn;
}
public readonly Dictionary<Type, WriteObjectDelegate> SpecialTypes;
public WriteObjectDelegate GetSpecialWriteFn(Type type)
{
if (SpecialTypes.TryGetValue(type, out var writeFn))
return writeFn;
if (type.IsInstanceOfType(typeof(Type)))
return WriteType;
if (type.IsInstanceOf(typeof(Exception)))
return Serializer.WriteException;
return null;
}
public void WriteType(TextWriter writer, object value)
{
Serializer.WriteRawString(writer, JsConfig.TypeWriter((Type)value));
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
public static void InitAot<T>()
{
WriteListsOfElements<T, TSerializer>.WriteList(null, null);
WriteListsOfElements<T, TSerializer>.WriteIList(null, null);
WriteListsOfElements<T, TSerializer>.WriteEnumerable(null, null);
WriteListsOfElements<T, TSerializer>.WriteListValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteIListValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteGenericArrayValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteArray(null, null);
TranslateListWithElements<T>.LateBoundTranslateToGenericICollection(null, null);
TranslateListWithConvertibleElements<T, T>.LateBoundTranslateToGenericICollection(null, null);
QueryStringWriter<T>.WriteObject(null, null);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RuntimeConfigurationRecord.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration {
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Xml;
using System.Net;
using System.Configuration.Internal;
using Assembly = System.Reflection.Assembly;
using System.Diagnostics.CodeAnalysis;
internal sealed class RuntimeConfigurationRecord : BaseConfigurationRecord {
static internal IInternalConfigRecord Create(
InternalConfigRoot configRoot,
IInternalConfigRecord parent,
string configPath) {
RuntimeConfigurationRecord configRecord = new RuntimeConfigurationRecord();
configRecord.Init(configRoot, (BaseConfigurationRecord) parent, configPath, null);
return configRecord;
}
private RuntimeConfigurationRecord() {
}
static readonly SimpleBitVector32 RuntimeClassFlags = new SimpleBitVector32(
ClassSupportsChangeNotifications
| ClassSupportsRefresh
| ClassSupportsImpersonation
| ClassSupportsRestrictedPermissions
| ClassSupportsDelayedInit);
override protected SimpleBitVector32 ClassFlags {
get {
return RuntimeClassFlags;
}
}
// Create the factory that will evaluate configuration
override protected object CreateSectionFactory(FactoryRecord factoryRecord) {
return new RuntimeConfigurationFactory(this, factoryRecord);
}
// parentConfig contains the config that we'd merge with.
override protected object CreateSection(bool inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentConfig, ConfigXmlReader reader) {
// Get the factory used to create a section.
RuntimeConfigurationFactory factory = (RuntimeConfigurationFactory) factoryRecord.Factory;
// Use the factory to create a section.
object config = factory.CreateSection(inputIsTrusted, this, factoryRecord, sectionRecord, parentConfig, reader);
return config;
}
override protected object UseParentResult(string configKey, object parentResult, SectionRecord sectionRecord) {
return parentResult;
}
// Ignore user code on the stack
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private object GetRuntimeObjectWithFullTrust(ConfigurationSection section) {
return section.GetRuntimeObject();
}
[SuppressMessage("Microsoft.Security", "CA2107:ReviewDenyAndPermitOnlyUsage", Justification = "This PermitOnly is meant to protect unassuming handlers from malicious callers by undoing any asserts we have put on the stack.")]
private object GetRuntimeObjectWithRestrictedPermissions(ConfigurationSection section) {
// Run configuration section handlers as if user code was on the stack
bool revertPermitOnly = false;
try {
PermissionSet permissionSet = GetRestrictedPermissions();
if (permissionSet != null) {
permissionSet.PermitOnly();
revertPermitOnly = true;
}
return section.GetRuntimeObject();
}
finally {
if (revertPermitOnly) {
CodeAccessPermission.RevertPermitOnly();
}
}
}
override protected object GetRuntimeObject(object result) {
object runtimeObject;
ConfigurationSection section = result as ConfigurationSection;
if (section == null) {
runtimeObject = result;
}
else {
// Call into config section while impersonating process or UNC identity
// so that the section could read files from disk if needed
try {
using (Impersonate()) {
// If this configRecord is trusted, ignore user code on stack
if (_flags[IsTrusted]) {
runtimeObject = GetRuntimeObjectWithFullTrust(section);
}
else {
// Run configuration section handlers as if user code was on the stack
runtimeObject = GetRuntimeObjectWithRestrictedPermissions(section);
}
}
}
catch (Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_exception_in_config_section_handler, section.SectionInformation.SectionName), e);
}
}
return runtimeObject;
}
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
protected override string CallHostDecryptSection(string encryptedXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfig) {
// Decrypt should always succeed in runtime. (VSWhidbey 429996)
// Need to override in order to Assert before calling the base class method.
return base.CallHostDecryptSection(encryptedXml, protectionProvider, protectedConfig);
}
private class RuntimeConfigurationFactory {
ConstructorInfo _sectionCtor;
IConfigurationSectionHandler _sectionHandler;
internal RuntimeConfigurationFactory(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) {
// If the factory record was defined in a trusted config record, ignore user code on stack
if (factoryRecord.IsFromTrustedConfigRecord) {
InitWithFullTrust(configRecord, factoryRecord);
}
else {
// Run configuration section handlers as if user code was on the stack
InitWithRestrictedPermissions(configRecord, factoryRecord);
}
}
private void Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) {
// Get the type of the factory
Type type = TypeUtil.GetTypeWithReflectionPermission(configRecord.Host, factoryRecord.FactoryTypeName, true);
// If the type is a ConfigurationSection, that's the type.
if (typeof(ConfigurationSection).IsAssignableFrom(type)) {
_sectionCtor = TypeUtil.GetConstructorWithReflectionPermission(type, typeof(ConfigurationSection), true);
}
else {
// Note: in v1, IConfigurationSectionHandler is in effect a factory that has a Create method
// that creates the real section object.
// throws if type does not implement IConfigurationSectionHandler
TypeUtil.VerifyAssignableType(typeof(IConfigurationSectionHandler), type, true);
// Create an instance of the handler
_sectionHandler = (IConfigurationSectionHandler) TypeUtil.CreateInstanceWithReflectionPermission(type);
}
}
// Ignore user code on the stack
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private void InitWithFullTrust(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) {
Init(configRecord, factoryRecord);
}
[SuppressMessage("Microsoft.Security", "CA2107:ReviewDenyAndPermitOnlyUsage", Justification = "This PermitOnly is meant to protect unassuming handlers from malicious callers by undoing any asserts we have put on the stack.")]
private void InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) {
// Run configuration section handlers as if user code was on the stack
bool revertPermitOnly = false;
try {
PermissionSet permissionSet = configRecord.GetRestrictedPermissions();
if (permissionSet != null) {
permissionSet.PermitOnly();
revertPermitOnly = true;
}
Init(configRecord, factoryRecord);
}
finally {
if (revertPermitOnly) {
CodeAccessPermission.RevertPermitOnly();
}
}
}
//
// Throw an exception if an attribute within a legacy section is one of our
// reserved locking attributes. We do not want admins to think they can lock
// an attribute or element within a legacy section.
//
private static void CheckForLockAttributes(string sectionName, XmlNode xmlNode) {
XmlAttributeCollection attributes = xmlNode.Attributes;
if (attributes != null) {
foreach (XmlAttribute attribute in attributes) {
if (ConfigurationElement.IsLockAttributeName(attribute.Name)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_element_locking_not_supported, sectionName), attribute);
}
}
}
foreach (XmlNode child in xmlNode.ChildNodes) {
if (xmlNode.NodeType == XmlNodeType.Element) {
CheckForLockAttributes(sectionName, child);
}
}
}
private object CreateSectionImpl(
RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord,
object parentConfig, ConfigXmlReader reader) {
object config;
if (_sectionCtor != null) {
ConfigurationSection configSection = (ConfigurationSection) TypeUtil.InvokeCtorWithReflectionPermission(_sectionCtor);
configSection.SectionInformation.SetRuntimeConfigurationInformation(configRecord, factoryRecord, sectionRecord);
configSection.CallInit();
ConfigurationSection parentSection = (ConfigurationSection) parentConfig;
configSection.Reset(parentSection);
if (reader != null) {
configSection.DeserializeSection(reader);
}
// throw if there are any cached errors
ConfigurationErrorsException errors = configSection.GetErrors();
if (errors != null) {
throw errors;
}
// don't allow changes to sections at runtime
configSection.SetReadOnly();
// reset the modified bit
configSection.ResetModified();
config = configSection;
}
else {
if (reader != null) {
XmlNode xmlNode = ErrorInfoXmlDocument.CreateSectionXmlNode(reader);
CheckForLockAttributes(factoryRecord.ConfigKey, xmlNode);
// In v1, our old section handler expects a context that contains the virtualPath from the configPath
object configContext = configRecord.Host.CreateDeprecatedConfigContext(configRecord.ConfigPath);
config = _sectionHandler.Create(parentConfig, configContext, xmlNode);
}
else {
config = null;
}
}
return config;
}
// Ignore user code on the stack
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private object CreateSectionWithFullTrust(
RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord,
object parentConfig, ConfigXmlReader reader) {
return CreateSectionImpl(configRecord, factoryRecord, sectionRecord, parentConfig, reader);
}
[SuppressMessage("Microsoft.Security", "CA2107:ReviewDenyAndPermitOnlyUsage", Justification = "This PermitOnly is meant to protect unassuming handlers from malicious callers by undoing any asserts we have put on the stack.")]
private object CreateSectionWithRestrictedPermissions(
RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord,
object parentConfig, ConfigXmlReader reader) {
// run configuration section handlers as if user code was on the stack
bool revertPermitOnly = false;
try {
PermissionSet permissionSet = configRecord.GetRestrictedPermissions();
if (permissionSet != null) {
permissionSet.PermitOnly();
revertPermitOnly = true;
}
return CreateSectionImpl(configRecord, factoryRecord, sectionRecord, parentConfig, reader);
}
finally {
if (revertPermitOnly) {
CodeAccessPermission.RevertPermitOnly();
}
}
}
internal object CreateSection(bool inputIsTrusted, RuntimeConfigurationRecord configRecord,
FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentConfig, ConfigXmlReader reader) {
if (inputIsTrusted) {
return CreateSectionWithFullTrust(configRecord, factoryRecord, sectionRecord, parentConfig, reader);
}
else {
return CreateSectionWithRestrictedPermissions(configRecord, factoryRecord, sectionRecord, parentConfig, reader);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Xml.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Xml
{
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Xsl;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Transform</i> (<b>Required: </b>Xml or XmlFile, XslTransform or XslTransformFile <b>Optional:</b> Conformance, Indent, OmitXmlDeclaration, OutputFile, TextEncoding <b>Output: </b>Output)</para>
/// <para><i>Validate</i> (<b>Required: </b>Xml or XmlFile, SchemaFiles <b>Optional: </b> TargetNamespace <b>Output: </b>IsValid, Output)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <ItemGroup>
/// <Schema Include="c:\Demo1\demo.xsd"/>
/// </ItemGroup>
/// <PropertyGroup>
/// <MyXml>
/// <![CDATA[
/// <Parent>
/// <Child1>Child1 data</Child1>
/// <Child2>Child2 data</Child2>
/// </Parent>]]>
/// </MyXml>
/// <MyXsl>
/// <![CDATA[<?xml version='1.0'?>
/// <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
/// <xsl:template match='/Parent'>
/// <Root>
/// <C1>
/// <xsl:value-of select='Child1'/>
/// </C1>
/// <C2>
/// <xsl:value-of select='Child2'/>
/// </C2>
/// </Root>
/// </xsl:template>
/// </xsl:stylesheet>]]>
/// </MyXsl>
/// <MyValidXml>
/// <![CDATA[
/// <D>
/// <Name full="Mike" type="3f3">
/// <Place>aPlace</Place>
/// </Name>
/// </D>]]>
/// </MyValidXml>
/// </PropertyGroup>
/// <!-- Validate an XmlFile -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Validate" XmlFile="c:\Demo1\demo.xml" SchemaFiles="@(Schema)">
/// <Output PropertyName="Validated" TaskParameter="IsValid"/>
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Valid File: $(Validated)"/>
/// <Message Text="Output: $(Out)"/>
/// <!-- Validate a piece of Xml -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Validate" Xml="$(MyValidXml)" SchemaFiles="@(Schema)">
/// <Output PropertyName="Validated" TaskParameter="IsValid"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Valid File: $(Validated)"/>
/// <!-- Transform an Xml file with an Xslt file -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Transform" XmlFile="C:\Demo1\XmlForTransform.xml" XslTransformFile="C:\Demo1\Transform.xslt">
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Transformed Xml: $(Out)"/>
/// <!-- Transfrom a piece of Xml with an Xslt file -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Transform" Xml="$(MyXml)" XslTransformFile="C:\Demo1\Transform.xslt">
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Transformed Xml: $(Out)"/>
/// <!-- Transfrom a piece of Xml with a piece of Xslt and write it out to a file with indented formatting -->
/// <MSBuild.ExtensionPack.Xml.XmlTask TaskAction="Transform" Xml="$(MyXml)" XslTransform="$(MyXsl)" OutputFile="C:\newxml.xml" Indent="true">
/// <Output PropertyName="Out" TaskParameter="Output"/>
/// </MSBuild.ExtensionPack.Xml.XmlTask>
/// <Message Text="Transformed Xml: $(Out)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
[HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/3d383fd0-d8a7-4b93-3e03-39b48456dac1.htm")]
public class XmlTask : BaseTask
{
private const string TransformTaskAction = "Transform";
private const string ValidateTaskAction = "Validate";
private string targetNamespace = string.Empty;
private XDocument xmlDoc;
private Encoding fileEncoding = Encoding.UTF8;
private ConformanceLevel conformanceLevel;
[DropdownValue(TransformTaskAction)]
[DropdownValue(ValidateTaskAction)]
public override string TaskAction
{
get { return base.TaskAction; }
set { base.TaskAction = value; }
}
/// <summary>
/// Sets the XmlFile
/// </summary>
[TaskAction(TransformTaskAction, false)]
[TaskAction(ValidateTaskAction, false)]
public string XmlFile { get; set; }
/// <summary>
/// Sets the XslTransformFile
/// </summary>
[TaskAction(TransformTaskAction, false)]
public string XslTransformFile { get; set; }
/// <summary>
/// Sets the XmlFile
/// </summary>
[TaskAction(TransformTaskAction, false)]
[TaskAction(ValidateTaskAction, false)]
public string Xml { get; set; }
/// <summary>
/// Sets the XslTransformFile
/// </summary>
[TaskAction(TransformTaskAction, false)]
public string XslTransform { get; set; }
/// <summary>
/// Sets the OutputFile
/// </summary>
[TaskAction(TransformTaskAction, false)]
public string OutputFile { get; set; }
/// <summary>
/// Sets the TargetNamespace for Validate. Default is ""
/// </summary>
[TaskAction(ValidateTaskAction, false)]
public string TargetNamespace
{
get { return this.targetNamespace; }
set { this.targetNamespace = value; }
}
/// <summary>
/// Sets the Schema Files collection
/// </summary>
[TaskAction(ValidateTaskAction, true)]
public ITaskItem[] SchemaFiles { get; set; }
/// <summary>
/// Set the OmitXmlDeclaration option for TransForm. Default is False
/// </summary>
[TaskAction(TransformTaskAction, false)]
public bool OmitXmlDeclaration { get; set; }
/// <summary>
/// Set the Indent option for TransForm. Default is False
/// </summary>
[TaskAction(TransformTaskAction, false)]
public bool Indent { get; set; }
/// <summary>
/// Set the Encoding option for TransForm. Default is UTF8
/// </summary>
[TaskAction(TransformTaskAction, false)]
public string TextEncoding
{
get { return this.fileEncoding.ToString(); }
set { this.fileEncoding = System.Text.Encoding.GetEncoding(value); }
}
/// <summary>
/// Sets the ConformanceLevel. Supports Auto, Document and Fragment. Default is ConformanceLevel.Document
/// </summary>
public string Conformance
{
get { return this.conformanceLevel.ToString(); }
set { this.conformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), value); }
}
/// <summary>
/// Gets whether an XmlFile is valid xml
/// </summary>
[Output]
[TaskAction(ValidateTaskAction, false)]
public bool IsValid { get; set; }
/// <summary>
/// Get the Output
/// </summary>
[Output]
[TaskAction(ValidateTaskAction, false)]
[TaskAction(TransformTaskAction, false)]
public string Output { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (!this.TargetingLocalMachine())
{
return;
}
if (!string.IsNullOrEmpty(this.XmlFile) && !File.Exists(this.XmlFile))
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "XmlFile not found: {0}", this.XmlFile));
return;
}
if (!string.IsNullOrEmpty(this.XmlFile))
{
// Load the XmlFile
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading XmlFile: {0}", this.XmlFile));
this.xmlDoc = XDocument.Load(this.XmlFile);
}
else if (!string.IsNullOrEmpty(this.Xml))
{
// Load the Xml
this.LogTaskMessage(MessageImportance.Low, "Loading Xml");
using (StringReader sr = new StringReader(this.Xml))
{
this.xmlDoc = XDocument.Load(sr);
}
}
else
{
this.Log.LogError("Xml or XmlFile must be specified");
return;
}
switch (this.TaskAction)
{
case TransformTaskAction:
this.Transform();
break;
case ValidateTaskAction:
this.Validate();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private void Transform()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Transforming: {0}", this.XmlFile));
XDocument xslDoc;
if (!string.IsNullOrEmpty(this.XslTransformFile) && !File.Exists(this.XslTransformFile))
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "XslTransformFile not found: {0}", this.XslTransformFile));
return;
}
if (!string.IsNullOrEmpty(this.XslTransformFile))
{
// Load the XslTransformFile
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading XslTransformFile: {0}", this.XslTransformFile));
xslDoc = XDocument.Load(this.XslTransformFile);
}
else if (!string.IsNullOrEmpty(this.XslTransform))
{
// Load the XslTransform
this.LogTaskMessage(MessageImportance.Low, "Loading XslTransform");
using (StringReader sr = new StringReader(this.XslTransform))
{
xslDoc = XDocument.Load(sr);
}
}
else
{
this.Log.LogError("XslTransform or XslTransformFile must be specified");
return;
}
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
XsltSettings settings = new XsltSettings { EnableScript = true };
using (StringReader sr = new StringReader(xslDoc.ToString()))
{
xslt.Load(XmlReader.Create(sr), settings, null);
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder, xslt.OutputSettings))
{
this.LogTaskMessage(MessageImportance.Low, "Running XslTransform");
// Execute the transform and output the results to a writer.
xslt.Transform(this.xmlDoc.CreateReader(), writer);
}
this.Output = builder.ToString();
}
if (!string.IsNullOrEmpty(this.OutputFile))
{
if (xslt.OutputSettings.OutputMethod == XmlOutputMethod.Text)
{
this.LogTaskMessage(MessageImportance.Low, "Writing using text method");
using (FileStream stream = new FileStream(this.OutputFile, FileMode.Create))
{
StreamWriter streamWriter = null;
try
{
streamWriter = new StreamWriter(stream, Encoding.Default);
// Output the results to a writer.
streamWriter.Write(this.Output);
}
finally
{
if (streamWriter != null)
{
streamWriter.Close();
}
}
}
}
else
{
this.LogTaskMessage(MessageImportance.Low, "Writing using XML method");
using (StringReader sr = new StringReader(this.Output))
{
XDocument newxmlDoc = XDocument.Load(sr);
if (!string.IsNullOrEmpty(this.OutputFile))
{
XmlWriterSettings writerSettings = new XmlWriterSettings { ConformanceLevel = this.conformanceLevel, Encoding = this.fileEncoding, Indent = this.Indent, OmitXmlDeclaration = this.OmitXmlDeclaration, CloseOutput = true };
using (XmlWriter xw = XmlWriter.Create(this.OutputFile, writerSettings))
{
if (xw != null)
{
newxmlDoc.WriteTo(xw);
}
else
{
Log.LogError("There was an error creating the XmlWriter for the OutputFile");
return;
}
}
}
}
}
}
}
private void Validate()
{
this.LogTaskMessage(!string.IsNullOrEmpty(this.XmlFile) ? string.Format(CultureInfo.CurrentCulture, "Validating: {0}", this.XmlFile) : "Validating Xml");
XmlSchemaSet schemas = new XmlSchemaSet();
foreach (ITaskItem i in this.SchemaFiles)
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading SchemaFile: {0}", i.ItemSpec));
schemas.Add(this.TargetNamespace, i.ItemSpec);
}
bool errorEncountered = false;
this.xmlDoc.Validate(
schemas,
(o, e) =>
{
this.Output += e.Message;
this.LogTaskWarning(string.Format(CultureInfo.InvariantCulture, "{0}", e.Message));
errorEncountered = true;
});
this.IsValid = errorEncountered ? false : true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using OmniSharp.Models.V2;
using OmniSharp.Roslyn.Utilities;
using OmniSharp.Utilities;
namespace OmniSharp.Extensions
{
public static class SymbolExtensions
{
private static readonly SymbolDisplayFormat NameFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface,
parameterOptions:
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private readonly static CachedStringBuilder s_cachedBuilder;
public static string ToNameDisplayString(this ISymbol symbol)
{
return symbol.ToDisplayString(NameFormat);
}
public static INamedTypeSymbol GetContainingTypeOrThis(this ISymbol symbol)
{
if (symbol is INamedTypeSymbol namedType)
{
return namedType;
}
return symbol.ContainingType;
}
public static string GetMetadataName(this ISymbol symbol)
{
if (symbol == null)
{
throw new ArgumentNullException(nameof(symbol));
}
var symbols = new Stack<ISymbol>();
while (symbol != null)
{
if (symbol.Kind == SymbolKind.Assembly ||
symbol.Kind == SymbolKind.NetModule)
{
break;
}
if ((symbol as INamespaceSymbol)?.IsGlobalNamespace == true)
{
break;
}
symbols.Push(symbol);
symbol = symbol.ContainingSymbol;
}
var builder = s_cachedBuilder.Acquire();
try
{
ISymbol current = null, previous = null;
while (symbols.Count > 0)
{
current = symbols.Pop();
if (previous != null)
{
if (previous.Kind == SymbolKind.NamedType &&
current.Kind == SymbolKind.NamedType)
{
builder.Append('+');
}
else
{
builder.Append('.');
}
}
builder.Append(current.MetadataName);
previous = current;
}
return builder.ToString();
}
finally
{
s_cachedBuilder.Release(builder);
}
}
public static string GetAccessibilityString(this ISymbol symbol)
{
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
return SymbolAccessibilities.Public;
case Accessibility.Internal:
return SymbolAccessibilities.Internal;
case Accessibility.Private:
return SymbolAccessibilities.Private;
case Accessibility.Protected:
return SymbolAccessibilities.Protected;
case Accessibility.ProtectedOrInternal:
return SymbolAccessibilities.ProtectedInternal;
case Accessibility.ProtectedAndInternal:
return SymbolAccessibilities.PrivateProtected;
default:
return null;
}
}
public static string GetKindString(this ISymbol symbol)
{
switch (symbol)
{
case INamespaceSymbol _:
return SymbolKinds.Namespace;
case INamedTypeSymbol namedTypeSymbol:
return namedTypeSymbol.GetKindString();
case IMethodSymbol methodSymbol:
return methodSymbol.GetKindString();
case IFieldSymbol fieldSymbol:
return fieldSymbol.GetKindString();
case IPropertySymbol propertySymbol:
return propertySymbol.GetKindString();
case IEventSymbol _:
return SymbolKinds.Event;
default:
return SymbolKinds.Unknown;
}
}
public static string GetKindString(this INamedTypeSymbol namedTypeSymbol)
{
switch (namedTypeSymbol.TypeKind)
{
case TypeKind.Class:
return SymbolKinds.Class;
case TypeKind.Delegate:
return SymbolKinds.Delegate;
case TypeKind.Enum:
return SymbolKinds.Enum;
case TypeKind.Interface:
return SymbolKinds.Interface;
case TypeKind.Struct:
return SymbolKinds.Struct;
default:
return SymbolKinds.Unknown;
}
}
public static string GetKindString(this IMethodSymbol methodSymbol)
{
switch (methodSymbol.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.ReducedExtension:
case MethodKind.ExplicitInterfaceImplementation:
return SymbolKinds.Method;
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
return SymbolKinds.Constructor;
case MethodKind.Destructor:
return SymbolKinds.Destructor;
case MethodKind.Conversion:
case MethodKind.BuiltinOperator:
case MethodKind.UserDefinedOperator:
return SymbolKinds.Operator;
default:
return SymbolKinds.Unknown;
}
}
public static string GetKindString(this IFieldSymbol fieldSymbol)
{
if (fieldSymbol.ContainingType?.TypeKind == TypeKind.Enum &&
fieldSymbol.HasConstantValue)
{
return SymbolKinds.EnumMember;
}
return fieldSymbol.IsConst
? SymbolKinds.Constant
: SymbolKinds.Field;
}
public static string GetKindString(this IPropertySymbol propertySymbol)
{
return propertySymbol.IsIndexer
? SymbolKinds.Indexer
: SymbolKinds.Property;
}
public static bool IsOverridable(this ISymbol symbol) => symbol?.ContainingType?.TypeKind == TypeKind.Class && !symbol.IsSealed && (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride);
/// <summary>
/// Do not use this API in new OmniSharp endpoints. Use <see cref="GetKindString(ISymbol)"/> instead.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static string GetKind(this ISymbol symbol)
{
if (symbol is INamedTypeSymbol namedType)
{
return Enum.GetName(namedType.TypeKind.GetType(), namedType.TypeKind);
}
if (symbol.Kind == SymbolKind.Field &&
symbol.ContainingType?.TypeKind == TypeKind.Enum &&
symbol.Name != WellKnownMemberNames.EnumBackingFieldName)
{
return "EnumMember";
}
if ((symbol as IFieldSymbol)?.IsConst == true)
{
return "Const";
}
return Enum.GetName(symbol.Kind.GetType(), symbol.Kind);
}
internal static INamedTypeSymbol GetTopLevelContainingNamedType(this ISymbol symbol)
{
// Traverse up until we find a named type that is parented by the namespace
var topLevelNamedType = symbol;
while (!SymbolEqualityComparer.Default.Equals(topLevelNamedType.ContainingSymbol, symbol.ContainingNamespace) ||
topLevelNamedType.Kind != SymbolKind.NamedType)
{
topLevelNamedType = topLevelNamedType.ContainingSymbol;
}
return (INamedTypeSymbol)topLevelNamedType;
}
public static string GetSymbolName(this ISymbol symbol)
{
var topLevelSymbol = symbol.GetTopLevelContainingNamedType();
return GetTypeDisplayString(topLevelSymbol);
}
private static string GetTypeDisplayString(INamedTypeSymbol symbol)
{
if (symbol.SpecialType != SpecialType.None)
{
var specialType = symbol.SpecialType;
var name = Enum.GetName(typeof(SpecialType), symbol.SpecialType).Replace("_", ".");
return name;
}
if (symbol.IsGenericType)
{
symbol = symbol.ConstructUnboundGenericType();
}
if (symbol.IsUnboundGenericType)
{
// TODO: Is this the best to get the fully metadata name?
var parts = symbol.ToDisplayParts();
var filteredParts = parts.Where(x => x.Kind != SymbolDisplayPartKind.Punctuation).ToArray();
var typeName = new StringBuilder();
foreach (var part in filteredParts.Take(filteredParts.Length - 1))
{
typeName.Append(part.Symbol.Name);
typeName.Append(".");
}
typeName.Append(symbol.MetadataName);
return typeName.ToString();
}
return symbol.ToDisplayString();
}
internal static string GetFilePathForExternalSymbol(this ISymbol symbol, Project project)
{
var topLevelSymbol = symbol.GetTopLevelContainingNamedType();
return $"$metadata$/Project/{Folderize(project.Name)}/Assembly/{Folderize(topLevelSymbol.ContainingAssembly.Name)}/Symbol/{Folderize(GetTypeDisplayString(topLevelSymbol))}.cs".Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
private static string Folderize(string path) => string.Join("/", path.Split('.'));
public static bool IsInterfaceType(this ISymbol symbol) => (symbol as ITypeSymbol)?.IsInterfaceType() == true;
public static bool IsInterfaceType(this ITypeSymbol symbol) => symbol?.TypeKind == TypeKind.Interface;
public static bool IsImplementableMember(this ISymbol symbol)
{
if (symbol?.ContainingType?.TypeKind == TypeKind.Interface)
{
if (symbol.Kind == SymbolKind.Event)
{
return true;
}
if (symbol.Kind == SymbolKind.Property)
{
return true;
}
if (symbol.Kind == SymbolKind.Method)
{
var methodSymbol = (IMethodSymbol)symbol;
if (methodSymbol.MethodKind == MethodKind.Ordinary ||
methodSymbol.MethodKind == MethodKind.PropertyGet ||
methodSymbol.MethodKind == MethodKind.PropertySet)
{
return true;
}
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.IO;
namespace CocosSharp
{
public class CCSpriteFrameCache
{
Dictionary<string, CCSpriteFrame> spriteFrames;
Dictionary<string, string> spriteFramesAliases;
#region Properties
public static CCSpriteFrameCache SharedSpriteFrameCache { get; internal set; }
// When false, an exception is thrown if an animation frame is overwritten.
public bool AllowFrameOverwrite { get; set; }
// Get the sprite frame for the given frame name, or as an alias for the sprite frame name.
public CCSpriteFrame this[string name]
{
get
{
CCSpriteFrame frame;
if (!spriteFrames.TryGetValue(name, out frame))
{
// try alias dictionary
string key;
if (spriteFramesAliases.TryGetValue(name, out key))
{
if (!spriteFrames.TryGetValue(key, out frame))
{
CCLog.Log("CocosSharp: CCSpriteFrameCahce: Frame '{0}' not found", name);
}
}
}
return frame;
}
}
#endregion Properties
#region Constructors
public CCSpriteFrameCache()
{
spriteFrames = new Dictionary<string, CCSpriteFrame>();
spriteFramesAliases = new Dictionary<string, string>();
}
#endregion Constructors
#region Adding frames
internal void AddSpriteFrames(PlistDictionary pobDictionary, CCTexture2D pobTexture)
{
/*
Supported Zwoptex Formats:
ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
*/
PlistDictionary metadataDict = null;
if (pobDictionary.ContainsKey("metadata"))
{
metadataDict = pobDictionary["metadata"].AsDictionary;
}
PlistDictionary framesDict = null;
if (pobDictionary.ContainsKey("frames"))
{
framesDict = pobDictionary["frames"].AsDictionary;
}
int format = 0;
// get the format
if (metadataDict != null)
{
format = metadataDict["format"].AsInt;
}
// check the format
if (format < 0 || format > 3)
{
throw (new NotSupportedException("PList format " + format + " is not supported."));
}
foreach (var pair in framesDict)
{
PlistDictionary frameDict = pair.Value.AsDictionary;
CCSpriteFrame spriteFrame = null;
if (format == 0)
{
float x=0f, y=0f, w=0f, h=0f;
x = frameDict["x"].AsFloat;
y = frameDict["y"].AsFloat;
w = frameDict["width"].AsFloat;
h = frameDict["height"].AsFloat;
float ox = 0f, oy = 0f;
ox = frameDict["offsetX"].AsFloat;
oy = frameDict["offsetY"].AsFloat;
int ow = 0, oh = 0;
ow = frameDict["originalWidth"].AsInt;
oh = frameDict["originalHeight"].AsInt;
// check ow/oh
if (ow == 0 || oh == 0)
{
CCLog.Log(
"cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist or check the 'format' metatag");
}
// abs ow/oh
ow = Math.Abs(ow);
oh = Math.Abs(oh);
// create frame
spriteFrame = new CCSpriteFrame(
new CCSize(ow, oh),
pobTexture,
new CCRect(x, y, w, h),
new CCSize(ow, oh),
false,
new CCPoint(ox, oy)
);
}
else if (format == 1 || format == 2)
{
CCRect frame = CCRect.Parse(frameDict["frame"].AsString);
bool rotated = false;
// rotation
if (format == 2)
{
if (frameDict.ContainsKey("rotated"))
{
rotated = frameDict["rotated"].AsBool;
}
}
CCPoint offset = CCPoint.Parse(frameDict["offset"].AsString);
CCSize sourceSize = CCSize.Parse (frameDict["sourceSize"].AsString);
// create frame
spriteFrame = new CCSpriteFrame(
sourceSize,
pobTexture,
frame,
sourceSize,
rotated,
offset
);
}
else if (format == 3)
{
// get values
CCSize spriteSize = CCSize.Parse (frameDict["spriteSize"].AsString);
CCPoint spriteOffset = CCPoint.Parse(frameDict["spriteOffset"].AsString);
CCSize spriteSourceSize = CCSize.Parse (frameDict["spriteSourceSize"].AsString);
CCRect textureRect = CCRect.Parse(frameDict["textureRect"].AsString);
bool textureRotated = false;
if (frameDict.ContainsKey("textureRotated"))
{
textureRotated = frameDict["textureRotated"].AsBool;
}
// get aliases
PlistArray aliases = frameDict["aliases"].AsArray;
string frameKey = pair.Key;
foreach (PlistObjectBase item2 in aliases)
{
string oneAlias = item2.AsString;
if (spriteFramesAliases.ContainsKey(oneAlias))
{
if (spriteFramesAliases[oneAlias] != null)
{
CCLog.Log("CocosSharp: WARNING: an alias with name {0} already exists", oneAlias);
}
}
if (!spriteFramesAliases.ContainsKey(oneAlias))
{
spriteFramesAliases.Add(oneAlias, frameKey);
}
}
// create frame
spriteFrame = new CCSpriteFrame(
spriteSourceSize,
pobTexture,
new CCRect(textureRect.Origin.X, textureRect.Origin.Y, spriteSize.Width, spriteSize.Height),
spriteSourceSize,
textureRotated,
spriteOffset
);
}
// add sprite frame
string key = pair.Key;
if (!AllowFrameOverwrite && spriteFrames.ContainsKey(key))
{
CCLog.Log("Frame named " + key + " already exists in the animation cache. Not overwriting existing record.");
}
else if (AllowFrameOverwrite || !spriteFrames.ContainsKey(key))
{
spriteFrames[key] = spriteFrame;
}
}
}
public void AddSpriteFrames(string plistFileName)
{
PlistDocument document = CCContentManager.SharedContentManager.Load<PlistDocument>(plistFileName);
PlistDictionary dict = document.Root.AsDictionary;
string texturePath = "";
PlistDictionary metadataDict = dict.ContainsKey("metadata") ? dict["metadata"].AsDictionary : null;
if (metadataDict != null)
{
// try to read texture file name from meta data
if (metadataDict.ContainsKey("textureFileName"))
{
texturePath = metadataDict["textureFileName"].AsString;
}
}
if (!string.IsNullOrEmpty(texturePath))
{
// build texture path relative to plist file
texturePath = CCFileUtils.FullPathFromRelativeFile(texturePath, plistFileName);
}
else
{
// build texture path by replacing file extension
texturePath = plistFileName;
// remove .xxx
texturePath = CCFileUtils.RemoveExtension(texturePath);
// append .png
texturePath = texturePath + ".png";
CCLog.Log("CocosSharp: CCSpriteFrameCache: Trying to use file {0} as texture", texturePath);
}
CCTexture2D pTexture = CCTextureCache.SharedTextureCache.AddImage(texturePath);
if (pTexture != null)
{
AddSpriteFrames(dict, pTexture);
}
else
{
CCLog.Log("CocosSharp: CCSpriteFrameCache: Couldn't load texture");
}
}
public void AddSpriteFrames(string plistFileName, string textureFileName)
{
Debug.Assert(textureFileName != null);
CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage(textureFileName);
if (texture != null)
{
AddSpriteFrames(plistFileName, texture);
}
else
{
CCLog.Log("CocosSharp: CCSpriteFrameCache: couldn't load texture file. File not found {0}", textureFileName);
}
}
public void AddSpriteFrames(Stream plist, CCTexture2D pobTexture)
{
PlistDocument document = new PlistDocument();
try
{
document.LoadFromXmlFile(plist);
}
catch (Exception)
{
throw (new Microsoft.Xna.Framework.Content.ContentLoadException("Failed to load the particle definition file from stream"));
}
PlistDictionary dict = document.Root.AsDictionary;
AddSpriteFrames(dict, pobTexture);
}
public void AddSpriteFrames(string plistFileName, CCTexture2D pobTexture)
{
PlistDocument document = CCContentManager.SharedContentManager.Load<PlistDocument>(plistFileName);
PlistDictionary dict = document.Root.AsDictionary;
AddSpriteFrames(dict, pobTexture);
}
public void AddSpriteFrame(CCSpriteFrame frame, string frameName)
{
if (!AllowFrameOverwrite && spriteFrames.ContainsKey(frameName))
{
throw (new ArgumentException("The frame named " + frameName + " already exists."));
}
spriteFrames[frameName] = frame;
}
#endregion Adding frames
#region Removing frames
public void RemoveSpriteFrames()
{
spriteFrames.Clear();
spriteFramesAliases.Clear();
}
public void RemoveUnusedSpriteFrames()
{
if (spriteFrames.Count > 0)
{
var tmp = new Dictionary<string, WeakReference>();
foreach (var pair in spriteFrames)
{
tmp.Add(pair.Key, new WeakReference(pair.Value));
}
spriteFrames.Clear();
GC.Collect();
foreach (var pair in tmp)
{
if (pair.Value.IsAlive)
{
spriteFrames.Add(pair.Key, (CCSpriteFrame) pair.Value.Target);
}
}
}
}
public void RemoveSpriteFrame(string frameName)
{
// explicit nil handling
if (string.IsNullOrEmpty(frameName))
{
return;
}
// Is this an alias ?
string key = string.Empty;
spriteFramesAliases.TryGetValue(frameName, out key);
if (!string.IsNullOrEmpty(key))
{
spriteFrames.Remove(key);
spriteFramesAliases.Remove(key);
}
else
{
spriteFrames.Remove(frameName);
}
}
public void RemoveSpriteFrames(string plistFileName)
{
PlistDocument document = CCContentManager.SharedContentManager.Load<PlistDocument>(plistFileName);
PlistDictionary dict = document.Root.AsDictionary;
RemoveSpriteFrames(dict);
}
public void RemoveSpriteFrames(PlistDictionary dictionary)
{
PlistDictionary framesDict = dictionary["frames"].AsDictionary;
var keysToRemove = new List<string>();
foreach (var pair in framesDict)
{
if (spriteFrames.ContainsKey(pair.Key))
{
keysToRemove.Add(pair.Key);
}
}
foreach (string key in keysToRemove)
{
spriteFrames.Remove(key);
}
}
public void RemoveSpriteFrames(CCTexture2D texture)
{
var keysToRemove = new List<string>();
foreach (string key in spriteFrames.Keys)
{
CCSpriteFrame frame = spriteFrames[key];
if (frame != null && (frame.Texture.Name == texture.Name))
{
keysToRemove.Add(key);
}
}
foreach (string key in keysToRemove)
{
spriteFrames.Remove(key);
}
}
#endregion Removing frames
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by wsdl, Version=2.0.50727.42.
//
namespace WebsitePanel.Providers.SharePoint
{
using System.Diagnostics;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Xml.Serialization;
using WebsitePanel.Providers.OS;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name = "SharePointServerSoap", Namespace = "http://smbsaas/websitepanel/server/")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(ServiceProviderItem))]
public partial class SharePointServer : Microsoft.Web.Services3.WebServicesClientProtocol
{
public ServiceProviderSettingsSoapHeader ServiceProviderSettingsSoapHeaderValue;
private System.Threading.SendOrPostCallback ExtendVirtualServerOperationCompleted;
private System.Threading.SendOrPostCallback UnextendVirtualServerOperationCompleted;
private System.Threading.SendOrPostCallback BackupVirtualServerOperationCompleted;
private System.Threading.SendOrPostCallback RestoreVirtualServerOperationCompleted;
private System.Threading.SendOrPostCallback GetTempFileBinaryChunkOperationCompleted;
private System.Threading.SendOrPostCallback AppendTempFileBinaryChunkOperationCompleted;
private System.Threading.SendOrPostCallback GetInstalledWebPartsOperationCompleted;
private System.Threading.SendOrPostCallback InstallWebPartsPackageOperationCompleted;
private System.Threading.SendOrPostCallback DeleteWebPartsPackageOperationCompleted;
private System.Threading.SendOrPostCallback UserExistsOperationCompleted;
private System.Threading.SendOrPostCallback GetUsersOperationCompleted;
private System.Threading.SendOrPostCallback GetUserOperationCompleted;
private System.Threading.SendOrPostCallback CreateUserOperationCompleted;
private System.Threading.SendOrPostCallback UpdateUserOperationCompleted;
private System.Threading.SendOrPostCallback ChangeUserPasswordOperationCompleted;
private System.Threading.SendOrPostCallback DeleteUserOperationCompleted;
private System.Threading.SendOrPostCallback GroupExistsOperationCompleted;
private System.Threading.SendOrPostCallback GetGroupsOperationCompleted;
private System.Threading.SendOrPostCallback GetGroupOperationCompleted;
private System.Threading.SendOrPostCallback CreateGroupOperationCompleted;
private System.Threading.SendOrPostCallback UpdateGroupOperationCompleted;
private System.Threading.SendOrPostCallback DeleteGroupOperationCompleted;
/// <remarks/>
public SharePointServer()
{
this.Url = "http://localhost/WebsitePanelServer11/SharePointServer.asmx";
}
/// <remarks/>
public event ExtendVirtualServerCompletedEventHandler ExtendVirtualServerCompleted;
/// <remarks/>
public event UnextendVirtualServerCompletedEventHandler UnextendVirtualServerCompleted;
/// <remarks/>
public event BackupVirtualServerCompletedEventHandler BackupVirtualServerCompleted;
/// <remarks/>
public event RestoreVirtualServerCompletedEventHandler RestoreVirtualServerCompleted;
/// <remarks/>
public event GetTempFileBinaryChunkCompletedEventHandler GetTempFileBinaryChunkCompleted;
/// <remarks/>
public event AppendTempFileBinaryChunkCompletedEventHandler AppendTempFileBinaryChunkCompleted;
/// <remarks/>
public event GetInstalledWebPartsCompletedEventHandler GetInstalledWebPartsCompleted;
/// <remarks/>
public event InstallWebPartsPackageCompletedEventHandler InstallWebPartsPackageCompleted;
/// <remarks/>
public event DeleteWebPartsPackageCompletedEventHandler DeleteWebPartsPackageCompleted;
/// <remarks/>
public event UserExistsCompletedEventHandler UserExistsCompleted;
/// <remarks/>
public event GetUsersCompletedEventHandler GetUsersCompleted;
/// <remarks/>
public event GetUserCompletedEventHandler GetUserCompleted;
/// <remarks/>
public event CreateUserCompletedEventHandler CreateUserCompleted;
/// <remarks/>
public event UpdateUserCompletedEventHandler UpdateUserCompleted;
/// <remarks/>
public event ChangeUserPasswordCompletedEventHandler ChangeUserPasswordCompleted;
/// <remarks/>
public event DeleteUserCompletedEventHandler DeleteUserCompleted;
/// <remarks/>
public event GroupExistsCompletedEventHandler GroupExistsCompleted;
/// <remarks/>
public event GetGroupsCompletedEventHandler GetGroupsCompleted;
/// <remarks/>
public event GetGroupCompletedEventHandler GetGroupCompleted;
/// <remarks/>
public event CreateGroupCompletedEventHandler CreateGroupCompleted;
/// <remarks/>
public event UpdateGroupCompletedEventHandler UpdateGroupCompleted;
/// <remarks/>
public event DeleteGroupCompletedEventHandler DeleteGroupCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/ExtendVirtualServer", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void ExtendVirtualServer(SharePointSite site)
{
this.Invoke("ExtendVirtualServer", new object[] {
site});
}
/// <remarks/>
public System.IAsyncResult BeginExtendVirtualServer(SharePointSite site, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("ExtendVirtualServer", new object[] {
site}, callback, asyncState);
}
/// <remarks/>
public void EndExtendVirtualServer(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void ExtendVirtualServerAsync(SharePointSite site)
{
this.ExtendVirtualServerAsync(site, null);
}
/// <remarks/>
public void ExtendVirtualServerAsync(SharePointSite site, object userState)
{
if ((this.ExtendVirtualServerOperationCompleted == null))
{
this.ExtendVirtualServerOperationCompleted = new System.Threading.SendOrPostCallback(this.OnExtendVirtualServerOperationCompleted);
}
this.InvokeAsync("ExtendVirtualServer", new object[] {
site}, this.ExtendVirtualServerOperationCompleted, userState);
}
private void OnExtendVirtualServerOperationCompleted(object arg)
{
if ((this.ExtendVirtualServerCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.ExtendVirtualServerCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UnextendVirtualServer", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void UnextendVirtualServer(string url, bool deleteContent)
{
this.Invoke("UnextendVirtualServer", new object[] {
url,
deleteContent});
}
/// <remarks/>
public System.IAsyncResult BeginUnextendVirtualServer(string url, bool deleteContent, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("UnextendVirtualServer", new object[] {
url,
deleteContent}, callback, asyncState);
}
/// <remarks/>
public void EndUnextendVirtualServer(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void UnextendVirtualServerAsync(string url, bool deleteContent)
{
this.UnextendVirtualServerAsync(url, deleteContent, null);
}
/// <remarks/>
public void UnextendVirtualServerAsync(string url, bool deleteContent, object userState)
{
if ((this.UnextendVirtualServerOperationCompleted == null))
{
this.UnextendVirtualServerOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUnextendVirtualServerOperationCompleted);
}
this.InvokeAsync("UnextendVirtualServer", new object[] {
url,
deleteContent}, this.UnextendVirtualServerOperationCompleted, userState);
}
private void OnUnextendVirtualServerOperationCompleted(object arg)
{
if ((this.UnextendVirtualServerCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.UnextendVirtualServerCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/BackupVirtualServer", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string BackupVirtualServer(string url, string fileName, bool zipBackup)
{
object[] results = this.Invoke("BackupVirtualServer", new object[] {
url,
fileName,
zipBackup});
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginBackupVirtualServer(string url, string fileName, bool zipBackup, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("BackupVirtualServer", new object[] {
url,
fileName,
zipBackup}, callback, asyncState);
}
/// <remarks/>
public string EndBackupVirtualServer(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
/// <remarks/>
public void BackupVirtualServerAsync(string url, string fileName, bool zipBackup)
{
this.BackupVirtualServerAsync(url, fileName, zipBackup, null);
}
/// <remarks/>
public void BackupVirtualServerAsync(string url, string fileName, bool zipBackup, object userState)
{
if ((this.BackupVirtualServerOperationCompleted == null))
{
this.BackupVirtualServerOperationCompleted = new System.Threading.SendOrPostCallback(this.OnBackupVirtualServerOperationCompleted);
}
this.InvokeAsync("BackupVirtualServer", new object[] {
url,
fileName,
zipBackup}, this.BackupVirtualServerOperationCompleted, userState);
}
private void OnBackupVirtualServerOperationCompleted(object arg)
{
if ((this.BackupVirtualServerCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.BackupVirtualServerCompleted(this, new BackupVirtualServerCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/RestoreVirtualServer", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void RestoreVirtualServer(string url, string fileName)
{
this.Invoke("RestoreVirtualServer", new object[] {
url,
fileName});
}
/// <remarks/>
public System.IAsyncResult BeginRestoreVirtualServer(string url, string fileName, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("RestoreVirtualServer", new object[] {
url,
fileName}, callback, asyncState);
}
/// <remarks/>
public void EndRestoreVirtualServer(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void RestoreVirtualServerAsync(string url, string fileName)
{
this.RestoreVirtualServerAsync(url, fileName, null);
}
/// <remarks/>
public void RestoreVirtualServerAsync(string url, string fileName, object userState)
{
if ((this.RestoreVirtualServerOperationCompleted == null))
{
this.RestoreVirtualServerOperationCompleted = new System.Threading.SendOrPostCallback(this.OnRestoreVirtualServerOperationCompleted);
}
this.InvokeAsync("RestoreVirtualServer", new object[] {
url,
fileName}, this.RestoreVirtualServerOperationCompleted, userState);
}
private void OnRestoreVirtualServerOperationCompleted(object arg)
{
if ((this.RestoreVirtualServerCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.RestoreVirtualServerCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetTempFileBinaryChunk", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")]
public byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
object[] results = this.Invoke("GetTempFileBinaryChunk", new object[] {
path,
offset,
length});
return ((byte[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetTempFileBinaryChunk(string path, int offset, int length, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetTempFileBinaryChunk", new object[] {
path,
offset,
length}, callback, asyncState);
}
/// <remarks/>
public byte[] EndGetTempFileBinaryChunk(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((byte[])(results[0]));
}
/// <remarks/>
public void GetTempFileBinaryChunkAsync(string path, int offset, int length)
{
this.GetTempFileBinaryChunkAsync(path, offset, length, null);
}
/// <remarks/>
public void GetTempFileBinaryChunkAsync(string path, int offset, int length, object userState)
{
if ((this.GetTempFileBinaryChunkOperationCompleted == null))
{
this.GetTempFileBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetTempFileBinaryChunkOperationCompleted);
}
this.InvokeAsync("GetTempFileBinaryChunk", new object[] {
path,
offset,
length}, this.GetTempFileBinaryChunkOperationCompleted, userState);
}
private void OnGetTempFileBinaryChunkOperationCompleted(object arg)
{
if ((this.GetTempFileBinaryChunkCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetTempFileBinaryChunkCompleted(this, new GetTempFileBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/AppendTempFileBinaryChunk", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string AppendTempFileBinaryChunk(string fileName, string path, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] chunk)
{
object[] results = this.Invoke("AppendTempFileBinaryChunk", new object[] {
fileName,
path,
chunk});
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginAppendTempFileBinaryChunk(string fileName, string path, byte[] chunk, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("AppendTempFileBinaryChunk", new object[] {
fileName,
path,
chunk}, callback, asyncState);
}
/// <remarks/>
public string EndAppendTempFileBinaryChunk(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
/// <remarks/>
public void AppendTempFileBinaryChunkAsync(string fileName, string path, byte[] chunk)
{
this.AppendTempFileBinaryChunkAsync(fileName, path, chunk, null);
}
/// <remarks/>
public void AppendTempFileBinaryChunkAsync(string fileName, string path, byte[] chunk, object userState)
{
if ((this.AppendTempFileBinaryChunkOperationCompleted == null))
{
this.AppendTempFileBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAppendTempFileBinaryChunkOperationCompleted);
}
this.InvokeAsync("AppendTempFileBinaryChunk", new object[] {
fileName,
path,
chunk}, this.AppendTempFileBinaryChunkOperationCompleted, userState);
}
private void OnAppendTempFileBinaryChunkOperationCompleted(object arg)
{
if ((this.AppendTempFileBinaryChunkCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.AppendTempFileBinaryChunkCompleted(this, new AppendTempFileBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetInstalledWebParts", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string[] GetInstalledWebParts(string url)
{
object[] results = this.Invoke("GetInstalledWebParts", new object[] {
url});
return ((string[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetInstalledWebParts(string url, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetInstalledWebParts", new object[] {
url}, callback, asyncState);
}
/// <remarks/>
public string[] EndGetInstalledWebParts(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string[])(results[0]));
}
/// <remarks/>
public void GetInstalledWebPartsAsync(string url)
{
this.GetInstalledWebPartsAsync(url, null);
}
/// <remarks/>
public void GetInstalledWebPartsAsync(string url, object userState)
{
if ((this.GetInstalledWebPartsOperationCompleted == null))
{
this.GetInstalledWebPartsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetInstalledWebPartsOperationCompleted);
}
this.InvokeAsync("GetInstalledWebParts", new object[] {
url}, this.GetInstalledWebPartsOperationCompleted, userState);
}
private void OnGetInstalledWebPartsOperationCompleted(object arg)
{
if ((this.GetInstalledWebPartsCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetInstalledWebPartsCompleted(this, new GetInstalledWebPartsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/InstallWebPartsPackage", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void InstallWebPartsPackage(string url, string packageName)
{
this.Invoke("InstallWebPartsPackage", new object[] {
url,
packageName});
}
/// <remarks/>
public System.IAsyncResult BeginInstallWebPartsPackage(string url, string packageName, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("InstallWebPartsPackage", new object[] {
url,
packageName}, callback, asyncState);
}
/// <remarks/>
public void EndInstallWebPartsPackage(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void InstallWebPartsPackageAsync(string url, string packageName)
{
this.InstallWebPartsPackageAsync(url, packageName, null);
}
/// <remarks/>
public void InstallWebPartsPackageAsync(string url, string packageName, object userState)
{
if ((this.InstallWebPartsPackageOperationCompleted == null))
{
this.InstallWebPartsPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnInstallWebPartsPackageOperationCompleted);
}
this.InvokeAsync("InstallWebPartsPackage", new object[] {
url,
packageName}, this.InstallWebPartsPackageOperationCompleted, userState);
}
private void OnInstallWebPartsPackageOperationCompleted(object arg)
{
if ((this.InstallWebPartsPackageCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.InstallWebPartsPackageCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteWebPartsPackage", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void DeleteWebPartsPackage(string url, string packageName)
{
this.Invoke("DeleteWebPartsPackage", new object[] {
url,
packageName});
}
/// <remarks/>
public System.IAsyncResult BeginDeleteWebPartsPackage(string url, string packageName, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("DeleteWebPartsPackage", new object[] {
url,
packageName}, callback, asyncState);
}
/// <remarks/>
public void EndDeleteWebPartsPackage(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void DeleteWebPartsPackageAsync(string url, string packageName)
{
this.DeleteWebPartsPackageAsync(url, packageName, null);
}
/// <remarks/>
public void DeleteWebPartsPackageAsync(string url, string packageName, object userState)
{
if ((this.DeleteWebPartsPackageOperationCompleted == null))
{
this.DeleteWebPartsPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteWebPartsPackageOperationCompleted);
}
this.InvokeAsync("DeleteWebPartsPackage", new object[] {
url,
packageName}, this.DeleteWebPartsPackageOperationCompleted, userState);
}
private void OnDeleteWebPartsPackageOperationCompleted(object arg)
{
if ((this.DeleteWebPartsPackageCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteWebPartsPackageCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UserExists", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public bool UserExists(string username)
{
object[] results = this.Invoke("UserExists", new object[] {
username});
return ((bool)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginUserExists(string username, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("UserExists", new object[] {
username}, callback, asyncState);
}
/// <remarks/>
public bool EndUserExists(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((bool)(results[0]));
}
/// <remarks/>
public void UserExistsAsync(string username)
{
this.UserExistsAsync(username, null);
}
/// <remarks/>
public void UserExistsAsync(string username, object userState)
{
if ((this.UserExistsOperationCompleted == null))
{
this.UserExistsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUserExistsOperationCompleted);
}
this.InvokeAsync("UserExists", new object[] {
username}, this.UserExistsOperationCompleted, userState);
}
private void OnUserExistsOperationCompleted(object arg)
{
if ((this.UserExistsCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.UserExistsCompleted(this, new UserExistsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetUsers", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string[] GetUsers()
{
object[] results = this.Invoke("GetUsers", new object[0]);
return ((string[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetUsers(System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetUsers", new object[0], callback, asyncState);
}
/// <remarks/>
public string[] EndGetUsers(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string[])(results[0]));
}
/// <remarks/>
public void GetUsersAsync()
{
this.GetUsersAsync(null);
}
/// <remarks/>
public void GetUsersAsync(object userState)
{
if ((this.GetUsersOperationCompleted == null))
{
this.GetUsersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUsersOperationCompleted);
}
this.InvokeAsync("GetUsers", new object[0], this.GetUsersOperationCompleted, userState);
}
private void OnGetUsersOperationCompleted(object arg)
{
if ((this.GetUsersCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetUsersCompleted(this, new GetUsersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetUser", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public SystemUser GetUser(string username)
{
object[] results = this.Invoke("GetUser", new object[] {
username});
return ((SystemUser)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetUser(string username, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetUser", new object[] {
username}, callback, asyncState);
}
/// <remarks/>
public SystemUser EndGetUser(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((SystemUser)(results[0]));
}
/// <remarks/>
public void GetUserAsync(string username)
{
this.GetUserAsync(username, null);
}
/// <remarks/>
public void GetUserAsync(string username, object userState)
{
if ((this.GetUserOperationCompleted == null))
{
this.GetUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserOperationCompleted);
}
this.InvokeAsync("GetUser", new object[] {
username}, this.GetUserOperationCompleted, userState);
}
private void OnGetUserOperationCompleted(object arg)
{
if ((this.GetUserCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetUserCompleted(this, new GetUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/CreateUser", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void CreateUser(SystemUser user)
{
this.Invoke("CreateUser", new object[] {
user});
}
/// <remarks/>
public System.IAsyncResult BeginCreateUser(SystemUser user, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("CreateUser", new object[] {
user}, callback, asyncState);
}
/// <remarks/>
public void EndCreateUser(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void CreateUserAsync(SystemUser user)
{
this.CreateUserAsync(user, null);
}
/// <remarks/>
public void CreateUserAsync(SystemUser user, object userState)
{
if ((this.CreateUserOperationCompleted == null))
{
this.CreateUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateUserOperationCompleted);
}
this.InvokeAsync("CreateUser", new object[] {
user}, this.CreateUserOperationCompleted, userState);
}
private void OnCreateUserOperationCompleted(object arg)
{
if ((this.CreateUserCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CreateUserCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UpdateUser", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void UpdateUser(SystemUser user)
{
this.Invoke("UpdateUser", new object[] {
user});
}
/// <remarks/>
public System.IAsyncResult BeginUpdateUser(SystemUser user, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("UpdateUser", new object[] {
user}, callback, asyncState);
}
/// <remarks/>
public void EndUpdateUser(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void UpdateUserAsync(SystemUser user)
{
this.UpdateUserAsync(user, null);
}
/// <remarks/>
public void UpdateUserAsync(SystemUser user, object userState)
{
if ((this.UpdateUserOperationCompleted == null))
{
this.UpdateUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateUserOperationCompleted);
}
this.InvokeAsync("UpdateUser", new object[] {
user}, this.UpdateUserOperationCompleted, userState);
}
private void OnUpdateUserOperationCompleted(object arg)
{
if ((this.UpdateUserCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.UpdateUserCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/ChangeUserPassword", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void ChangeUserPassword(string username, string password)
{
this.Invoke("ChangeUserPassword", new object[] {
username,
password});
}
/// <remarks/>
public System.IAsyncResult BeginChangeUserPassword(string username, string password, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("ChangeUserPassword", new object[] {
username,
password}, callback, asyncState);
}
/// <remarks/>
public void EndChangeUserPassword(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void ChangeUserPasswordAsync(string username, string password)
{
this.ChangeUserPasswordAsync(username, password, null);
}
/// <remarks/>
public void ChangeUserPasswordAsync(string username, string password, object userState)
{
if ((this.ChangeUserPasswordOperationCompleted == null))
{
this.ChangeUserPasswordOperationCompleted = new System.Threading.SendOrPostCallback(this.OnChangeUserPasswordOperationCompleted);
}
this.InvokeAsync("ChangeUserPassword", new object[] {
username,
password}, this.ChangeUserPasswordOperationCompleted, userState);
}
private void OnChangeUserPasswordOperationCompleted(object arg)
{
if ((this.ChangeUserPasswordCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.ChangeUserPasswordCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteUser", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void DeleteUser(string username)
{
this.Invoke("DeleteUser", new object[] {
username});
}
/// <remarks/>
public System.IAsyncResult BeginDeleteUser(string username, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("DeleteUser", new object[] {
username}, callback, asyncState);
}
/// <remarks/>
public void EndDeleteUser(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void DeleteUserAsync(string username)
{
this.DeleteUserAsync(username, null);
}
/// <remarks/>
public void DeleteUserAsync(string username, object userState)
{
if ((this.DeleteUserOperationCompleted == null))
{
this.DeleteUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteUserOperationCompleted);
}
this.InvokeAsync("DeleteUser", new object[] {
username}, this.DeleteUserOperationCompleted, userState);
}
private void OnDeleteUserOperationCompleted(object arg)
{
if ((this.DeleteUserCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteUserCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GroupExists", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public bool GroupExists(string groupName)
{
object[] results = this.Invoke("GroupExists", new object[] {
groupName});
return ((bool)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGroupExists(string groupName, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GroupExists", new object[] {
groupName}, callback, asyncState);
}
/// <remarks/>
public bool EndGroupExists(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((bool)(results[0]));
}
/// <remarks/>
public void GroupExistsAsync(string groupName)
{
this.GroupExistsAsync(groupName, null);
}
/// <remarks/>
public void GroupExistsAsync(string groupName, object userState)
{
if ((this.GroupExistsOperationCompleted == null))
{
this.GroupExistsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGroupExistsOperationCompleted);
}
this.InvokeAsync("GroupExists", new object[] {
groupName}, this.GroupExistsOperationCompleted, userState);
}
private void OnGroupExistsOperationCompleted(object arg)
{
if ((this.GroupExistsCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GroupExistsCompleted(this, new GroupExistsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetGroups", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string[] GetGroups()
{
object[] results = this.Invoke("GetGroups", new object[0]);
return ((string[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetGroups(System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetGroups", new object[0], callback, asyncState);
}
/// <remarks/>
public string[] EndGetGroups(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((string[])(results[0]));
}
/// <remarks/>
public void GetGroupsAsync()
{
this.GetGroupsAsync(null);
}
/// <remarks/>
public void GetGroupsAsync(object userState)
{
if ((this.GetGroupsOperationCompleted == null))
{
this.GetGroupsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetGroupsOperationCompleted);
}
this.InvokeAsync("GetGroups", new object[0], this.GetGroupsOperationCompleted, userState);
}
private void OnGetGroupsOperationCompleted(object arg)
{
if ((this.GetGroupsCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetGroupsCompleted(this, new GetGroupsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetGroup", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public SystemGroup GetGroup(string groupName)
{
object[] results = this.Invoke("GetGroup", new object[] {
groupName});
return ((SystemGroup)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetGroup(string groupName, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("GetGroup", new object[] {
groupName}, callback, asyncState);
}
/// <remarks/>
public SystemGroup EndGetGroup(System.IAsyncResult asyncResult)
{
object[] results = this.EndInvoke(asyncResult);
return ((SystemGroup)(results[0]));
}
/// <remarks/>
public void GetGroupAsync(string groupName)
{
this.GetGroupAsync(groupName, null);
}
/// <remarks/>
public void GetGroupAsync(string groupName, object userState)
{
if ((this.GetGroupOperationCompleted == null))
{
this.GetGroupOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetGroupOperationCompleted);
}
this.InvokeAsync("GetGroup", new object[] {
groupName}, this.GetGroupOperationCompleted, userState);
}
private void OnGetGroupOperationCompleted(object arg)
{
if ((this.GetGroupCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetGroupCompleted(this, new GetGroupCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/CreateGroup", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void CreateGroup(SystemGroup group)
{
this.Invoke("CreateGroup", new object[] {
group});
}
/// <remarks/>
public System.IAsyncResult BeginCreateGroup(SystemGroup group, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("CreateGroup", new object[] {
group}, callback, asyncState);
}
/// <remarks/>
public void EndCreateGroup(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void CreateGroupAsync(SystemGroup group)
{
this.CreateGroupAsync(group, null);
}
/// <remarks/>
public void CreateGroupAsync(SystemGroup group, object userState)
{
if ((this.CreateGroupOperationCompleted == null))
{
this.CreateGroupOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateGroupOperationCompleted);
}
this.InvokeAsync("CreateGroup", new object[] {
group}, this.CreateGroupOperationCompleted, userState);
}
private void OnCreateGroupOperationCompleted(object arg)
{
if ((this.CreateGroupCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CreateGroupCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UpdateGroup", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void UpdateGroup(SystemGroup group)
{
this.Invoke("UpdateGroup", new object[] {
group});
}
/// <remarks/>
public System.IAsyncResult BeginUpdateGroup(SystemGroup group, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("UpdateGroup", new object[] {
group}, callback, asyncState);
}
/// <remarks/>
public void EndUpdateGroup(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void UpdateGroupAsync(SystemGroup group)
{
this.UpdateGroupAsync(group, null);
}
/// <remarks/>
public void UpdateGroupAsync(SystemGroup group, object userState)
{
if ((this.UpdateGroupOperationCompleted == null))
{
this.UpdateGroupOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateGroupOperationCompleted);
}
this.InvokeAsync("UpdateGroup", new object[] {
group}, this.UpdateGroupOperationCompleted, userState);
}
private void OnUpdateGroupOperationCompleted(object arg)
{
if ((this.UpdateGroupCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.UpdateGroupCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteGroup", RequestNamespace = "http://smbsaas/websitepanel/server/", ResponseNamespace = "http://smbsaas/websitepanel/server/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void DeleteGroup(string groupName)
{
this.Invoke("DeleteGroup", new object[] {
groupName});
}
/// <remarks/>
public System.IAsyncResult BeginDeleteGroup(string groupName, System.AsyncCallback callback, object asyncState)
{
return this.BeginInvoke("DeleteGroup", new object[] {
groupName}, callback, asyncState);
}
/// <remarks/>
public void EndDeleteGroup(System.IAsyncResult asyncResult)
{
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void DeleteGroupAsync(string groupName)
{
this.DeleteGroupAsync(groupName, null);
}
/// <remarks/>
public void DeleteGroupAsync(string groupName, object userState)
{
if ((this.DeleteGroupOperationCompleted == null))
{
this.DeleteGroupOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteGroupOperationCompleted);
}
this.InvokeAsync("DeleteGroup", new object[] {
groupName}, this.DeleteGroupOperationCompleted, userState);
}
private void OnDeleteGroupOperationCompleted(object arg)
{
if ((this.DeleteGroupCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteGroupCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState)
{
base.CancelAsync(userState);
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void ExtendVirtualServerCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void UnextendVirtualServerCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void BackupVirtualServerCompletedEventHandler(object sender, BackupVirtualServerCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class BackupVirtualServerCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal BackupVirtualServerCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void RestoreVirtualServerCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetTempFileBinaryChunkCompletedEventHandler(object sender, GetTempFileBinaryChunkCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetTempFileBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetTempFileBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public byte[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((byte[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void AppendTempFileBinaryChunkCompletedEventHandler(object sender, AppendTempFileBinaryChunkCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class AppendTempFileBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal AppendTempFileBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetInstalledWebPartsCompletedEventHandler(object sender, GetInstalledWebPartsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetInstalledWebPartsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetInstalledWebPartsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void InstallWebPartsPackageCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteWebPartsPackageCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void UserExistsCompletedEventHandler(object sender, UserExistsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class UserExistsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal UserExistsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public bool Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((bool)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetUsersCompletedEventHandler(object sender, GetUsersCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetUsersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetUsersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetUserCompletedEventHandler(object sender, GetUserCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public SystemUser Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((SystemUser)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void CreateUserCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void UpdateUserCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void ChangeUserPasswordCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteUserCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GroupExistsCompletedEventHandler(object sender, GroupExistsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GroupExistsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GroupExistsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public bool Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((bool)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetGroupsCompletedEventHandler(object sender, GetGroupsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetGroupsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetGroupsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public string[] Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((string[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetGroupCompletedEventHandler(object sender, GetGroupCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetGroupCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
private object[] results;
internal GetGroupCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState)
:
base(exception, cancelled, userState)
{
this.results = results;
}
/// <remarks/>
public SystemGroup Result
{
get
{
this.RaiseExceptionIfNecessary();
return ((SystemGroup)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void CreateGroupCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void UpdateGroupCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteGroupCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Linq;
namespace NoraGrace.Engine
{
[Flags]
public enum CastleFlags
{
WhiteShort = 1,
WhiteLong = 2,
BlackShort = 4,
BlackLong = 8,
All = WhiteShort | WhiteLong | BlackShort | BlackLong
}
[System.Diagnostics.DebuggerDisplay(@"{FENCurrent,nq}")]
public sealed class Board
{
private class MoveHistory
{
public Move Move;
public Position Enpassant;
public CastleFlags Castle;
public int FiftyCount;
public int MovesSinceNull;
public Int64 Zobrist;
public Int64 ZobristPawn;
public Int64 ZobristMaterial;
public Bitboard Checkers;
public void Reset(Move move, Position enpassant, CastleFlags castle, int fifty, int sinceNull, Int64 zob, Int64 zobPawn, Int64 zobMaterial, Bitboard checkers)
{
this.Move = move;
this.Enpassant = enpassant;
this.Castle = castle;
this.FiftyCount = fifty;
this.MovesSinceNull = sinceNull;
this.Zobrist = zob;
this.ZobristPawn = zobPawn;
this.ZobristMaterial = zobMaterial;
this.Checkers = checkers;
}
}
private Piece[] _pieceat = new Piece[65];
private int[][] _pieceCount = Helpers.ArrayInit<int>(2, PieceTypeUtil.LookupArrayLength);
private Position[] _kingpos = new Position[2];
private Bitboard[] _pieceTypes = new Bitboard[PieceTypeUtil.LookupArrayLength];
private Bitboard[] _playerBoards = new Bitboard[2];
private Position[][][] _piecePositions = Helpers.ArrayInit<Position>(2, PieceTypeUtil.LookupArrayLength, 10);
private int[] _piecePositionIndex = new int[65];
private Bitboard _allPieces = 0;
private Bitboard _checkers = 0;
private Player _whosturn;
private CastleFlags _castleFlags;
private Position _enpassant;
private int _fiftymove = 0;
private int _fullmove = 0;
private Int64 _zob;
private Int64 _zobPawn;
private Int64 _zobMaterial;
private MoveHistory[] _hist = new MoveHistory[25];
private int _histUB;
private int _histCount = 0;
private int _movesSinceNull = 100;
private readonly Evaluation.PcSqEvaluator _pcSqEvaluator;
private Evaluation.PhasedScore _pcSq;
public Board(Evaluation.PcSqEvaluator pcSqEvaluator = null)
: this(new FEN(FEN.FENStart), pcSqEvaluator)
{
}
public Board(string fen, Evaluation.PcSqEvaluator pcSqEvaluator = null)
: this(new FEN(fen), pcSqEvaluator)
{
}
public Board(FEN fen, Evaluation.PcSqEvaluator pcSqEvaluator = null)
{
_histUB = _hist.GetUpperBound(0);
for (int i = 0; i <= _histUB; i++)
{
_hist[i] = new MoveHistory();
}
_pcSqEvaluator = pcSqEvaluator ?? Evaluation.Evaluator.Default.PcSq;
initPieceAtArray();
this.FENCurrent = fen;
}
public Board(FEN fen, IEnumerable<Move> prevMoves, Evaluation.PcSqEvaluator pcSqEvaluator = null)
: this(fen, pcSqEvaluator)
{
foreach (Move move in prevMoves)
{
this.MoveApply(move);
}
}
private void initPieceAtArray()
{
Helpers.ArrayReset(_pieceat, Piece.EMPTY);
Helpers.ArrayReset(_pieceCount, 0);
Helpers.ArrayReset(_kingpos, Position.OUTOFBOUNDS);
Helpers.ArrayReset(_pieceTypes, Bitboard.Empty);
Helpers.ArrayReset(_playerBoards, Bitboard.Empty);
Helpers.ArrayReset(_piecePositions, Position.OUTOFBOUNDS);
Helpers.ArrayReset(_piecePositionIndex, -1);
_allPieces = 0;
_pcSq = 0;
}
public Position EnPassant
{
get
{
return _enpassant;
}
}
public Position KingPosition(Player kingplayer)
{
return _kingpos[(int)kingplayer];
}
public Bitboard Checkers
{
get { return _checkers; }
}
public bool IsCheck()
{
System.Diagnostics.Debug.Assert(_checkers == (AttacksTo(KingPosition(WhosTurn)) & this[WhosTurn.PlayerOther()]));
return _checkers != Bitboard.Empty;
//return IsCheck(_whosturn);
}
public bool IsCheck(Player kingplayer)
{
Position kingpos = KingPosition(kingplayer);
return PositionAttacked(kingpos, kingplayer.PlayerOther());
}
private void PieceMove(Position from, Position to)
{
Piece piece = _pieceat[(int)from];
Player player = piece.PieceToPlayer();
PieceType pieceType = piece.ToPieceType();
_pieceat[(int)from] = Piece.EMPTY;
_pieceat[(int)to] = piece;
_zob ^= Zobrist.PiecePosition(piece, from);
_zob ^= Zobrist.PiecePosition(piece, to);
int index = _piecePositionIndex[(int)from];
_piecePositionIndex[(int)to] = index;
_piecePositions[(int)player][(int)pieceType][index] = to;
_pcSqEvaluator.PcSqValuesRemove(piece, from, ref _pcSq);
_pcSqEvaluator.PcSqValuesAdd(piece, to, ref _pcSq);
Bitboard posBits = from.ToBitboard() | to.ToBitboard();
_pieceTypes[(int)pieceType] ^= posBits;
_playerBoards[(int)player] ^= posBits;
_allPieces ^= posBits;
if (pieceType == PieceType.Pawn)
{
_zobPawn ^= Zobrist.PiecePosition(piece, from);
_zobPawn ^= Zobrist.PiecePosition(piece, to);
}
else if (pieceType == PieceType.King)
{
_kingpos[(int)player] = to;
}
}
private void PieceChange(Position pos, Piece newPiece)
{
PieceRemove(pos);
PieceAdd(pos, newPiece);
}
private void PieceAdd(Position pos, Piece piece)
{
Player player = piece.PieceToPlayer();
PieceType pieceType = piece.ToPieceType();
_pieceat[(int)pos] = piece;
_zob ^= Zobrist.PiecePosition(piece, pos);
int countOthers = _pieceCount[(int)player][(int)pieceType];
_zobMaterial ^= Zobrist.Material(piece, countOthers);
_piecePositionIndex[(int)pos] = countOthers;
_piecePositions[(int)player][(int)pieceType][countOthers] = pos;
_pieceCount[(int)player][(int)pieceType] = countOthers + 1;
_pcSqEvaluator.PcSqValuesAdd(piece, pos, ref _pcSq);
Bitboard posBits = pos.ToBitboard();
_pieceTypes[(int)piece.ToPieceType()] |= posBits;
_allPieces |= posBits;
_playerBoards[(int)piece.PieceToPlayer()] |= posBits;
if (pieceType == PieceType.Pawn)
{
_zobPawn ^= Zobrist.PiecePosition(piece, pos);
}
else if (pieceType == PieceType.King)
{
_kingpos[(int)player] = pos;
}
}
private void PieceRemove(Position pos)
{
Piece piece = PieceAt(pos);
Player player = piece.PieceToPlayer();
PieceType pieceType = piece.ToPieceType();
_pieceat[(int)pos] = Piece.EMPTY;
_zob ^= Zobrist.PiecePosition(piece, pos);
int index = _piecePositionIndex[(int)pos];
int countOthers = _pieceCount[(int)player][(int)pieceType] - 1;
_piecePositionIndex[(int)pos] = -1;
var list = _piecePositions[(int)player][(int)pieceType];
for (int i = index; i < countOthers; i++)
{
list[i] = list[i + 1];
_piecePositionIndex[(int)list[i]]--;
}
_zobMaterial ^= Zobrist.Material(piece, countOthers);
_pieceCount[(int)player][(int)pieceType] = countOthers;
_pcSqEvaluator.PcSqValuesRemove(piece, pos, ref _pcSq);
Bitboard notPosBits = ~pos.ToBitboard();
_pieceTypes[(int)pieceType] &= notPosBits;
_playerBoards[(int)player] &= notPosBits;
_allPieces &= notPosBits;
if (pieceType == PieceType.Pawn)
{
_zobPawn ^= Zobrist.PiecePosition(piece, pos);
}
}
private Bitboard PieceBitboardFromList(Player player, PieceType pieceType)
{
Bitboard retval = Bitboard.Empty;
int count = _pieceCount[(int)player][(int)pieceType];
for (int i = 0; i < count; i++)
{
retval |= _piecePositions[(int)player][(int)pieceType][i].ToBitboard();
}
return retval;
}
private void Validate()
{
System.Diagnostics.Debug.Assert(this[Player.White, PieceType.Pawn] == PieceBitboardFromList(Player.White, PieceType.Pawn));
System.Diagnostics.Debug.Assert(this[Player.White, PieceType.Knight] == PieceBitboardFromList(Player.White, PieceType.Knight));
System.Diagnostics.Debug.Assert(this[Player.White, PieceType.Bishop] == PieceBitboardFromList(Player.White, PieceType.Bishop));
System.Diagnostics.Debug.Assert(this[Player.White, PieceType.Rook] == PieceBitboardFromList(Player.White, PieceType.Rook));
System.Diagnostics.Debug.Assert(this[Player.White, PieceType.Queen] == PieceBitboardFromList(Player.White, PieceType.Queen));
System.Diagnostics.Debug.Assert(this[Player.White, PieceType.King] == PieceBitboardFromList(Player.White, PieceType.King));
System.Diagnostics.Debug.Assert(this[Player.Black, PieceType.Pawn] == PieceBitboardFromList(Player.Black, PieceType.Pawn));
System.Diagnostics.Debug.Assert(this[Player.Black, PieceType.Knight] == PieceBitboardFromList(Player.Black, PieceType.Knight));
System.Diagnostics.Debug.Assert(this[Player.Black, PieceType.Bishop] == PieceBitboardFromList(Player.Black, PieceType.Bishop));
System.Diagnostics.Debug.Assert(this[Player.Black, PieceType.Rook] == PieceBitboardFromList(Player.Black, PieceType.Rook));
System.Diagnostics.Debug.Assert(this[Player.Black, PieceType.Queen] == PieceBitboardFromList(Player.Black, PieceType.Queen));
System.Diagnostics.Debug.Assert(this[Player.Black, PieceType.King] == PieceBitboardFromList(Player.Black, PieceType.King));
}
public int PieceCount(Player player, PieceType pieceType)
{
return _pieceCount[(int)player][(int)pieceType];
}
public Position PieceLocation(Player player, PieceType pieceType, int index)
{
return _piecePositions[(int)player][(int)pieceType][index];
}
public Evaluation.PhasedScore PcSqValue
{
get { return _pcSq; }
}
public Evaluation.PcSqEvaluator PcSqEvaluator
{
get { return _pcSqEvaluator; }
}
public bool IsMate()
{
if (IsCheck())
{
if (!MoveUtil.GenMovesLegal(this).Any())
{
return true;
}
}
return false;
}
public bool IsDrawByStalemate()
{
if (!IsCheck())
{
if (!MoveUtil.GenMovesLegal(this).Any())
{
return true;
}
}
return false;
}
public bool IsDrawBy50MoveRule()
{
return (_fiftymove >= 100);
}
public bool IsDrawByRepetition()
{
return PositionRepetitionCount() >= 3;
}
public int PositionRepetitionCount()
{
Int64 currzob = this.ZobristBoard;
int repcount = 1;
for (int i = _histCount - 1; i >= 0; i--)
{
MoveHistory movehist = _hist[i];
if (movehist.Zobrist == currzob)
{
repcount++;
}
if (repcount >= 3)
{
return repcount;
}
if (movehist.Move.IsCapture())
{
break;
}
if (movehist.Move.MovingPieceType() == PieceType.Pawn)
{
break;
}
}
return repcount;
}
public int FiftyMovePlyCount
{
get
{
return _fiftymove;
}
}
public int FullMoveCount
{
get
{
return _fullmove;
}
}
public FEN FENCurrent
{
get
{
return new FEN(this);
}
set
{
//clear all existing pieces.
foreach (var pos in PositionUtil.AllPositions)
{
if (_pieceat[(int)pos] != Piece.EMPTY)
{
this.PieceRemove(pos);
}
}
//reset board
_histCount = 0;
initPieceAtArray();
//add pieces
foreach (var pos in PositionUtil.AllPositions)
{
if (value.pieceat[pos.GetIndex64()] != Piece.EMPTY)
{
this.PieceAdd(pos,value.pieceat[(int)pos]);
}
}
_castleFlags = 0;
_castleFlags |= value.castleWS ? CastleFlags.WhiteShort : 0;
_castleFlags |= value.castleWL ? CastleFlags.WhiteLong : 0;
_castleFlags |= value.castleBS ? CastleFlags.BlackShort : 0;
_castleFlags |= value.castleBL ? CastleFlags.BlackLong : 0;
_whosturn = value.whosturn;
_enpassant = value.enpassant;
_fiftymove = value.fiftymove;
_fullmove = value.fullmove;
_zob = Zobrist.BoardZob(this);
_zobPawn = Zobrist.BoardZobPawn(this);
_zobMaterial = Zobrist.BoardZobMaterial(this);
_checkers = AttacksTo(_kingpos[(int)_whosturn]) & this[_whosturn.PlayerOther()];
}
}
public Int64 ZobristBoard
{
get { return _zob; }
}
public Int64 ZobristPrevious
{
get { return _hist[_histCount - 1].Zobrist; }
}
public Int64 ZobristPawn
{
get { return _zobPawn; }
}
public Int64 ZobristMaterial
{
get { return _zobMaterial; }
}
public Bitboard RookSliders
{
get { return _pieceTypes[(int)PieceType.Rook] | _pieceTypes[(int)PieceType.Queen]; }
}
public Bitboard BishopSliders
{
get { return _pieceTypes[(int)PieceType.Bishop] | _pieceTypes[(int)PieceType.Queen]; }
}
public Bitboard this[PieceType pieceType]
{
get { return _pieceTypes[(int)pieceType]; }
}
public Bitboard this[Player player]
{
get
{
return _playerBoards[(int)player];
}
}
public Bitboard this[Player player, PieceType pieceType]
{
get
{
return _playerBoards[(int)player] & _pieceTypes[(int)pieceType];
}
}
public Bitboard PieceLocationsAll
{
get
{
return _allPieces;
}
}
public Piece PieceAt(Position pos)
{
return _pieceat[(int)pos];
}
public CastleFlags CastleRights
{
get { return _castleFlags; }
}
public Player WhosTurn
{
get
{
return _whosturn;
}
}
private void HistResize()
{
if (_histCount > _histUB)
{
Array.Resize(ref _hist, (_histCount + 10) * 2);
_histUB = _hist.GetUpperBound(0);
for (int i = _histCount; i <= _histUB; i++)
{
_hist[i] = new MoveHistory();
}
_histUB = _hist.GetUpperBound(0);
}
}
public void MoveApply(string movedesc)
{
Move move = MoveUtil.Parse(this, movedesc);
this.MoveApply(move);
}
public void MoveApply(Move move)
{
System.Diagnostics.Debug.Assert(move != Move.EMPTY);
System.Diagnostics.Debug.Assert(move.MovingPiece() == this.PieceAt(move.From()));
System.Diagnostics.Debug.Assert(move.CapturedPiece() == this.PieceAt(move.To()));
System.Diagnostics.Debug.Assert(move.MovingPlayer() == WhosTurn);
Position from = move.From();
Position to = move.To();
Piece piece = move.MovingPiece();
Piece capture = move.CapturedPiece();
//Rank fromrank = from.ToRank();
//Rank torank = to.ToRank();
//File fromfile = from.ToFile();
//File tofile = to.ToFile();
if (_histCount > _histUB) { HistResize(); }
_hist[_histCount++].Reset(move, _enpassant, _castleFlags, _fiftymove,_movesSinceNull, _zob, _zobPawn, _zobMaterial, _checkers);
//increment since null count;
_movesSinceNull++;
//remove captured piece
if (capture != Piece.EMPTY)
{
this.PieceRemove(to);
}
//move piece, promote if needed
this.PieceMove(from, to);
//promote if needed
if (move.IsPromotion())
{
this.PieceChange(to, move.Promote());
}
//if castle, move rook
if (move.IsCastle())
{
if (piece == Piece.WKing && from == Position.E1 && to == Position.G1)
{
this.PieceMove(Position.H1, Position.F1);
}
else if (piece == Piece.WKing && from == Position.E1 && to == Position.C1)
{
this.PieceMove(Position.A1, Position.D1);
}
else if (piece == Piece.BKing && from == Position.E8 && to == Position.G8)
{
this.PieceMove(Position.H8, Position.F8);
}
else if (piece == Piece.BKing && from == Position.E8 && to == Position.C8)
{
this.PieceMove(Position.A8, Position.D8);
}
}
//mark unavailability of castling
if(_castleFlags != 0)
{
if (((_castleFlags & CastleFlags.WhiteShort) != 0)
&& (piece == Piece.WKing || from == Position.H1))
{
_castleFlags &= ~CastleFlags.WhiteShort;
_zob ^= Zobrist.CastleWS;
}
if (((_castleFlags & CastleFlags.WhiteLong) != 0)
&& (piece == Piece.WKing || from == Position.A1))
{
_castleFlags &= ~CastleFlags.WhiteLong;
_zob ^= Zobrist.CastleWL;
}
if (((_castleFlags & CastleFlags.BlackShort) != 0)
&& (piece == Piece.BKing || from == Position.H8))
{
_castleFlags &= ~CastleFlags.BlackShort;
_zob ^= Zobrist.CastleBS;
}
if (((_castleFlags & CastleFlags.BlackLong) != 0)
&& (piece == Piece.BKing || from == Position.A8))
{
_castleFlags &= ~CastleFlags.BlackLong;
_zob ^= Zobrist.CastleBL;
}
}
//if enpassant move then remove captured pawn
if (move.IsEnPassant())
{
this.PieceRemove(to.ToFile().ToPosition(move.MovingPlayer().MyRank(Rank.Rank5)));
}
//unmark enpassant sq
if (_enpassant.IsInBounds())
{
_zob ^= Zobrist.Enpassant(_enpassant);
_enpassant = (Position.OUTOFBOUNDS);
}
//mark enpassant sq if pawn double jump
if (move.IsPawnDoubleJump())
{
_enpassant = from.PositionInDirectionUnsafe(move.MovingPlayer().MyNorth());
_zob ^= Zobrist.Enpassant(_enpassant);
}
//increment the move count
if (_whosturn == Player.Black)
{
_fullmove++;
}
if (piece != Piece.WPawn && piece != Piece.BPawn && capture == Piece.EMPTY)
{
_fiftymove++;
}
else
{
_fiftymove = 0;
}
//switch whos turn
_whosturn = _whosturn.PlayerOther();
_zob ^= Zobrist.PlayerKey;
_checkers = AttacksTo(_kingpos[(int)_whosturn]) & this[_whosturn.PlayerOther()];
Validate();
}
public int HistoryCount
{
get
{
return _histCount;
}
}
public IEnumerable<Move> HistoryMoves
{
get
{
for (int i = 0; i < _histCount; i++)
{
yield return _hist[i].Move;
}
}
}
public Move HistMove(int MovesAgo)
{
return _hist[_histCount - MovesAgo].Move;
}
public void MoveUndo()
{
//undo move history
MoveHistory movehist = _hist[_histCount - 1];
_histCount--;
Move moveUndoing = movehist.Move;
//undo promotion
if (moveUndoing.IsPromotion())
{
PieceChange(moveUndoing.To(), moveUndoing.MovingPiece());
}
//move piece to it's original location
PieceMove(moveUndoing.To(), moveUndoing.From());
//replace the captured piece
if (moveUndoing.IsCapture())
{
PieceAdd(moveUndoing.To(), moveUndoing.CapturedPiece());
}
//move rook back if castle
if (moveUndoing.IsCastle())
{
Player movingPlayer = moveUndoing.MovingPlayer();
Position to = moveUndoing.To();
if (moveUndoing.MovingPlayer() == Player.White && moveUndoing.To() == Position.G1)
{
this.PieceMove(Position.F1, Position.H1);
}
if (moveUndoing.MovingPlayer() == Player.White && moveUndoing.To() == Position.C1)
{
this.PieceMove(Position.D1, Position.A1);
}
if (moveUndoing.MovingPlayer() == Player.Black && moveUndoing.To() == Position.G8)
{
this.PieceMove(Position.F8, Position.H8);
}
if (moveUndoing.MovingPlayer() == Player.Black && moveUndoing.To() == Position.C8)
{
this.PieceMove(Position.D8, Position.A8);
}
}
//put back pawn if enpassant capture
if (moveUndoing.IsEnPassant())
{
System.Diagnostics.Debug.Assert(moveUndoing.To() == movehist.Enpassant);
File tofile = moveUndoing.To().ToFile();
Rank enpassantRank = moveUndoing.MovingPlayer().MyRank(Rank.Rank5);
PieceAdd(tofile.ToPosition(enpassantRank), PieceType.Pawn.ForPlayer(moveUndoing.MovingPlayer().PlayerOther()));
}
this._castleFlags = movehist.Castle;
this._enpassant = movehist.Enpassant;
this._fiftymove = movehist.FiftyCount;
this._movesSinceNull = movehist.MovesSinceNull;
if (_whosturn == Player.White)
{
_fullmove--;
}
_whosturn = _whosturn.PlayerOther();
_zob = movehist.Zobrist;
_zobPawn = movehist.ZobristPawn;
_zobMaterial = movehist.ZobristMaterial;
_checkers = movehist.Checkers;
}
public void MoveNullApply()
{
//save move history
if (_histCount > _histUB) { HistResize(); }
_hist[_histCount++].Reset(Move.EMPTY, _enpassant, _castleFlags, _fiftymove, _movesSinceNull, _zob, _zobPawn, _zobMaterial, _checkers);
//reset since null count;
_movesSinceNull = 0;
//unmark enpassant sq
if (_enpassant.IsInBounds())
{
_zob ^= Zobrist.Enpassant(_enpassant);
_enpassant = (Position.OUTOFBOUNDS);
}
//switch whos turn
_whosturn = _whosturn.PlayerOther();
_zob ^= Zobrist.PlayerKey;
_checkers = AttacksTo(_kingpos[(int)_whosturn]) & this[_whosturn.PlayerOther()];
}
public void MoveNullUndo()
{
MoveHistory movehist = _hist[_histCount - 1];
_histCount--;
this._castleFlags = movehist.Castle;
this._enpassant = movehist.Enpassant;
this._fiftymove = movehist.FiftyCount;
this._movesSinceNull = movehist.MovesSinceNull;
_whosturn = _whosturn.PlayerOther();
_zob = movehist.Zobrist;
_zobPawn = movehist.ZobristPawn;
_zobMaterial = movehist.ZobristMaterial;
_checkers = movehist.Checkers;
}
public int MovesSinceNull
{
get
{
return this._movesSinceNull;
}
}
public bool LastTwoMovesNull()
{
return MovesSinceNull == 0
&& this._histCount >= 2
&& this._hist[_histCount - 2].Move == Move.EMPTY;
}
public Piece PieceInDirection(Position from, Direction dir, ref Position pos)
{
int i = 0;
return PieceInDirection(from, dir, ref pos, ref i);
}
public Piece PieceInDirection(Position from, Direction dir, ref Position pos, ref int dist)
{
Piece piece;
pos = from.PositionInDirection(dir);
dist = 1;
while (pos.IsInBounds())
{
piece = this.PieceAt(pos);
if (piece != Piece.EMPTY) { return piece; }
dist++;
if (dir.IsDirectionKnight())
{
break;
}
else
{
pos = pos.PositionInDirection(dir);
}
}
return Piece.EMPTY;
}
public Bitboard AttacksTo(Position to, Player by)
{
return AttacksTo(to) & this[by];
}
public Bitboard AttacksTo(Position to)
{
Bitboard retval = 0;
retval |= Attacks.KnightAttacks(to) & this[PieceType.Knight];
retval |= Attacks.RookAttacks(to, this.PieceLocationsAll) & (this[PieceType.Queen] | this[PieceType.Rook]);
retval |= Attacks.BishopAttacks(to, this.PieceLocationsAll) & (this[PieceType.Queen] | this[PieceType.Bishop]);
retval |= Attacks.KingAttacks(to) & (this[PieceType.King]);
retval |= Attacks.PawnAttacks(to, Player.Black) & this[Player.White, PieceType.Pawn];
retval |= Attacks.PawnAttacks(to, Player.White) & this[Player.Black, PieceType.Pawn];
return retval;
}
public bool PositionAttacked(Position to, Player byPlayer)
{
return !AttacksTo(to, byPlayer).Empty();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.Util
{
using System;
/// <summary>
/// A List of short's; as full an implementation of the java.Util.List
/// interface as possible, with an eye toward minimal creation of
/// objects
///
/// the mimicry of List is as follows:
/// <ul>
/// <li> if possible, operations designated 'optional' in the List
/// interface are attempted</li>
/// <li> wherever the List interface refers to an Object, substitute
/// short</li>
/// <li> wherever the List interface refers to a Collection or List,
/// substitute shortList</li>
/// </ul>
///
/// the mimicry is not perfect, however:
/// <ul>
/// <li> operations involving Iterators or ListIterators are not
/// supported</li>
/// <li> Remove(Object) becomes RemoveValue to distinguish it from
/// Remove(short index)</li>
/// <li> subList is not supported</li>
/// </ul>
/// </summary>
internal class ShortList
{
private short[] _array;
private int _limit;
private static int _default_size = 128;
/// <summary>
/// create an shortList of default size
/// </summary>
public ShortList()
: this(_default_size)
{
}
/// <summary>
/// create a copy of an existing shortList
/// </summary>
/// <param name="list">the existing shortList</param>
public ShortList(ShortList list)
: this(list._array.Length)
{
Array.Copy(list._array, 0, _array, 0, _array.Length);
_limit = list._limit;
}
/// <summary>
/// create an shortList with a predefined Initial size
/// </summary>
/// <param name="InitialCapacity">the size for the internal array</param>
public ShortList(int InitialCapacity)
{
_array = new short[InitialCapacity];
_limit = 0;
}
/// <summary>
/// add the specfied value at the specified index
/// </summary>
/// <param name="index">the index where the new value is to be Added</param>
/// <param name="value">the new value</param>
public void Add(int index, short value)
{
if (index > _limit)
{
throw new IndexOutOfRangeException();
}
else if (index == _limit)
{
Add(value);
}
else
{
// index < limit -- insert into the middle
if (_limit == _array.Length)
{
GrowArray(_limit * 2);
}
Array.Copy(_array, index, _array, index + 1,
_limit - index);
_array[index] = value;
_limit++;
}
}
/// <summary>
/// Appends the specified element to the end of this list
/// </summary>
/// <param name="value">element to be Appended to this list.</param>
/// <returns>return true (as per the general contract of the Collection.add method).</returns>
public bool Add(short value)
{
if (_limit == _array.Length)
{
GrowArray(_limit * 2);
}
_array[_limit++] = value;
return true;
}
/// <summary>
/// Appends all of the elements in the specified collection to the
/// end of this list, in the order that they are returned by the
/// specified collection's iterator. The behavior of this
/// operation is unspecified if the specified collection is
/// modified while the operation is in progress. (Note that this
/// will occur if the specified collection is this list, and it's
/// nonempty.)
/// </summary>
/// <param name="c">collection whose elements are to be Added to this list.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
public bool AddAll(ShortList c)
{
if (c._limit != 0)
{
if ((_limit + c._limit) > _array.Length)
{
GrowArray(_limit + c._limit);
}
Array.Copy(c._array, 0, _array, _limit, c._limit);
_limit += c._limit;
}
return true;
}
/// <summary>
/// Inserts all of the elements in the specified collection into
/// this list at the specified position. Shifts the element
/// currently at that position (if any) and any subsequent elements
/// to the right (increases their indices). The new elements will
/// appear in this list in the order that they are returned by the
/// specified collection's iterator. The behavior of this
/// operation is unspecified if the specified collection is
/// modified while the operation is in progress. (Note that this
/// will occur if the specified collection is this list, and it's
/// nonempty.)
/// </summary>
/// <param name="index">index at which to insert first element from the specified collection.</param>
/// <param name="c">elements to be inserted into this list.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
/// <exception cref="IndexOutOfRangeException"> if the index is out of range (index < 0 || index > size())</exception>
public bool AddAll(int index, ShortList c)
{
if (index > _limit)
{
throw new IndexOutOfRangeException();
}
if (c._limit != 0)
{
if ((_limit + c._limit) > _array.Length)
{
GrowArray(_limit + c._limit);
}
// make a hole
Array.Copy(_array, index, _array, index + c._limit,
_limit - index);
// fill it in
Array.Copy(c._array, 0, _array, index, c._limit);
_limit += c._limit;
}
return true;
}
/// <summary>
/// Removes all of the elements from this list. This list will be
/// empty After this call returns (unless it throws an exception).
/// </summary>
public void Clear()
{
_limit = 0;
}
/// <summary>
/// Returns true if this list Contains the specified element. More
/// formally, returns true if and only if this list Contains at
/// least one element e such that o == e
/// </summary>
/// <param name="o">element whose presence in this list is to be Tested.</param>
/// <returns>return true if this list Contains the specified element.</returns>
public bool Contains(short o)
{
bool rval = false;
for (int j = 0; !rval && (j < _limit); j++)
{
if (_array[j] == o)
{
rval = true;
}
}
return rval;
}
/// <summary>
/// Returns true if this list Contains all of the elements of the specified collection.
/// </summary>
/// <param name="c">collection to be Checked for Containment in this list.</param>
/// <returns>return true if this list Contains all of the elements of the specified collection.</returns>
public bool ContainsAll(ShortList c)
{
bool rval = true;
if (this != c)
{
for (int j = 0; rval && (j < c._limit); j++)
{
if (!Contains(c._array[j]))
{
rval = false;
}
}
}
return rval;
}
/// <summary>
/// Compares the specified object with this list for Equality.
/// Returns true if and only if the specified object is also a
/// list, both lists have the same size, and all corresponding
/// pairs of elements in the two lists are Equal. (Two elements e1
/// and e2 are equal if e1 == e2.) In other words, two lists are
/// defined to be equal if they contain the same elements in the
/// same order. This defInition ensures that the Equals method
/// works properly across different implementations of the List
/// interface.
/// </summary>
/// <param name="o">the object to be Compared for Equality with this list.</param>
/// <returns>return true if the specified object is equal to this list.</returns>
public override bool Equals(Object o)
{
bool rval = this == o;
if (!rval && (o != null) && (o.GetType() == this.GetType()))
{
ShortList other = (ShortList)o;
if (other._limit == _limit)
{
// assume match
rval = true;
for (int j = 0; rval && (j < _limit); j++)
{
rval = _array[j] == other._array[j];
}
}
}
return rval;
}
/// <summary>
/// Returns the element at the specified position in this list.
/// </summary>
/// <param name="index">index of element to return.</param>
/// <returns>return the element at the specified position in this list.</returns>
public short Get(int index)
{
if (index >= _limit)
{
throw new IndexOutOfRangeException();
}
return _array[index];
}
/// <summary>
/// Returns the hash code value for this list. The hash code of a
/// list is defined to be the result of the following calculation:
///
/// <code>
/// hashCode = 1;
/// Iterator i = list.Iterator();
/// while (i.HasNext()) {
/// Object obj = i.Next();
/// hashCode = 31*hashCode + (obj==null ? 0 : obj.HashCode());
/// }
/// </code>
///
/// This ensures that list1.Equals(list2) implies that
/// list1.HashCode()==list2.HashCode() for any two lists, list1 and
/// list2, as required by the general contract of Object.HashCode.
/// </summary>
/// <returns>return the hash code value for this list.</returns>
public override int GetHashCode()
{
int hash = 0;
for (int j = 0; j < _limit; j++)
{
hash = (31 * hash) + _array[j];
}
return hash;
}
/// <summary>
/// Returns the index in this list of the first occurrence of the
/// specified element, or -1 if this list does not contain this
/// element. More formally, returns the lowest index i such that
/// (o == Get(i)), or -1 if there is no such index.
/// </summary>
/// <param name="o">element to search for.</param>
/// <returns>the index in this list of the first occurrence of the
/// specified element, or -1 if this list does not contain
/// this element.
/// </returns>
public int IndexOf(short o)
{
int rval = 0;
for (; rval < _limit; rval++)
{
if (o == _array[rval])
{
break;
}
}
if (rval == _limit)
{
rval = -1; // didn't find it
}
return rval;
}
/// <summary>
/// Returns true if this list Contains no elements.
/// </summary>
/// <returns>return true if this list Contains no elements.</returns>
public bool IsEmpty()
{
return _limit == 0;
}
/// <summary>
/// Returns the index in this list of the last occurrence of the
/// specified element, or -1 if this list does not contain this
/// element. More formally, returns the highest index i such that
/// (o == Get(i)), or -1 if there is no such index.
/// </summary>
/// <param name="o">element to search for.</param>
/// <returns>return the index in this list of the last occurrence of the
/// specified element, or -1 if this list does not contain this element.</returns>
public int LastIndexOf(short o)
{
int rval = _limit - 1;
for (; rval >= 0; rval--)
{
if (o == _array[rval])
{
break;
}
}
return rval;
}
/// <summary>
/// Removes the element at the specified position in this list.
/// Shifts any subsequent elements to the left (subtracts one from
/// their indices). Returns the element that was Removed from the
/// list.
/// </summary>
/// <param name="index">the index of the element to Removed.</param>
/// <returns>return the element previously at the specified position.</returns>
public short Remove(int index)
{
if (index >= _limit)
{
throw new IndexOutOfRangeException();
}
short rval = _array[index];
Array.Copy(_array, index + 1, _array, index, _limit - index);
_limit--;
return rval;
}
/// <summary>
/// Removes the first occurrence in this list of the specified
/// element (optional operation). If this list does not contain
/// the element, it is unChanged. More formally, Removes the
/// element with the lowest index i such that (o.Equals(get(i)))
/// (if such an element exists).
/// </summary>
/// <param name="o">element to be Removed from this list, if present.</param>
/// <returns>return true if this list Contained the specified element.</returns>
public bool RemoveValue(short o)
{
bool rval = false;
for (int j = 0; !rval && (j < _limit); j++)
{
if (o == _array[j])
{
Array.Copy(_array, j + 1, _array, j, _limit - j);
_limit--;
rval = true;
}
}
return rval;
}
/// <summary>
/// Removes from this list all the elements that are Contained in the specified collection
/// </summary>
/// <param name="c">collection that defines which elements will be removed from this list.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
public bool RemoveAll(ShortList c)
{
bool rval = false;
for (int j = 0; j < c._limit; j++)
{
if (RemoveValue(c._array[j]))
{
rval = true;
}
}
return rval;
}
/// <summary>
/// Retains only the elements in this list that are Contained in
/// the specified collection. In other words, Removes from this
/// list all the elements that are not Contained in the specified
/// collection.
/// </summary>
/// <param name="c">collection that defines which elements this Set will retain.</param>
/// <returns>return true if this list Changed as a result of the call.</returns>
public bool RetainAll(ShortList c)
{
bool rval = false;
for (int j = 0; j < _limit; )
{
if (!c.Contains(_array[j]))
{
Remove(j);
rval = true;
}
else
{
j++;
}
}
return rval;
}
/// <summary>
/// Replaces the element at the specified position in this list with the specified element
/// </summary>
/// <param name="index">index of element to Replace.</param>
/// <param name="element">element to be stored at the specified position.</param>
/// <returns>return the element previously at the specified position.</returns>
public short Set(int index, short element)
{
if (index >= _limit)
{
throw new IndexOutOfRangeException();
}
short rval = _array[index];
_array[index] = element;
return rval;
}
/// <summary>
/// Returns the number of elements in this list. If this list
/// Contains more than Int32.MaxValue elements, returns
/// Int32.MaxValue.
/// </summary>
/// <returns>return the number of elements in this shortList</returns>
public int Size()
{
return _limit;
}
/// <summary>
/// the number of elements in this shortList
/// </summary>
public int Count
{
get { return _limit; }
}
/// <summary>
/// Returns an array Containing all of the elements in this list in
/// proper sequence. Obeys the general contract of the
/// Collection.ToArray method.
/// </summary>
/// <returns>an array Containing all of the elements in this list in
/// proper sequence.</returns>
public short[] ToArray()
{
short[] rval = new short[_limit];
Array.Copy(_array, 0, rval, 0, _limit);
return rval;
}
/// <summary>
/// Returns an array Containing all of the elements in this list in
/// proper sequence. Obeys the general contract of the
/// Collection.ToArray(Object[]) method.
/// </summary>
/// <param name="a">the array into which the elements of this list are to
/// be stored, if it is big enough; otherwise, a new array
/// is allocated for this purpose.</param>
/// <returns>return an array Containing the elements of this list.</returns>
public short[] ToArray(short[] a)
{
short[] rval;
if (a.Length == _limit)
{
Array.Copy(_array, 0, a, 0, _limit);
rval = a;
}
else
{
rval = ToArray();
}
return rval;
}
private void GrowArray(int new_size)
{
int size = (new_size == _array.Length) ? new_size + 1
: new_size;
short[] new_array = new short[size];
Array.Copy(_array, 0, new_array, 0, _limit);
_array = new_array;
}
} // end internal class shortList
}
| |
using System.Linq;
using FluentAssert;
using FluentBrowserAutomation.Controls;
using FluentBrowserAutomation.Extensions;
// ReSharper disable once CheckNamespace
namespace FluentBrowserAutomation
{
public interface IAmGenericInputThatCanBeChanged : IAmInputThatCanBeChanged
{
}
public static class IAmGenericInputThatCanBeChangedExtensions
{
// ReSharper disable once SuggestBaseTypeForParameter
public static IAmInputThatCanBeChanged CheckIt(this IAmGenericInputThatCanBeChanged input)
{
input.AssertIsCheckBox();
var checkBox = input.AsCheckBox();
checkBox.CheckedState().SetValueTo(true);
return checkBox;
}
public static bool HasOption(this IAmGenericInputThatCanBeChanged input, string expected)
{
input.AssertIsDropDownList();
var dropDown = input.AsDropDownList();
return dropDown.HasOption(expected);
}
public static bool HasTextValue(this IAmGenericInputThatCanBeChanged input, string expected)
{
input.BrowserContext.WaitUntil(x => input.IsVisible().IsTrue, errorMessage:"wait for " + input.HowFound + " to be visible in HasTextValue");
if (input.IsTextBox())
{
var textBox = input.AsTextBox();
return textBox.Text() == expected;
}
if (input.IsDropDownList())
{
var dropDown = input.AsDropDownList();
return dropDown.HasOption(expected);
}
if (input.IsCheckBox())
{
var checkBox = input.AsCheckBox();
return checkBox.Element.ValueAttributeHasValue(expected);
}
throw new AssertionException("Cannot get a text value from " + input.HowFound);
}
public static IAmInputThatCanBeChanged SelectAnyOptionExcept(this IAmGenericInputThatCanBeChanged input, params string[] unwantedValues)
{
input.AssertIsDropDownList();
var dropDown = input.AsDropDownList();
dropDown.SelectAnyOptionExcept(unwantedValues);
return dropDown;
}
public static IAmInputThatCanBeChanged SelectIt(this IAmGenericInputThatCanBeChanged input)
{
input.AssertIsRadioOption();
var radioOption = input.AsRadioOption();
radioOption.SelectedState().SetValueTo(true);
return radioOption;
}
public static IAmInputThatCanBeChanged SelectedOptionShouldBeEqualTo(this IAmGenericInputThatCanBeChanged input, string text)
{
input.AssertIsDropDownList();
var dropDown = input.AsDropDownList();
dropDown.SelectedOptionShouldBeEqualTo(text);
return dropDown;
}
public static IAmInputThatCanBeChanged SelectedOptionValueShouldBeEqualTo(this IAmGenericInputThatCanBeChanged input, string value)
{
input.AssertIsDropDownList();
input.BrowserContext.WaitUntil(x => input.IsVisible().IsTrue, errorMessage:"wait for " + input.HowFound + " to be visible in SelectedOptionValueShouldBeEqualTo");
var dropDown = input.AsDropDownList();
input.BrowserContext.WaitUntil(x => dropDown.Options.Any(), errorMessage:"wait for " + input.HowFound + " options to be visible in SelectedOptionValueShouldBeEqualTo");
var selectedValues = dropDown.GetSelectedValues().ToArray();
selectedValues.Contains(value).ShouldBeTrue("Selected value of " + dropDown.HowFound + " should be '" + value + "' but is/are '" + string.Join(", ", selectedValues) + "'");
return dropDown;
}
public static IAmInputThatCanBeChanged SetTo(this IAmGenericInputThatCanBeChanged input, string text)
{
input.WaitUntil(x => x.Exists().IsTrue, errorMessage:"wait for " + input.HowFound + " to exist in SetTo");
if (input.IsTextBox())
{
var textBox = input.AsTextBox();
textBox.SetTo(text);
return textBox;
}
if (input.IsDropDownList())
{
var dropDown = input.AsDropDownList();
dropDown.Select(text);
return dropDown;
}
if (input.IsCheckBox())
{
var checkBox = input.AsCheckBox();
if (text == "checked")
{
checkBox.CheckIt();
}
else
{
checkBox.UncheckIt();
}
return checkBox;
}
if (input.IsRadioOption())
{
var radioOption = input.AsRadioOption();
if (text == "checked" || text == "selected")
{
radioOption.SelectIt();
}
else
{
radioOption.UnselectIt();
}
return radioOption;
}
if (input.IsFileUpload())
{
var fileUploadWrapper = input.AsFileUpload();
fileUploadWrapper.SetTo(text);
return fileUploadWrapper;
}
return new MissingInputWrapper(input.HowFound, input.BrowserContext);
}
public static IAmInputThatCanBeChanged ShouldBeChecked(this IAmGenericInputThatCanBeChanged input)
{
input.AssertIsCheckBox();
var checkBox = input.AsCheckBox();
checkBox.ShouldBeChecked();
return checkBox;
}
public static IAmInputThatCanBeChanged ShouldBeEmpty(this IAmGenericInputThatCanBeChanged input)
{
input.HasTextValue("").ShouldBeTrue();
return input;
}
public static IAmInputThatCanBeChanged ShouldBeEqualTo(this IAmGenericInputThatCanBeChanged input, string expected)
{
var textBox = input.AsTextBox();
if (textBox == null)
{
throw new AssertionException(input.HowFound + " is not a text box. It is a(n) " + input.GetType());
}
input.BrowserContext.WaitUntil(x => textBox.IsVisible().IsTrue, errorMessage:"wait for " + input.HowFound + " to be visible in ShouldBeEqualTo");
input.BrowserContext.WaitUntil(x =>
{
var actual = textBox.Text().Text ?? "";
return actual == (expected??"");
}, errorMessage:"wait for " + input.HowFound + " to have text '" + expected + "' in ShouldBeEqualTo");
textBox.Text().ShouldBeEqualTo(expected ?? "");
return textBox;
}
public static IAmInputThatCanBeChanged ShouldHaveOption(this IAmGenericInputThatCanBeChanged input, string optionText)
{
input.AssertIsDropDownList();
input.BrowserContext.WaitUntil(x => input.IsVisible().IsTrue, errorMessage:"wait for " + input.HowFound + " to be visible in ShouldHaveOption");
var dropDown = input.AsDropDownList();
input.BrowserContext.WaitUntil(x => dropDown.Options.Any(), errorMessage:"wait for " + input.HowFound + " options to be visible in ShouldHaveOption");
dropDown.Options.Select(x => (string)x.Text).ToList().ShouldContainAll(new[] { optionText });
return dropDown;
}
public static IAmInputThatCanBeChanged ShouldNotBeChecked(this IAmGenericInputThatCanBeChanged input)
{
input.AssertIsCheckBox();
var checkBox = input.AsCheckBox();
checkBox.ShouldNotBeChecked();
return checkBox;
}
public static IAmInputThatCanBeChanged ShouldNotBeEmpty(this IAmGenericInputThatCanBeChanged input)
{
input.HasTextValue("").ShouldBeFalse();
return input;
}
public static IAmInputThatCanBeChanged ShouldNotHaveOption(this IAmGenericInputThatCanBeChanged input, string optionText)
{
input.AssertIsDropDownList();
var dropDown = input.AsDropDownList();
dropDown.ShouldNotHaveOption(optionText);
return dropDown;
}
public static IAmInputThatCanBeChanged UncheckIt(this IAmGenericInputThatCanBeChanged input)
{
input.AssertIsCheckBox();
var checkBox = input.AsCheckBox();
checkBox.CheckedState().SetValueTo(false);
return checkBox;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Xml;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
using System.Linq;
#if USE_REFEMIT || NET_NATIVE
public sealed class ClassDataContract : DataContract
#else
internal sealed class ClassDataContract : DataContract
#endif
{
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML namespaces for class members.
/// statically cached and used from IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent IL generated code.
/// not changed to property to avoid regressing performance; any changes to initialization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] ContractNamespaces;
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML element names for class members.
/// statically cached and used from IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent IL generated code.
/// not changed to property to avoid regressing performance; any changes to initialization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] MemberNames;
/// <SecurityNote>
/// Review - XmlDictionaryString(s) representing the XML namespaces for class members.
/// statically cached and used when calling IL generated code. should ideally be Critical.
/// marked SecurityRequiresReview to be callable from transparent code.
/// not changed to property to avoid regressing performance; any changes to initialization should be reviewed.
/// </SecurityNote>
public XmlDictionaryString[] MemberNamespaces;
[SecurityCritical]
/// <SecurityNote>
/// Critical - XmlDictionaryString representing the XML namespaces for members of class.
/// statically cached and used from IL generated code.
/// </SecurityNote>
private XmlDictionaryString[] _childElementNamespaces;
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private ClassDataContractCriticalHelper _helper;
private bool _isScriptObject;
#if NET_NATIVE
public ClassDataContract() : base(new ClassDataContractCriticalHelper())
{
InitClassDataContract();
}
#endif
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type))
{
InitClassDataContract();
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames))
{
InitClassDataContract();
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical fields; called from all constructors
/// </SecurityNote>
private void InitClassDataContract()
{
_helper = base.Helper as ClassDataContractCriticalHelper;
this.ContractNamespaces = _helper.ContractNamespaces;
this.MemberNames = _helper.MemberNames;
this.MemberNamespaces = _helper.MemberNamespaces;
_isScriptObject = _helper.IsScriptObject;
}
internal ClassDataContract BaseContract
{
/// <SecurityNote>
/// Critical - fetches the critical baseContract property
/// Safe - baseContract only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.BaseContract; }
}
internal List<DataMember> Members
{
/// <SecurityNote>
/// Critical - fetches the critical members property
/// Safe - members only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.Members; }
}
public XmlDictionaryString[] ChildElementNamespaces
{
/// <SecurityNote>
/// Critical - fetches the critical childElementNamespaces property
/// Safe - childElementNamespaces only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_childElementNamespaces == null)
{
lock (this)
{
if (_childElementNamespaces == null)
{
if (_helper.ChildElementNamespaces == null)
{
XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces();
Interlocked.MemoryBarrier();
_helper.ChildElementNamespaces = tempChildElementamespaces;
}
_childElementNamespaces = _helper.ChildElementNamespaces;
}
}
}
return _childElementNamespaces;
}
set
{
_childElementNamespaces = value;
}
}
internal MethodInfo OnSerializing
{
/// <SecurityNote>
/// Critical - fetches the critical onSerializing property
/// Safe - onSerializing only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnSerializing; }
}
internal MethodInfo OnSerialized
{
/// <SecurityNote>
/// Critical - fetches the critical onSerialized property
/// Safe - onSerialized only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnSerialized; }
}
internal MethodInfo OnDeserializing
{
/// <SecurityNote>
/// Critical - fetches the critical onDeserializing property
/// Safe - onDeserializing only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnDeserializing; }
}
internal MethodInfo OnDeserialized
{
/// <SecurityNote>
/// Critical - fetches the critical onDeserialized property
/// Safe - onDeserialized only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.OnDeserialized; }
}
#if !NET_NATIVE
public override DataContractDictionary KnownDataContracts
{
/// <SecurityNote>
/// Critical - fetches the critical knownDataContracts property
/// Safe - knownDataContracts only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
}
#endif
internal bool IsNonAttributedType
{
/// <SecurityNote>
/// Critical - fetches the critical IsNonAttributedType property
/// Safe - IsNonAttributedType only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsNonAttributedType; }
}
#if NET_NATIVE
public bool HasDataContract
{
[SecuritySafeCritical]
get
{ return _helper.HasDataContract; }
set { _helper.HasDataContract = value; }
}
public bool HasExtensionData
{
[SecuritySafeCritical]
get
{ return _helper.HasExtensionData; }
set { _helper.HasExtensionData = value; }
}
#endif
internal bool IsKeyValuePairAdapter
{
[SecuritySafeCritical]
get
{ return _helper.IsKeyValuePairAdapter; }
}
internal Type[] KeyValuePairGenericArguments
{
[SecuritySafeCritical]
get
{ return _helper.KeyValuePairGenericArguments; }
}
internal ConstructorInfo KeyValuePairAdapterConstructorInfo
{
[SecuritySafeCritical]
get
{ return _helper.KeyValuePairAdapterConstructorInfo; }
}
internal MethodInfo GetKeyValuePairMethodInfo
{
[SecuritySafeCritical]
get
{ return _helper.GetKeyValuePairMethodInfo; }
}
private ConstructorInfo _nonAttributedTypeConstructor;
/// <SecurityNote>
/// Critical - fetches information about which constructor should be used to initialize non-attributed types that are valid for serialization
/// Safe - only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
internal ConstructorInfo GetNonAttributedTypeConstructor()
{
if (_nonAttributedTypeConstructor == null)
{
// Cache the ConstructorInfo to improve performance.
_nonAttributedTypeConstructor = _helper.GetNonAttributedTypeConstructor();
}
return _nonAttributedTypeConstructor;
}
private Func<object> _makeNewInstance;
private Func<object> MakeNewInstance
{
get
{
if (_makeNewInstance == null)
{
_makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType);
}
return _makeNewInstance;
}
}
internal bool CreateNewInstanceViaDefaultConstructor(out object obj)
{
ConstructorInfo ci = GetNonAttributedTypeConstructor();
if (ci == null)
{
obj = null;
return false;
}
if (ci.IsPublic)
{
// Optimization for calling public default ctor.
obj = MakeNewInstance();
}
else
{
obj = ci.Invoke(Array.Empty<object>());
}
return true;
}
#if NET_NATIVE
private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate;
public XmlFormatClassWriterDelegate XmlFormatWriterDelegate
#else
internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate
#endif
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatWriterDelegate property
/// Safe - xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
#if NET_NATIVE
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatWriterDelegate != null))
{
return _xmlFormatWriterDelegate;
}
#endif
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatClassWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
set
{
#if NET_NATIVE
_xmlFormatWriterDelegate = value;
#endif
}
}
#if NET_NATIVE
private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate;
public XmlFormatClassReaderDelegate XmlFormatReaderDelegate
#else
internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate
#endif
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatReaderDelegate property
/// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
#if NET_NATIVE
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly
|| (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatReaderDelegate != null))
{
return _xmlFormatReaderDelegate;
}
#endif
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
XmlFormatClassReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
set
{
#if NET_NATIVE
_xmlFormatReaderDelegate = value;
#endif
}
}
internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames)
{
ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type);
if (cdc == null)
{
return new ClassDataContract(type, ns, memberNames);
}
else
{
ClassDataContract cloned = cdc.Clone();
cloned.UpdateNamespaceAndMembers(type, ns, memberNames);
return cloned;
}
}
internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable)
{
DataMember existingMemberContract;
if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract))
{
Type declaringType = memberContract.MemberInfo.DeclaringType;
DataContract.ThrowInvalidDataContractException(
SR.Format((declaringType.GetTypeInfo().IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName),
existingMemberContract.MemberInfo.Name,
memberContract.MemberInfo.Name,
DataContract.GetClrTypeFullName(declaringType),
memberContract.Name),
declaringType);
}
memberNamesTable.Add(memberContract.Name, memberContract);
members.Add(memberContract);
}
internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary)
{
childType = DataContract.UnwrapNullableType(childType);
if (!childType.GetTypeInfo().IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType)
&& DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull)
{
string ns = DataContract.GetStableName(childType).Namespace;
if (ns.Length > 0 && ns != dataContract.Namespace.Value)
return dictionary.Add(ns);
}
return null;
}
private static bool IsArraySegment(Type t)
{
return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
/// <SecurityNote>
/// RequiresReview - callers may need to depend on isNonAttributedType for a security decision
/// isNonAttributedType must be calculated correctly
/// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and
/// is therefore marked SRR
/// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value
/// </SecurityNote>
static internal bool IsNonAttributedTypeValidForSerialization(Type type)
{
if (type.IsArray)
return false;
if (type.GetTypeInfo().IsEnum)
return false;
if (type.IsGenericParameter)
return false;
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
return false;
if (type.IsPointer)
return false;
if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
return false;
Type[] interfaceTypes = type.GetInterfaces();
if (!IsArraySegment(type))
{
foreach (Type interfaceType in interfaceTypes)
{
if (CollectionDataContract.IsCollectionInterface(interfaceType))
return false;
}
}
if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))
return false;
if (type.GetTypeInfo().IsValueType)
{
return type.GetTypeInfo().IsVisible;
}
else
{
return (type.GetTypeInfo().IsVisible &&
type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()) != null);
}
}
private static readonly Dictionary<string, string[]> s_knownSerializableTypeInfos = new Dictionary<string, string[]> {
{ "System.Collections.Generic.KeyValuePair`2", Array.Empty<string>() },
{ "System.Collections.Generic.Queue`1", new [] { "_syncRoot" } },
{ "System.Collections.Generic.Stack`1", new [] {"_syncRoot" } },
{ "System.Collections.ObjectModel.ReadOnlyCollection`1", new [] {"_syncRoot" } },
{ "System.Collections.ObjectModel.ReadOnlyDictionary`2", new [] {"_syncRoot", "_keys","_values" } },
{ "System.Tuple`1", Array.Empty<string>() },
{ "System.Tuple`2", Array.Empty<string>() },
{ "System.Tuple`3", Array.Empty<string>() },
{ "System.Tuple`4", Array.Empty<string>() },
{ "System.Tuple`5", Array.Empty<string>() },
{ "System.Tuple`6", Array.Empty<string>() },
{ "System.Tuple`7", Array.Empty<string>() },
{ "System.Tuple`8", Array.Empty<string>() },
{ "System.Collections.Queue", new [] {"_syncRoot" } },
{ "System.Collections.Stack", new [] {"_syncRoot" } },
{ "System.Globalization.CultureInfo", Array.Empty<string>() },
{ "System.Version", Array.Empty<string>() },
};
private static string GetGeneralTypeName(Type type)
{
TypeInfo typeInfo = type.GetTypeInfo();
return typeInfo.IsGenericType && !typeInfo.IsGenericParameter
? typeInfo.GetGenericTypeDefinition().FullName
: type.FullName;
}
internal static bool IsKnownSerializableType(Type type)
{
// Applies to known types that DCS understands how to serialize/deserialize
//
string typeFullName = GetGeneralTypeName(type);
return s_knownSerializableTypeInfos.ContainsKey(typeFullName)
|| Globals.TypeOfException.IsAssignableFrom(type);
}
internal static bool IsNonSerializedMember(Type type, string memberName)
{
string typeFullName = GetGeneralTypeName(type);
string[] members;
return s_knownSerializableTypeInfos.TryGetValue(typeFullName, out members)
&& members.Contains(memberName);
}
private XmlDictionaryString[] CreateChildElementNamespaces()
{
if (Members == null)
return null;
XmlDictionaryString[] baseChildElementNamespaces = null;
if (this.BaseContract != null)
baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces;
int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0;
XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount];
if (baseChildElementNamespaceCount > 0)
Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length);
XmlDictionary dictionary = new XmlDictionary();
for (int i = 0; i < this.Members.Count; i++)
{
childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary);
}
return childElementNamespaces;
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - calls critical method on helper
/// Safe - doesn't leak anything
/// </SecurityNote>
private void EnsureMethodsImported()
{
_helper.EnsureMethodsImported();
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
if (_isScriptObject)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
}
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
if (_isScriptObject)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
}
xmlReader.Read();
object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces);
xmlReader.ReadEndElement();
return o;
}
/// <SecurityNote>
/// Review - calculates whether this class requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
EnsureMethodsImported();
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException))
return true;
if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor()))
{
if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType))
{
return true;
}
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnDeserializing))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnDeserializingNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnDeserializing.Name),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnDeserialized))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnDeserializedNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnDeserialized.Name),
securityException));
}
return true;
}
if (this.Members != null)
{
for (int i = 0; i < this.Members.Count; i++)
{
if (this.Members[i].RequiresMemberAccessForSet())
{
if (securityException != null)
{
if (this.Members[i].MemberInfo is FieldInfo)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractFieldSetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractPropertySetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
}
return true;
}
}
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this class requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
EnsureMethodsImported();
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException))
return true;
if (MethodRequiresMemberAccess(this.OnSerializing))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnSerializingNotPublic,
DataContract.GetClrTypeFullName(this.UnderlyingType),
this.OnSerializing.Name),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.OnSerialized))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractOnSerializedNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.OnSerialized.Name),
securityException));
}
return true;
}
if (this.Members != null)
{
for (int i = 0; i < this.Members.Count; i++)
{
if (this.Members[i].RequiresMemberAccessForGet())
{
if (securityException != null)
{
if (this.Members[i].MemberInfo is FieldInfo)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractFieldGetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustDataContractPropertyGetNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.Members[i].MemberInfo.Name),
securityException));
}
}
return true;
}
}
}
return false;
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for (de)serializing classes.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private ClassDataContract _baseContract;
private List<DataMember> _members;
private MethodInfo _onSerializing, _onSerialized;
private MethodInfo _onDeserializing, _onDeserialized;
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private bool _isMethodChecked;
/// <SecurityNote>
/// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract
/// </SecurityNote>
private bool _isNonAttributedType;
/// <SecurityNote>
/// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType
/// </SecurityNote>
private bool _hasDataContract;
#if NET_NATIVE
private bool _hasExtensionData;
#endif
private bool _isScriptObject;
private XmlDictionaryString[] _childElementNamespaces;
private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate;
public XmlDictionaryString[] ContractNamespaces;
public XmlDictionaryString[] MemberNames;
public XmlDictionaryString[] MemberNamespaces;
internal ClassDataContractCriticalHelper() : base()
{
}
internal ClassDataContractCriticalHelper(Type type) : base(type)
{
XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type);
if (type == Globals.TypeOfDBNull)
{
this.StableName = stableName;
_members = new List<DataMember>();
XmlDictionary dictionary = new XmlDictionary(2);
this.Name = dictionary.Add(StableName.Name);
this.Namespace = dictionary.Add(StableName.Namespace);
this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty<XmlDictionaryString>();
EnsureMethodsImported();
return;
}
Type baseType = type.GetTypeInfo().BaseType;
SetIsNonAttributedType(type);
SetKeyValuePairAdapterFlags(type);
this.IsValueType = type.GetTypeInfo().IsValueType;
if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri)
{
DataContract baseContract = DataContract.GetDataContract(baseType);
if (baseContract is CollectionDataContract)
this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract;
else
this.BaseContract = baseContract as ClassDataContract;
if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError
(new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes,
DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType))));
}
}
else
this.BaseContract = null;
{
this.StableName = stableName;
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(2 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = dictionary.Add(StableName.Namespace);
int baseMemberCount = 0;
int baseContractCount = 0;
if (BaseContract == null)
{
MemberNames = new XmlDictionaryString[Members.Count];
MemberNamespaces = new XmlDictionaryString[Members.Count];
ContractNamespaces = new XmlDictionaryString[1];
}
else
{
baseMemberCount = BaseContract.MemberNames.Length;
MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount];
Array.Copy(BaseContract.MemberNames, 0, MemberNames, 0, baseMemberCount);
MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount];
Array.Copy(BaseContract.MemberNamespaces, 0, MemberNamespaces, 0, baseMemberCount);
baseContractCount = BaseContract.ContractNamespaces.Length;
ContractNamespaces = new XmlDictionaryString[1 + baseContractCount];
Array.Copy(BaseContract.ContractNamespaces, 0, ContractNamespaces, 0, baseContractCount);
}
ContractNamespaces[baseContractCount] = Namespace;
for (int i = 0; i < Members.Count; i++)
{
MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name);
MemberNamespaces[i + baseMemberCount] = Namespace;
}
}
EnsureMethodsImported();
_isScriptObject = this.IsNonAttributedType &&
Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType);
}
internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type)
{
this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value);
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(1 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = ns;
ContractNamespaces = new XmlDictionaryString[] { Namespace };
MemberNames = new XmlDictionaryString[Members.Count];
MemberNamespaces = new XmlDictionaryString[Members.Count];
for (int i = 0; i < Members.Count; i++)
{
Members[i].Name = memberNames[i];
MemberNames[i] = dictionary.Add(Members[i].Name);
MemberNamespaces[i] = Namespace;
}
EnsureMethodsImported();
}
private void EnsureIsReferenceImported(Type type)
{
DataContractAttribute dataContractAttribute;
bool isReference = false;
bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute);
if (BaseContract != null)
{
if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly)
{
bool baseIsReference = this.BaseContract.IsReference;
if ((baseIsReference && !dataContractAttribute.IsReference) ||
(!baseIsReference && dataContractAttribute.IsReference))
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.InconsistentIsReference,
DataContract.GetClrTypeFullName(type),
dataContractAttribute.IsReference,
DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType),
this.BaseContract.IsReference),
type);
}
else
{
isReference = dataContractAttribute.IsReference;
}
}
else
{
isReference = this.BaseContract.IsReference;
}
}
else if (hasDataContractAttribute)
{
if (dataContractAttribute.IsReference)
isReference = dataContractAttribute.IsReference;
}
if (isReference && type.GetTypeInfo().IsValueType)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.ValueTypeCannotHaveIsReference,
DataContract.GetClrTypeFullName(type),
true,
false),
type);
return;
}
this.IsReference = isReference;
}
private void ImportDataMembers()
{
Type type = this.UnderlyingType;
EnsureIsReferenceImported(type);
List<DataMember> tempMembers = new List<DataMember>();
Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>();
MemberInfo[] memberInfos;
bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type);
if (!isPodSerializable)
{
memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
}
else
{
memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
for (int i = 0; i < memberInfos.Length; i++)
{
MemberInfo member = memberInfos[i];
if (HasDataContract)
{
object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray();
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
DataMember memberContract = new DataMember(member);
if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
MethodInfo getMethod = property.GetMethod;
if (getMethod != null && IsMethodOverriding(getMethod))
continue;
MethodInfo setMethod = property.SetMethod;
if (setMethod != null && IsMethodOverriding(setMethod))
continue;
if (getMethod == null)
ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name));
if (setMethod == null)
{
if (!SetIfGetOnlyCollection(memberContract))
{
ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name));
}
}
if (getMethod.GetParameters().Length > 0)
ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name));
}
else if (!(member is FieldInfo))
ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name));
DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0];
if (memberAttribute.IsNameSetExplicitly)
{
if (memberAttribute.Name == null || memberAttribute.Name.Length == 0)
ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type)));
memberContract.Name = memberAttribute.Name;
}
else
memberContract.Name = member.Name;
memberContract.Name = DataContract.EncodeLocalName(memberContract.Name);
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
memberContract.IsRequired = memberAttribute.IsRequired;
if (memberAttribute.IsRequired && this.IsReference)
{
ThrowInvalidDataContractException(
SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType,
DataContract.GetClrTypeFullName(member.DeclaringType),
member.Name, true), type);
}
memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue;
memberContract.Order = memberAttribute.Order;
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
else if (!isPodSerializable)
{
FieldInfo field = member as FieldInfo;
PropertyInfo property = member as PropertyInfo;
if ((field == null && property == null) || (field != null && field.IsInitOnly))
continue;
object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray();
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
else
continue;
}
DataMember memberContract = new DataMember(member);
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0)
continue;
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
{
if (!SetIfGetOnlyCollection(memberContract))
continue;
}
else
{
if (!setMethod.IsPublic || IsMethodOverriding(setMethod))
continue;
}
}
memberContract.Name = DataContract.EncodeLocalName(member.Name);
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
else
{
// [Serializible] and [NonSerialized] are deprecated on FxCore
// Try to mimic the behavior by allowing certain known types to go through
// POD types are fine also
FieldInfo field = member as FieldInfo;
if (CanSerializeMember(field))
{
DataMember memberContract = new DataMember(member);
memberContract.Name = DataContract.EncodeLocalName(member.Name);
object[] optionalFields = null; // TODO 11477: Add back optional field support
if (optionalFields == null || optionalFields.Length == 0)
{
if (this.IsReference)
{
ThrowInvalidDataContractException(
SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType,
DataContract.GetClrTypeFullName(member.DeclaringType),
member.Name, true), type);
}
memberContract.IsRequired = true;
}
memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);
CheckAndAddMember(tempMembers, memberContract, memberNamesTable);
}
}
}
if (tempMembers.Count > 1)
tempMembers.Sort(DataMemberComparer.Singleton);
SetIfMembersHaveConflict(tempMembers);
Interlocked.MemoryBarrier();
_members = tempMembers;
}
private static bool CanSerializeMember(FieldInfo field)
{
return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType, field.Name);
}
private bool SetIfGetOnlyCollection(DataMember memberContract)
{
//OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios
if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.GetTypeInfo().IsValueType)
{
memberContract.IsGetOnlyCollection = true;
return true;
}
return false;
}
private void SetIfMembersHaveConflict(List<DataMember> members)
{
if (BaseContract == null)
return;
int baseTypeIndex = 0;
List<Member> membersInHierarchy = new List<Member>();
foreach (DataMember member in members)
{
membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex));
}
ClassDataContract currContract = BaseContract;
while (currContract != null)
{
baseTypeIndex++;
foreach (DataMember member in currContract.Members)
{
membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex));
}
currContract = currContract.BaseContract;
}
IComparer<Member> comparer = DataMemberConflictComparer.Singleton;
membersInHierarchy.Sort(comparer);
for (int i = 0; i < membersInHierarchy.Count - 1; i++)
{
int startIndex = i;
int endIndex = i;
bool hasConflictingType = false;
while (endIndex < membersInHierarchy.Count - 1
&& String.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0
&& String.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0)
{
membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member;
if (!hasConflictingType)
{
if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType)
{
hasConflictingType = true;
}
else
{
hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType);
}
}
endIndex++;
}
if (hasConflictingType)
{
for (int j = startIndex; j <= endIndex; j++)
{
membersInHierarchy[j].member.HasConflictingNameAndType = true;
}
}
i = endIndex + 1;
}
}
/// <SecurityNote>
/// Critical - sets the critical hasDataContract field
/// Safe - uses a trusted critical API (DataContract.GetStableName) to calculate the value
/// does not accept the value from the caller
/// </SecurityNote>
//CSD16748
//[SecuritySafeCritical]
private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type)
{
return DataContract.GetStableName(type, out _hasDataContract);
}
/// <SecurityNote>
/// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision
/// isNonAttributedType must be calculated correctly
/// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it
/// is dependent on the correct calculation of hasDataContract
/// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value
/// </SecurityNote>
private void SetIsNonAttributedType(Type type)
{
_isNonAttributedType = !_hasDataContract && IsNonAttributedTypeValidForSerialization(type);
}
private static bool IsMethodOverriding(MethodInfo method)
{
return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0);
}
internal void EnsureMethodsImported()
{
if (!_isMethodChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isMethodChecked)
{
Type type = this.UnderlyingType;
MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < methods.Length; i++)
{
MethodInfo method = methods[i];
Type prevAttributeType = null;
ParameterInfo[] parameters = method.GetParameters();
//THese attributes are cut from mscorlib.
if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType))
_onSerializing = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType))
_onSerialized = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType))
_onDeserializing = method;
if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType))
_onDeserialized = method;
}
Interlocked.MemoryBarrier();
_isMethodChecked = true;
}
}
}
}
private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
{
if (method.IsDefined(attributeType, false))
{
if (currentCallback != null)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);
else if (prevAttributeType != null)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);
else if (method.IsVirtual)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);
else
{
if (method.ReturnType != Globals.TypeOfVoid)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);
if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext)
DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType);
prevAttributeType = attributeType;
}
return true;
}
return false;
}
internal ClassDataContract BaseContract
{
get { return _baseContract; }
set
{
_baseContract = value;
if (_baseContract != null && IsValueType)
ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace));
}
}
internal List<DataMember> Members
{
get { return _members; }
}
internal MethodInfo OnSerializing
{
get
{
EnsureMethodsImported();
return _onSerializing;
}
}
internal MethodInfo OnSerialized
{
get
{
EnsureMethodsImported();
return _onSerialized;
}
}
internal MethodInfo OnDeserializing
{
get
{
EnsureMethodsImported();
return _onDeserializing;
}
}
internal MethodInfo OnDeserialized
{
get
{
EnsureMethodsImported();
return _onDeserialized;
}
}
internal override DataContractDictionary KnownDataContracts
{
[SecurityCritical]
get
{
if (_knownDataContracts != null)
{
return _knownDataContracts;
}
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
[SecurityCritical]
set
{ _knownDataContracts = value; }
}
internal bool HasDataContract
{
get { return _hasDataContract; }
#if NET_NATIVE
set { _hasDataContract = value; }
#endif
}
#if NET_NATIVE
internal bool HasExtensionData
{
get { return _hasExtensionData; }
set { _hasExtensionData = value; }
}
#endif
internal bool IsNonAttributedType
{
get { return _isNonAttributedType; }
}
private void SetKeyValuePairAdapterFlags(Type type)
{
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
{
_isKeyValuePairAdapter = true;
_keyValuePairGenericArguments = type.GetGenericArguments();
_keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) });
_getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers);
}
}
private bool _isKeyValuePairAdapter;
private Type[] _keyValuePairGenericArguments;
private ConstructorInfo _keyValuePairCtorInfo;
private MethodInfo _getKeyValuePairMethodInfo;
internal bool IsKeyValuePairAdapter
{
get { return _isKeyValuePairAdapter; }
}
internal bool IsScriptObject
{
get { return _isScriptObject; }
}
internal Type[] KeyValuePairGenericArguments
{
get { return _keyValuePairGenericArguments; }
}
internal ConstructorInfo KeyValuePairAdapterConstructorInfo
{
get { return _keyValuePairCtorInfo; }
}
internal MethodInfo GetKeyValuePairMethodInfo
{
get { return _getKeyValuePairMethodInfo; }
}
internal ConstructorInfo GetNonAttributedTypeConstructor()
{
if (!this.IsNonAttributedType)
return null;
Type type = UnderlyingType;
if (type.GetTypeInfo().IsValueType)
return null;
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
if (ctor == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
return ctor;
}
internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
public XmlDictionaryString[] ChildElementNamespaces
{
get { return _childElementNamespaces; }
set { _childElementNamespaces = value; }
}
internal struct Member
{
internal Member(DataMember member, string ns, int baseTypeIndex)
{
this.member = member;
this.ns = ns;
this.baseTypeIndex = baseTypeIndex;
}
internal DataMember member;
internal string ns;
internal int baseTypeIndex;
}
internal class DataMemberConflictComparer : IComparer<Member>
{
[SecuritySafeCritical]
public int Compare(Member x, Member y)
{
int nsCompare = String.CompareOrdinal(x.ns, y.ns);
if (nsCompare != 0)
return nsCompare;
int nameCompare = String.CompareOrdinal(x.member.Name, y.member.Name);
if (nameCompare != 0)
return nameCompare;
return x.baseTypeIndex - y.baseTypeIndex;
}
internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer();
}
internal ClassDataContractCriticalHelper Clone()
{
ClassDataContractCriticalHelper clonedHelper = new ClassDataContractCriticalHelper(this.UnderlyingType);
clonedHelper._baseContract = this._baseContract;
clonedHelper._childElementNamespaces = this._childElementNamespaces;
clonedHelper.ContractNamespaces = this.ContractNamespaces;
clonedHelper._hasDataContract = this._hasDataContract;
clonedHelper._isMethodChecked = this._isMethodChecked;
clonedHelper._isNonAttributedType = this._isNonAttributedType;
clonedHelper.IsReference = this.IsReference;
clonedHelper.IsValueType = this.IsValueType;
clonedHelper.MemberNames = this.MemberNames;
clonedHelper.MemberNamespaces = this.MemberNamespaces;
clonedHelper._members = this._members;
clonedHelper.Name = this.Name;
clonedHelper.Namespace = this.Namespace;
clonedHelper._onDeserialized = this._onDeserialized;
clonedHelper._onDeserializing = this._onDeserializing;
clonedHelper._onSerialized = this._onSerialized;
clonedHelper._onSerializing = this._onSerializing;
clonedHelper.StableName = this.StableName;
clonedHelper.TopLevelElementName = this.TopLevelElementName;
clonedHelper.TopLevelElementNamespace = this.TopLevelElementNamespace;
clonedHelper._xmlFormatReaderDelegate = this._xmlFormatReaderDelegate;
clonedHelper._xmlFormatWriterDelegate = this._xmlFormatWriterDelegate;
return clonedHelper;
}
}
internal class DataMemberComparer : IComparer<DataMember>
{
public int Compare(DataMember x, DataMember y)
{
int orderCompare = x.Order - y.Order;
if (orderCompare != 0)
return orderCompare;
return String.CompareOrdinal(x.Name, y.Name);
}
internal static DataMemberComparer Singleton = new DataMemberComparer();
}
#if !NET_NATIVE
/// <summary>
/// Get object type for Xml/JsonFormmatReaderGenerator
/// </summary>
internal Type ObjectType
{
get
{
Type type = UnderlyingType;
if (type.GetTypeInfo().IsValueType && !IsNonAttributedType)
{
type = Globals.TypeOfValueType;
}
return type;
}
}
#endif
internal ClassDataContract Clone()
{
ClassDataContract clonedDc = new ClassDataContract(this.UnderlyingType);
clonedDc._helper = _helper.Clone();
clonedDc.ContractNamespaces = this.ContractNamespaces;
clonedDc.ChildElementNamespaces = this.ChildElementNamespaces;
clonedDc.MemberNames = this.MemberNames;
clonedDc.MemberNamespaces = this.MemberNamespaces;
clonedDc.XmlFormatWriterDelegate = this.XmlFormatWriterDelegate;
clonedDc.XmlFormatReaderDelegate = this.XmlFormatReaderDelegate;
return clonedDc;
}
internal void UpdateNamespaceAndMembers(Type type, XmlDictionaryString ns, string[] memberNames)
{
this.StableName = new XmlQualifiedName(GetStableName(type).Name, ns.Value);
this.Namespace = ns;
XmlDictionary dictionary = new XmlDictionary(1 + memberNames.Length);
this.Name = dictionary.Add(StableName.Name);
this.Namespace = ns;
this.ContractNamespaces = new XmlDictionaryString[] { ns };
this.MemberNames = new XmlDictionaryString[memberNames.Length];
this.MemberNamespaces = new XmlDictionaryString[memberNames.Length];
for (int i = 0; i < memberNames.Length; i++)
{
this.MemberNames[i] = dictionary.Add(memberNames[i]);
this.MemberNamespaces[i] = ns;
}
}
internal Type UnadaptedClassType
{
get
{
if (IsKeyValuePairAdapter)
{
return Globals.TypeOfKeyValuePair.MakeGenericType(KeyValuePairGenericArguments);
}
else
{
return UnderlyingType;
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Framework.Testing;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Cursor;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Edit.Components.Menus;
namespace osu.Game.Skinning.Editor
{
[Cached(typeof(SkinEditor))]
public class SkinEditor : VisibilityContainer
{
public const double TRANSITION_DURATION = 500;
public readonly BindableList<ISkinnableDrawable> SelectedComponents = new BindableList<ISkinnableDrawable>();
protected override bool StartHidden => true;
private readonly Drawable targetScreen;
private OsuTextFlowContainer headerText;
private Bindable<Skin> currentSkin;
[Resolved]
private SkinManager skins { get; set; }
[Resolved]
private OsuColour colours { get; set; }
private bool hasBegunMutating;
public SkinEditor(Drawable targetScreen)
{
this.targetScreen = targetScreen;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new OsuContextMenuContainer
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Container
{
Name = "Top bar",
RelativeSizeAxes = Axes.X,
Depth = float.MinValue,
Height = 40,
Children = new Drawable[]
{
new EditorMenuBar
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
RelativeSizeAxes = Axes.Both,
Items = new[]
{
new MenuItem("File")
{
Items = new[]
{
new EditorMenuItem("Save", MenuItemType.Standard, Save),
new EditorMenuItem("Revert to default", MenuItemType.Destructive, revert),
new EditorMenuItemSpacer(),
new EditorMenuItem("Exit", MenuItemType.Standard, Hide),
},
},
}
},
headerText = new OsuTextFlowContainer
{
TextAnchor = Anchor.TopRight,
Padding = new MarginPadding(5),
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
AutoSizeAxes = Axes.X,
RelativeSizeAxes = Axes.Y,
},
},
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension()
},
Content = new[]
{
new Drawable[]
{
new SkinComponentToolbox(600)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
RequestPlacement = placeComponent
},
new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new SkinBlueprintContainer(targetScreen),
}
},
}
}
}
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
Show();
// as long as the skin editor is loaded, let's make sure we can modify the current skin.
currentSkin = skins.CurrentSkin.GetBoundCopy();
// schedule ensures this only happens when the skin editor is visible.
// also avoid some weird endless recursion / bindable feedback loop (something to do with tracking skins across three different bindable types).
// probably something which will be factored out in a future database refactor so not too concerning for now.
currentSkin.BindValueChanged(skin =>
{
hasBegunMutating = false;
Scheduler.AddOnce(skinChanged);
}, true);
}
private void skinChanged()
{
headerText.Clear();
headerText.AddParagraph("Skin editor", cp => cp.Font = OsuFont.Default.With(size: 16));
headerText.NewParagraph();
headerText.AddText("Currently editing ", cp =>
{
cp.Font = OsuFont.Default.With(size: 12);
cp.Colour = colours.Yellow;
});
headerText.AddText($"{currentSkin.Value.SkinInfo}", cp =>
{
cp.Font = OsuFont.Default.With(size: 12, weight: FontWeight.Bold);
cp.Colour = colours.Yellow;
});
skins.EnsureMutableSkin();
hasBegunMutating = true;
}
private void placeComponent(Type type)
{
var targetContainer = getTarget(SkinnableTarget.MainHUDComponents);
if (targetContainer == null)
return;
if (!(Activator.CreateInstance(type) is ISkinnableDrawable component))
throw new InvalidOperationException($"Attempted to instantiate a component for placement which was not an {typeof(ISkinnableDrawable)}.");
var drawableComponent = (Drawable)component;
// give newly added components a sane starting location.
drawableComponent.Origin = Anchor.TopCentre;
drawableComponent.Anchor = Anchor.TopCentre;
drawableComponent.Y = targetContainer.DrawSize.Y / 2;
targetContainer.Add(component);
SelectedComponents.Clear();
SelectedComponents.Add(component);
}
private IEnumerable<ISkinnableTarget> availableTargets => targetScreen.ChildrenOfType<ISkinnableTarget>();
private ISkinnableTarget getTarget(SkinnableTarget target)
{
return availableTargets.FirstOrDefault(c => c.Target == target);
}
private void revert()
{
ISkinnableTarget[] targetContainers = availableTargets.ToArray();
foreach (var t in targetContainers)
{
currentSkin.Value.ResetDrawableTarget(t);
// add back default components
getTarget(t.Target).Reload();
}
}
public void Save()
{
if (!hasBegunMutating)
return;
ISkinnableTarget[] targetContainers = availableTargets.ToArray();
foreach (var t in targetContainers)
currentSkin.Value.UpdateDrawableTarget(t);
skins.Save(skins.CurrentSkin.Value);
}
protected override bool OnHover(HoverEvent e) => true;
protected override bool OnMouseDown(MouseDownEvent e) => true;
protected override void PopIn()
{
this.FadeIn(TRANSITION_DURATION, Easing.OutQuint);
}
protected override void PopOut()
{
this.FadeOut(TRANSITION_DURATION, Easing.OutQuint);
}
public void DeleteItems(ISkinnableDrawable[] items)
{
foreach (var item in items)
availableTargets.FirstOrDefault(t => t.Components.Contains(item))?.Remove(item);
}
}
}
| |
/// <Licensing>
/// ?2011 (Copyright) Path-o-logical Games, LLC
/// Licensed under the Unity Asset Package Product License (the "License");
/// You may not use this file except in compliance with the License.
/// You may obtain a copy of the License at: http://licensing.path-o-logical.com
/// </Licensing>
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//using System.Diagnostics;
namespace PathologicalGames
{
/// <description>
/// PoolManager v2.0
/// - PoolManager.Pools is not a complete implimentation of the IDictionary interface
/// Which enabled:
/// * Much more acurate and clear error handling
/// * Member access protection so you can't run anything you aren't supposed to.
/// - Moved all functions for working with Pools from PoolManager to PoolManager.Pools
/// which enabled shorter names to reduces the length of lines of code.
/// Online Docs: http://docs.poolmanager2.path-o-logical.com
/// </description>
public static class PoolManager
{
public static readonly SpawnPoolsDict Pools = new SpawnPoolsDict();
}
public static class PoolManagerUtils
{
internal static void SetActive(GameObject obj, bool state)
{
#if (UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0)
obj.SetActiveRecursively(state);
#else
obj.SetActive(state);
#endif
}
internal static bool activeInHierarchy(GameObject obj)
{
#if (UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0)
return obj.active;
#else
return obj.activeInHierarchy;
#endif
}
}
public class SpawnPoolsDict : IDictionary<string, SpawnPool>
{
#region Event Handling
public delegate void OnCreatedDelegate(SpawnPool pool);
internal Dictionary<string, OnCreatedDelegate> onCreatedDelegates =
new Dictionary<string, OnCreatedDelegate>();
public void AddOnCreatedDelegate(string poolName, OnCreatedDelegate createdDelegate)
{
// Assign first delegate "just in time"
if (!this.onCreatedDelegates.ContainsKey(poolName))
{
this.onCreatedDelegates.Add(poolName, createdDelegate);
return;
}
this.onCreatedDelegates[poolName] += createdDelegate;
}
public void RemoveOnCreatedDelegate(string poolName, OnCreatedDelegate createdDelegate)
{
if (!this.onCreatedDelegates.ContainsKey(poolName))
throw new KeyNotFoundException
(
"No OnCreatedDelegates found for pool name '" + poolName + "'."
);
this.onCreatedDelegates[poolName] -= createdDelegate;
}
#endregion Event Handling
#region Public Custom Memebers
/// <summary>
/// Creates a new GameObject with a SpawnPool Component which registers itself
/// with the PoolManager.Pools dictionary. The SpawnPool can then be accessed
/// directly via the return value of this function or by via the PoolManager.Pools
/// dictionary using a 'key' (string : the name of the pool, SpawnPool.poolName).
/// </summary>
/// <param name="poolName">
/// The name for the new SpawnPool. The GameObject will have the word "Pool"
/// Added at the end.
/// </param>
/// <returns>A reference to the new SpawnPool component</returns>
public SpawnPool Create(string poolName)
{
// Add "Pool" to the end of the poolName to make a more user-friendly
// GameObject name. This gets stripped back out in SpawnPool Awake()
var owner = new GameObject(poolName + "Pool");
return owner.AddComponent<SpawnPool>();
}
/// <summary>
///Creates a SpawnPool Component on an 'owner' GameObject which registers
/// itself with the PoolManager.Pools dictionary. The SpawnPool can then be
/// accessed directly via the return value of this function or via the
/// PoolManager.Pools dictionary.
/// </summary>
/// <param name="poolName">
/// The name for the new SpawnPool. The GameObject will have the word "Pool"
/// Added at the end.
/// </param>
/// <param name="owner">A GameObject to add the SpawnPool Component</param>
/// <returns>A reference to the new SpawnPool component</returns>
public SpawnPool Create(string poolName, GameObject owner)
{
if (!this.assertValidPoolName(poolName))
return null;
// When the SpawnPool is created below, there is no way to set the poolName
// before awake runs. The SpawnPool will use the gameObject name by default
// so a try statement is used to temporarily change the parent's name in a
// safe way. The finally block will always run, even if there is an error.
string ownerName = owner.gameObject.name;
try
{
owner.gameObject.name = poolName;
// Note: This will use SpawnPool.Awake() to finish init and self-add the pool
return owner.AddComponent<SpawnPool>();
}
finally
{
// Runs no matter what
owner.gameObject.name = ownerName;
}
}
/// <summary>
/// Used to ensure a name is valid before creating anything.
/// </summary>
/// <param name="poolName">The name to test</param>
/// <returns>True if sucessful, false if failed.</returns>
private bool assertValidPoolName(string poolName)
{
// Cannot request a name with the word "Pool" in it. This would be a
// rundundant naming convention and is a reserved word for GameObject
// defaul naming
string tmpPoolName;
tmpPoolName = poolName.Replace("Pool", "");
if (tmpPoolName != poolName) // Warn if "Pool" was used in poolName
{
// Log a warning and continue on with the fixed name
string msg = string.Format("'{0}' has the word 'Pool' in it. " +
"This word is reserved for GameObject defaul naming. " +
"The pool name has been changed to '{1}'",
poolName, tmpPoolName);
Debug.LogWarning(msg);
poolName = tmpPoolName;
}
if (this.ContainsKey(poolName))
{
Debug.Log(string.Format("A pool with the name '{0}' already exists",
poolName));
return false;
}
return true;
}
/// <summary>
/// Returns a formatted string showing all the pool names
/// </summary>
/// <returns></returns>
public override string ToString()
{
// Get a string[] array of the keys for formatting with join()
var keysArray = new string[this._pools.Count];
this._pools.Keys.CopyTo(keysArray, 0);
// Return a comma-sperated list inside square brackets (Pythonesque)
return string.Format("[{0}]", System.String.Join(", ", keysArray));
}
/// <summary>
/// Destroy an entire SpawnPool, including its GameObject and all children.
/// You can also just destroy the GameObject directly to achieve the same result.
/// This is really only here to make it easier when a reference isn't at hand.
/// </summary>
/// <param name="spawnPool"></param>
public bool Destroy(string poolName)
{
// Use TryGetValue to avoid KeyNotFoundException.
// This is faster than Contains() and then accessing the dictionary
SpawnPool spawnPool;
if (!this._pools.TryGetValue(poolName, out spawnPool))
{
Debug.LogError(
string.Format("PoolManager: Unable to destroy '{0}'. Not in PoolManager",
poolName));
return false;
}
// The rest of the logic will be handled by OnDestroy() in SpawnPool
UnityEngine.Object.Destroy(spawnPool.gameObject);
// Remove it from the dict in case the user re-creates a SpawnPool of the
// same name later
//this._pools.Remove(spawnPool.poolName);
return true;
}
/// <summary>
/// Destroy ALL SpawnPools, including their GameObjects and all children.
/// You can also just destroy the GameObjects directly to achieve the same result.
/// This is really only here to make it easier when a reference isn't at hand.
/// </summary>
/// <param name="spawnPool"></param>
public void DestroyAll()
{
foreach (KeyValuePair<string, SpawnPool> pair in this._pools)
UnityEngine.Object.Destroy(pair.Value);
// Clear the dict in case the user re-creates a SpawnPool of the same name later
this._pools.Clear();
}
#endregion Public Custom Memebers
#region Dict Functionality
// Internal (wrapped) dictionary
private Dictionary<string, SpawnPool> _pools = new Dictionary<string, SpawnPool>();
/// <summary>
/// Used internally by SpawnPools to add themseleves on Awake().
/// Use PoolManager.CreatePool() to create an entirely new SpawnPool GameObject
/// </summary>
/// <param name="spawnPool"></param>
internal void Add(SpawnPool spawnPool)
{
// Don't let two pools with the same name be added. See error below for details
int _id = 0;
string _name = spawnPool.poolName;
while (this.ContainsKey(spawnPool.poolName))
{
//Debug.LogWarning(string.Format("A pool with the name '{0}' already exists. " +
// "This should only happen if a SpawnPool with " +
// "this name is added to a scene twice.",
// spawnPool.poolName));
//return;
spawnPool.poolName = _name + "_" + _id.ToString();
_id++;
}
this._pools.Add(spawnPool.poolName, spawnPool);
if (this.onCreatedDelegates.ContainsKey(spawnPool.poolName))
this.onCreatedDelegates[spawnPool.poolName](spawnPool);
}
// Keeping here so I remember we have a NotImplimented overload (original signature)
public void Add(string key, SpawnPool value)
{
string msg = "SpawnPools add themselves to PoolManager.Pools when created, so " +
"there is no need to Add() them explicitly. Create pools using " +
"PoolManager.Pools.Create() or add a SpawnPool component to a " +
"GameObject.";
throw new System.NotImplementedException(msg);
}
/// <summary>
/// Used internally by SpawnPools to remove themseleves on Destroy().
/// Use PoolManager.Destroy() to destroy an entire SpawnPool GameObject.
/// </summary>
/// <param name="spawnPool"></param>
internal bool Remove(SpawnPool spawnPool)
{
if (!this.ContainsKey(spawnPool.poolName))
{
Debug.LogError(string.Format("PoolManager: Unable to remove '{0}'. " +
"Pool not in PoolManager",
spawnPool.poolName));
return false;
}
this._pools.Remove(spawnPool.poolName);
return true;
}
// Keeping here so I remember we have a NotImplimented overload (original signature)
public bool Remove(string poolName)
{
string msg = "SpawnPools can only be destroyed, not removed and kept alive" +
" outside of PoolManager. There are only 2 legal ways to destroy " +
"a SpawnPool: Destroy the GameObject directly, if you have a " +
"reference, or use PoolManager.Destroy(string poolName).";
throw new System.NotImplementedException(msg);
}
/// <summary>
/// Get the number of SpawnPools in PoolManager
/// </summary>
public int Count { get { return this._pools.Count; } }
/// <summary>
/// Returns true if a pool exists with the passed pool name.
/// </summary>
/// <param name="poolName">The name to look for</param>
/// <returns>True if the pool exists, otherwise, false.</returns>
public bool ContainsKey(string poolName)
{
return this._pools.ContainsKey(poolName);
}
/// <summary>
/// Used to get a SpawnPool when the user is not sure if the pool name is used.
/// This is faster than checking IsPool(poolName) and then accessing Pools][poolName.]
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool TryGetValue(string poolName, out SpawnPool spawnPool)
{
return this._pools.TryGetValue(poolName, out spawnPool);
}
#region Not Implimented
public bool Contains(KeyValuePair<string, SpawnPool> item)
{
string msg = "Use PoolManager.Pools.Contains(string poolName) instead.";
throw new System.NotImplementedException(msg);
}
public SpawnPool this[string key]
{
get
{
SpawnPool pool;
try
{
pool = this._pools[key];
}
catch (KeyNotFoundException)
{
/*string msg = string.Format("A Pool with the name '{0}' not found. " +
"\nPools={1}",
key, this.ToString());
throw new KeyNotFoundException(msg);*/
return null;
}
return pool;
}
set
{
string msg = "Cannot set PoolManager.Pools[key] directly. " +
"SpawnPools add themselves to PoolManager.Pools when created, so " +
"there is no need to set them explicitly. Create pools using " +
"PoolManager.Pools.Create() or add a SpawnPool component to a " +
"GameObject.";
throw new System.NotImplementedException(msg);
}
}
public ICollection<string> Keys
{
get
{
string msg = "If you need this, please request it.";
throw new System.NotImplementedException(msg);
}
}
public ICollection<SpawnPool> Values
{
get
{
string msg = "If you need this, please request it.";
throw new System.NotImplementedException(msg);
}
}
#region ICollection<KeyValuePair<string,SpawnPool>> Members
private bool IsReadOnly { get { return true; } }
bool ICollection<KeyValuePair<string, SpawnPool>>.IsReadOnly { get { return true; } }
public void Add(KeyValuePair<string, SpawnPool> item)
{
string msg = "SpawnPools add themselves to PoolManager.Pools when created, so " +
"there is no need to Add() them explicitly. Create pools using " +
"PoolManager.Pools.Create() or add a SpawnPool component to a " +
"GameObject.";
throw new System.NotImplementedException(msg);
}
public void Clear()
{
string msg = "Use PoolManager.Pools.DestroyAll() instead.";
throw new System.NotImplementedException(msg);
}
private void CopyTo(KeyValuePair<string, SpawnPool>[] array, int arrayIndex)
{
string msg = "PoolManager.Pools cannot be copied";
throw new System.NotImplementedException(msg);
}
void ICollection<KeyValuePair<string, SpawnPool>>.CopyTo(KeyValuePair<string, SpawnPool>[] array, int arrayIndex)
{
string msg = "PoolManager.Pools cannot be copied";
throw new System.NotImplementedException(msg);
}
public bool Remove(KeyValuePair<string, SpawnPool> item)
{
string msg = "SpawnPools can only be destroyed, not removed and kept alive" +
" outside of PoolManager. There are only 2 legal ways to destroy " +
"a SpawnPool: Destroy the GameObject directly, if you have a " +
"reference, or use PoolManager.Destroy(string poolName).";
throw new System.NotImplementedException(msg);
}
#endregion ICollection<KeyValuePair<string, SpawnPool>> Members
#endregion Not Implimented
#region IEnumerable<KeyValuePair<string,SpawnPool>> Members
public IEnumerator<KeyValuePair<string, SpawnPool>> GetEnumerator()
{
return this._pools.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this._pools.GetEnumerator();
}
#endregion
#endregion Dict Functionality
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// BindingResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Chat.V2.Service
{
public class BindingResource : Resource
{
public sealed class BindingTypeEnum : StringEnum
{
private BindingTypeEnum(string value) : base(value) {}
public BindingTypeEnum() {}
public static implicit operator BindingTypeEnum(string value)
{
return new BindingTypeEnum(value);
}
public static readonly BindingTypeEnum Gcm = new BindingTypeEnum("gcm");
public static readonly BindingTypeEnum Apn = new BindingTypeEnum("apn");
public static readonly BindingTypeEnum Fcm = new BindingTypeEnum("fcm");
}
private static Request BuildReadRequest(ReadBindingOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Bindings",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Binding parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Binding </returns>
public static ResourceSet<BindingResource> Read(ReadBindingOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<BindingResource>.FromJson("bindings", response.Content);
return new ResourceSet<BindingResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Binding parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Binding </returns>
public static async System.Threading.Tasks.Task<ResourceSet<BindingResource>> ReadAsync(ReadBindingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<BindingResource>.FromJson("bindings", response.Content);
return new ResourceSet<BindingResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="bindingType"> The push technology used by the Binding resources to read </param>
/// <param name="identity"> The `identity` value of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Binding </returns>
public static ResourceSet<BindingResource> Read(string pathServiceSid,
List<BindingResource.BindingTypeEnum> bindingType = null,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadBindingOptions(pathServiceSid){BindingType = bindingType, Identity = identity, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="bindingType"> The push technology used by the Binding resources to read </param>
/// <param name="identity"> The `identity` value of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Binding </returns>
public static async System.Threading.Tasks.Task<ResourceSet<BindingResource>> ReadAsync(string pathServiceSid,
List<BindingResource.BindingTypeEnum> bindingType = null,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadBindingOptions(pathServiceSid){BindingType = bindingType, Identity = identity, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<BindingResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<BindingResource>.FromJson("bindings", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<BindingResource> NextPage(Page<BindingResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<BindingResource>.FromJson("bindings", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<BindingResource> PreviousPage(Page<BindingResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<BindingResource>.FromJson("bindings", response.Content);
}
private static Request BuildFetchRequest(FetchBindingOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Bindings/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Binding parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Binding </returns>
public static BindingResource Fetch(FetchBindingOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Binding parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Binding </returns>
public static async System.Threading.Tasks.Task<BindingResource> FetchAsync(FetchBindingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathSid"> The SID of the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Binding </returns>
public static BindingResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchBindingOptions(pathServiceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathSid"> The SID of the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Binding </returns>
public static async System.Threading.Tasks.Task<BindingResource> FetchAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchBindingOptions(pathServiceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteBindingOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Chat,
"/v2/Services/" + options.PathServiceSid + "/Bindings/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Binding parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Binding </returns>
public static bool Delete(DeleteBindingOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Binding parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Binding </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteBindingOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathSid"> The SID of the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Binding </returns>
public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteBindingOptions(pathServiceSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathSid"> The SID of the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Binding </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteBindingOptions(pathServiceSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a BindingResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> BindingResource object represented by the provided JSON </returns>
public static BindingResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<BindingResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Service that the Binding resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The unique endpoint identifier for the Binding
/// </summary>
[JsonProperty("endpoint")]
public string Endpoint { get; private set; }
/// <summary>
/// The string that identifies the resource's User
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// The SID of the Credential for the binding
/// </summary>
[JsonProperty("credential_sid")]
public string CredentialSid { get; private set; }
/// <summary>
/// The push technology to use for the binding
/// </summary>
[JsonProperty("binding_type")]
[JsonConverter(typeof(StringEnumConverter))]
public BindingResource.BindingTypeEnum BindingType { get; private set; }
/// <summary>
/// The Programmable Chat message types the binding is subscribed to
/// </summary>
[JsonProperty("message_types")]
public List<string> MessageTypes { get; private set; }
/// <summary>
/// The absolute URL of the Binding resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The absolute URLs of the Binding's User
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private BindingResource()
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public partial class AutomationManagementClient : ServiceClient<AutomationManagementClient>, IAutomationManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private string _resourceNamespace;
/// <summary>
/// Gets or sets the resource namespace.
/// </summary>
public string ResourceNamespace
{
get { return this._resourceNamespace; }
set { this._resourceNamespace = value; }
}
private IActivityOperations _activities;
/// <summary>
/// Service operation for automation activities. (see
/// http://aka.ms/azureautomationsdk/activityoperations for more
/// information)
/// </summary>
public virtual IActivityOperations Activities
{
get { return this._activities; }
}
private IAgentRegistrationOperation _agentRegistrationInformation;
/// <summary>
/// Service operation for automation agent registration information.
/// (see http://aka.ms/azureautomationsdk/agentregistrationoperations
/// for more information)
/// </summary>
public virtual IAgentRegistrationOperation AgentRegistrationInformation
{
get { return this._agentRegistrationInformation; }
}
private IAutomationAccountOperations _automationAccounts;
/// <summary>
/// Service operation for automation accounts. (see
/// http://aka.ms/azureautomationsdk/automationaccountoperations for
/// more information)
/// </summary>
public virtual IAutomationAccountOperations AutomationAccounts
{
get { return this._automationAccounts; }
}
private ICertificateOperations _certificates;
/// <summary>
/// Service operation for automation certificates. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
public virtual ICertificateOperations Certificates
{
get { return this._certificates; }
}
private IConnectionOperations _connections;
/// <summary>
/// Service operation for automation connections. (see
/// http://aka.ms/azureautomationsdk/connectionoperations for more
/// information)
/// </summary>
public virtual IConnectionOperations Connections
{
get { return this._connections; }
}
private IConnectionTypeOperations _connectionTypes;
/// <summary>
/// Service operation for automation connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
public virtual IConnectionTypeOperations ConnectionTypes
{
get { return this._connectionTypes; }
}
private ICredentialOperations _psCredentials;
/// <summary>
/// Service operation for automation credentials. (see
/// http://aka.ms/azureautomationsdk/credentialoperations for more
/// information)
/// </summary>
public virtual ICredentialOperations PsCredentials
{
get { return this._psCredentials; }
}
private IDscCompilationJobOperations _compilationJobs;
/// <summary>
/// Service operation for automation dsc configuration compile jobs.
/// (see
/// http://aka.ms/azureautomationsdk/dscccompilationjoboperations for
/// more information)
/// </summary>
public virtual IDscCompilationJobOperations CompilationJobs
{
get { return this._compilationJobs; }
}
private IDscConfigurationOperations _configurations;
/// <summary>
/// Service operation for configurations. (see
/// http://aka.ms/azureautomationsdk/configurationoperations for more
/// information)
/// </summary>
public virtual IDscConfigurationOperations Configurations
{
get { return this._configurations; }
}
private IDscNodeConfigurationOperations _nodeConfigurations;
/// <summary>
/// Service operation for automation dsc node configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
public virtual IDscNodeConfigurationOperations NodeConfigurations
{
get { return this._nodeConfigurations; }
}
private IDscNodeOperations _nodes;
/// <summary>
/// Service operation for dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
public virtual IDscNodeOperations Nodes
{
get { return this._nodes; }
}
private IDscNodeReportsOperations _nodeReports;
/// <summary>
/// Service operation for node reports. (see
/// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
/// information)
/// </summary>
public virtual IDscNodeReportsOperations NodeReports
{
get { return this._nodeReports; }
}
private IHybridRunbookWorkerGroupOperations _hybridRunbookWorkerGroups;
/// <summary>
/// Service operation for automation hybrid runbook worker group. (see
/// http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations
/// for more information)
/// </summary>
public virtual IHybridRunbookWorkerGroupOperations HybridRunbookWorkerGroups
{
get { return this._hybridRunbookWorkerGroups; }
}
private IJobOperations _jobs;
/// <summary>
/// Service operation for automation jobs. (see
/// http://aka.ms/azureautomationsdk/joboperations for more
/// information)
/// </summary>
public virtual IJobOperations Jobs
{
get { return this._jobs; }
}
private IJobScheduleOperations _jobSchedules;
/// <summary>
/// Service operation for automation job schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
public virtual IJobScheduleOperations JobSchedules
{
get { return this._jobSchedules; }
}
private IJobStreamOperations _jobStreams;
/// <summary>
/// Service operation for automation job streams. (see
/// http://aka.ms/azureautomationsdk/jobstreamoperations for more
/// information)
/// </summary>
public virtual IJobStreamOperations JobStreams
{
get { return this._jobStreams; }
}
private IModuleOperations _modules;
/// <summary>
/// Service operation for automation modules. (see
/// http://aka.ms/azureautomationsdk/moduleoperations for more
/// information)
/// </summary>
public virtual IModuleOperations Modules
{
get { return this._modules; }
}
private IRunbookDraftOperations _runbookDraft;
/// <summary>
/// Service operation for automation runbook draft. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
public virtual IRunbookDraftOperations RunbookDraft
{
get { return this._runbookDraft; }
}
private IRunbookOperations _runbooks;
/// <summary>
/// Service operation for automation runbooks. (see
/// http://aka.ms/azureautomationsdk/runbookoperations for more
/// information)
/// </summary>
public virtual IRunbookOperations Runbooks
{
get { return this._runbooks; }
}
private IScheduleOperations _schedules;
/// <summary>
/// Service operation for automation schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
public virtual IScheduleOperations Schedules
{
get { return this._schedules; }
}
private ITestJobOperations _testJobs;
/// <summary>
/// Service operation for automation test jobs. (see
/// http://aka.ms/azureautomationsdk/testjoboperations for more
/// information)
/// </summary>
public virtual ITestJobOperations TestJobs
{
get { return this._testJobs; }
}
private IVariableOperations _variables;
/// <summary>
/// Service operation for automation variables. (see
/// http://aka.ms/azureautomationsdk/variableoperations for more
/// information)
/// </summary>
public virtual IVariableOperations Variables
{
get { return this._variables; }
}
private IWebhookOperations _webhooks;
/// <summary>
/// Service operation for automation webhook. (see
/// http://aka.ms/azureautomationsdk/webhookoperations for more
/// information)
/// </summary>
public virtual IWebhookOperations Webhooks
{
get { return this._webhooks; }
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
public AutomationManagementClient()
: base()
{
this._activities = new ActivityOperations(this);
this._agentRegistrationInformation = new AgentRegistrationOperation(this);
this._automationAccounts = new AutomationAccountOperations(this);
this._certificates = new CertificateOperations(this);
this._connections = new ConnectionOperations(this);
this._connectionTypes = new ConnectionTypeOperations(this);
this._psCredentials = new CredentialOperations(this);
this._compilationJobs = new DscCompilationJobOperations(this);
this._configurations = new DscConfigurationOperations(this);
this._nodeConfigurations = new DscNodeConfigurationOperations(this);
this._nodes = new DscNodeOperations(this);
this._nodeReports = new DscNodeReportsOperations(this);
this._hybridRunbookWorkerGroups = new HybridRunbookWorkerGroupOperations(this);
this._jobs = new JobOperations(this);
this._jobSchedules = new JobScheduleOperations(this);
this._jobStreams = new JobStreamOperations(this);
this._modules = new ModuleOperations(this);
this._runbookDraft = new RunbookDraftOperations(this);
this._runbooks = new RunbookOperations(this);
this._schedules = new ScheduleOperations(this);
this._testJobs = new TestJobOperations(this);
this._variables = new VariableOperations(this);
this._webhooks = new WebhookOperations(this);
this._resourceNamespace = "Microsoft.Automation";
this._apiVersion = "2014-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._activities = new ActivityOperations(this);
this._agentRegistrationInformation = new AgentRegistrationOperation(this);
this._automationAccounts = new AutomationAccountOperations(this);
this._certificates = new CertificateOperations(this);
this._connections = new ConnectionOperations(this);
this._connectionTypes = new ConnectionTypeOperations(this);
this._psCredentials = new CredentialOperations(this);
this._compilationJobs = new DscCompilationJobOperations(this);
this._configurations = new DscConfigurationOperations(this);
this._nodeConfigurations = new DscNodeConfigurationOperations(this);
this._nodes = new DscNodeOperations(this);
this._nodeReports = new DscNodeReportsOperations(this);
this._hybridRunbookWorkerGroups = new HybridRunbookWorkerGroupOperations(this);
this._jobs = new JobOperations(this);
this._jobSchedules = new JobScheduleOperations(this);
this._jobStreams = new JobStreamOperations(this);
this._modules = new ModuleOperations(this);
this._runbookDraft = new RunbookDraftOperations(this);
this._runbooks = new RunbookOperations(this);
this._schedules = new ScheduleOperations(this);
this._testJobs = new TestJobOperations(this);
this._variables = new VariableOperations(this);
this._webhooks = new WebhookOperations(this);
this._resourceNamespace = "Microsoft.Automation";
this._apiVersion = "2014-06-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AutomationManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AutomationManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// AutomationManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of AutomationManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<AutomationManagementClient> client)
{
base.Clone(client);
if (client is AutomationManagementClient)
{
AutomationManagementClient clonedClient = ((AutomationManagementClient)client);
clonedClient._resourceNamespace = this._resourceNamespace;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <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'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> GetOperationResultStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetOperationResultStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
result = new LongRunningOperationResultResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.BadRequest)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.NotFound)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.NoContent)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Operation Status operation returns the status of
/// thespecified 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. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<LongRunningOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
}
url = url + "/operations/";
url = url + Uri.EscapeDataString(requestId);
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LongRunningOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
LongRunningOperationStatusResponse.ErrorDetails errorInstance = new LongRunningOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class OverrideReturnAddress : IEquatable<OverrideReturnAddress>
{
/// <summary>
/// Initializes a new instance of the <see cref="OverrideReturnAddress" /> class.
/// Initializes a new instance of the <see cref="OverrideReturnAddress" />class.
/// </summary>
/// <param name="LobId">LobId (required).</param>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="OrderSourceId">OrderSourceId (required).</param>
/// <param name="Name">Name (required).</param>
/// <param name="Attention">Attention.</param>
/// <param name="Street">Street (required).</param>
/// <param name="Street2">Street2.</param>
/// <param name="City">City (required).</param>
/// <param name="State">State (required).</param>
/// <param name="Zip">Zip (required).</param>
/// <param name="Country">Country.</param>
/// <param name="Phone">Phone (required).</param>
/// <param name="CustomFields">CustomFields.</param>
public OverrideReturnAddress(int? LobId = null, int? WarehouseId = null, int? OrderSourceId = null, string Name = null, string Attention = null, string Street = null, string Street2 = null, string City = null, string State = null, string Zip = null, string Country = null, string Phone = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "LobId" is required (not null)
if (LobId == null)
{
throw new InvalidDataException("LobId is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.LobId = LobId;
}
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
// to ensure "OrderSourceId" is required (not null)
if (OrderSourceId == null)
{
throw new InvalidDataException("OrderSourceId is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.OrderSourceId = OrderSourceId;
}
// to ensure "Name" is required (not null)
if (Name == null)
{
throw new InvalidDataException("Name is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.Name = Name;
}
// to ensure "Street" is required (not null)
if (Street == null)
{
throw new InvalidDataException("Street is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.Street = Street;
}
// to ensure "City" is required (not null)
if (City == null)
{
throw new InvalidDataException("City is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.City = City;
}
// to ensure "State" is required (not null)
if (State == null)
{
throw new InvalidDataException("State is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.State = State;
}
// to ensure "Zip" is required (not null)
if (Zip == null)
{
throw new InvalidDataException("Zip is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.Zip = Zip;
}
// to ensure "Phone" is required (not null)
if (Phone == null)
{
throw new InvalidDataException("Phone is a required property for OverrideReturnAddress and cannot be null");
}
else
{
this.Phone = Phone;
}
this.Attention = Attention;
this.Street2 = Street2;
this.Country = Country;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets OrderSourceId
/// </summary>
[DataMember(Name="orderSourceId", EmitDefaultValue=false)]
public int? OrderSourceId { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Attention
/// </summary>
[DataMember(Name="attention", EmitDefaultValue=false)]
public string Attention { get; set; }
/// <summary>
/// Gets or Sets Street
/// </summary>
[DataMember(Name="street", EmitDefaultValue=false)]
public string Street { get; set; }
/// <summary>
/// Gets or Sets Street2
/// </summary>
[DataMember(Name="street2", EmitDefaultValue=false)]
public string Street2 { get; set; }
/// <summary>
/// Gets or Sets City
/// </summary>
[DataMember(Name="city", EmitDefaultValue=false)]
public string City { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public string State { get; set; }
/// <summary>
/// Gets or Sets Zip
/// </summary>
[DataMember(Name="zip", EmitDefaultValue=false)]
public string Zip { get; set; }
/// <summary>
/// Gets or Sets Country
/// </summary>
[DataMember(Name="country", EmitDefaultValue=false)]
public string Country { get; set; }
/// <summary>
/// Gets or Sets Phone
/// </summary>
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OverrideReturnAddress {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" OrderSourceId: ").Append(OrderSourceId).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Attention: ").Append(Attention).Append("\n");
sb.Append(" Street: ").Append(Street).Append("\n");
sb.Append(" Street2: ").Append(Street2).Append("\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Zip: ").Append(Zip).Append("\n");
sb.Append(" Country: ").Append(Country).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OverrideReturnAddress);
}
/// <summary>
/// Returns true if OverrideReturnAddress instances are equal
/// </summary>
/// <param name="other">Instance of OverrideReturnAddress to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OverrideReturnAddress other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.OrderSourceId == other.OrderSourceId ||
this.OrderSourceId != null &&
this.OrderSourceId.Equals(other.OrderSourceId)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Attention == other.Attention ||
this.Attention != null &&
this.Attention.Equals(other.Attention)
) &&
(
this.Street == other.Street ||
this.Street != null &&
this.Street.Equals(other.Street)
) &&
(
this.Street2 == other.Street2 ||
this.Street2 != null &&
this.Street2.Equals(other.Street2)
) &&
(
this.City == other.City ||
this.City != null &&
this.City.Equals(other.City)
) &&
(
this.State == other.State ||
this.State != null &&
this.State.Equals(other.State)
) &&
(
this.Zip == other.Zip ||
this.Zip != null &&
this.Zip.Equals(other.Zip)
) &&
(
this.Country == other.Country ||
this.Country != null &&
this.Country.Equals(other.Country)
) &&
(
this.Phone == other.Phone ||
this.Phone != null &&
this.Phone.Equals(other.Phone)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.OrderSourceId != null)
hash = hash * 59 + this.OrderSourceId.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Attention != null)
hash = hash * 59 + this.Attention.GetHashCode();
if (this.Street != null)
hash = hash * 59 + this.Street.GetHashCode();
if (this.Street2 != null)
hash = hash * 59 + this.Street2.GetHashCode();
if (this.City != null)
hash = hash * 59 + this.City.GetHashCode();
if (this.State != null)
hash = hash * 59 + this.State.GetHashCode();
if (this.Zip != null)
hash = hash * 59 + this.Zip.GetHashCode();
if (this.Country != null)
hash = hash * 59 + this.Country.GetHashCode();
if (this.Phone != null)
hash = hash * 59 + this.Phone.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class InputManager : MonoBehaviour {
private Character character;
private UIHandler UI;
[SerializeField] private string controllerType = "Keyboard";
private char osType;
private bool[] inputFlags;
private bool initialRTrigger = true; // True until trigger has been pressed, expressly for 360 on mac
private bool initialLTrigger = true;
private bool overclockAxisInUse = false; // Toggle, not hold
private char[] latestKeys = { '0', '0', '0', '0' }; // 0
private Dictionary<string, string> inputs = new Dictionary<string, string>();
private void Awake()
{
//get UI script
UI = GameObject.Find("Main Camera").GetComponent<UIHandler>();
// INPUT FLAGS, IN ORDER: SLICE[0], ATTACK[1], DEFLECT[2], DASH[3], OVERCLOCK[4], FIRE[5], INTERACT[6]
inputFlags = new bool[] { false, false, false, false, false, false, false };
character = GetComponent<Character>();
if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) // Set OS type
{
osType = 'w';
initialRTrigger = false;
initialLTrigger = false;
}
else if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXDashboardPlayer)
{
osType = 'm';
}
else if (Application.platform == RuntimePlatform.LinuxPlayer)
{
osType = 'l';
controllerType = "Keyboard";
initialRTrigger = false;
initialLTrigger = false;
}
else
{
throw new System.ArgumentException("This OS is not supported", "e");
}
}
void Start()
{
SetInputDevice(controllerType); // Set initial scheme
}
//update is called once per frame
private void Update()
{
//Checks for pausing
if(Input.GetButtonDown(inputs["Pause"]))
{
if (UI.IsGamePaused) UI.SetPaused(false);
else UI.SetPaused(true);
}
if (!inputFlags[0]) // Slice
{
if (controllerType != "Keyboard" && (osType == 'w' || initialRTrigger))
{
inputFlags[0] = Input.GetButton(inputs["Slice"]) || Input.GetAxis(inputs["Slice2"]) > 0;
if (initialRTrigger) initialRTrigger = false;
}
else if (controllerType != "Keyboard" && !initialRTrigger) inputFlags[0] = Input.GetButton(inputs["Slice"]) || Input.GetAxis(inputs["Slice2"]) > -1;
else inputFlags[0] = Input.GetButton(inputs["Slice"]);
}
if (!inputFlags[1]) // Attack
{
inputFlags[1] = Input.GetButtonDown(inputs["Attack"]);
}
if (!inputFlags[2]) // Deflect
{
inputFlags[2] = Input.GetButtonDown(inputs["Deflect"]);
}
if (!inputFlags[3]) // Interact
{
if ((controllerType == "Xbox360A" || controllerType == "PS4A") && osType == 'w') inputFlags[3] = Input.GetAxis(inputs["Interact"]) < 0;
else inputFlags[3] = Input.GetButton(inputs["Interact"]);
}
if (!inputFlags[4]) // Overclock
{
if ((controllerType == "Xbox360B" || controllerType == "PS4B") && osType == 'w')
{
if (Input.GetAxis(inputs["Overclock"]) < 0) // This is the code for using getaxis the same way as getbuttondown
{
if (overclockAxisInUse == false)
{
inputFlags[4] = Input.GetAxis(inputs["Overclock"]) < 0;
overclockAxisInUse = true;
}
}
else overclockAxisInUse = false;
}
else inputFlags[4] = Input.GetButtonDown(inputs["Overclock"]);
}
if (!inputFlags[5]) // Fire
{
inputFlags[5] = Input.GetButton(inputs["Fire"]);
}
if (!inputFlags[6]) // Dash
{
if (controllerType != "Keyboard" && (osType == 'w' || initialLTrigger)) // Mac triggers for 360 start at 0 then range from -1 to 1, Triggers are treated as axes for all controllers
{
inputFlags[6] = Input.GetButton(inputs["Dash"]) || Input.GetAxis(inputs["Dash2"]) > 0; // Change to get down if on press is desired rather than continuous
if (initialLTrigger) initialLTrigger = false;
}
else if (controllerType != "Keyboard" && !initialLTrigger) inputFlags[6] = Input.GetButton(inputs["Dash"]) || Input.GetAxis(inputs["Dash2"]) > -1;
else inputFlags[6] = Input.GetButton(inputs["Dash"]);
}
if (controllerType == "Keyboard")
{
if (Input.GetButtonDown(inputs["HorizontalMove"]) && Input.GetAxisRaw(inputs["HorizontalMove"]) > 0) // D
{
pushKey('d');
}
if (Input.GetButtonDown(inputs["HorizontalMove"]) && Input.GetAxisRaw(inputs["HorizontalMove"]) < 0) // A, set the latest key
{
pushKey('a');
}
if (Input.GetButtonDown(inputs["VerticalMove"]) && Input.GetAxisRaw(inputs["VerticalMove"]) > 0) // W
{
pushKey('w');
}
if (Input.GetButtonDown(inputs["VerticalMove"]) && Input.GetAxisRaw(inputs["VerticalMove"]) < 0) // S
{
pushKey('s');
}
checkIfLatest(); // Check if latestKey is valid
//Debug.Log(latestKey.ToString());
}
}
private void FixedUpdate()
{
if (UI.IsGamePaused) return;
// Read the inputs.
float hMove = Input.GetAxis(inputs["HorizontalMove"]); // Invert stuff here
float vMove = Input.GetAxis(inputs["VerticalMove"]);
if (controllerType != "Keyboard")
{
float hLook = Input.GetAxis(inputs["HorizontalLook"]); // Invert stuff here
float vLook = Input.GetAxis(inputs["VerticalLook"]);
if (osType == 'w') vLook = -vLook;
character.controllerMove(hMove, vMove, hLook, vLook);
}
else
{
Vector3 mousePos = Input.mousePosition;
character.keyboardMove(hMove, vMove, mousePos);
}
character.InputFlags = inputFlags; // Send input information, then reset it
for (int i=0;i<inputFlags.Length; i++) inputFlags[i] = false;
}
private void setControlScheme() // Sets the current control scheme; http://wiki.unity3d.com/index.php?title=Xbox360Controller, https://www.reddit.com/r/Unity3D/comments/1syswe/ps4_controller_map_for_unity/ (slightly wrong)
{
inputs.Clear(); // Empty current scheme
if (controllerType == "Keyboard" || osType == 'l') // Keyboard
{
inputs.Add("HorizontalMove", "KeyHorizontalMove");
inputs.Add("VerticalMove", "KeyVerticalMove");
inputs.Add("Slice", "Mouse2");
inputs.Add("Attack", "Mouse1");
inputs.Add("Fire", "F");
inputs.Add("Dash", "LSHIFT");
inputs.Add("Deflect", "R");
inputs.Add("Overclock", "SPACE");
inputs.Add("Interact", "E");
inputs.Add("Pause", "P");
}
else // Controller (Win and Mac only)
{
inputs.Add("HorizontalMove", "Axis1");
inputs.Add("VerticalMove", "Axis2");
if (osType == 'w')
{
if (controllerType == "Xbox360A")
{
inputs.Add("HorizontalLook", "Axis4");
inputs.Add("VerticalLook", "Axis5");
inputs.Add("Slice", "Button2");
inputs.Add("Attack", "Button3");
inputs.Add("Fire", "Button1");
inputs.Add("Dash", "Button0");
inputs.Add("Deflect", "Button5");
inputs.Add("Overclock", "Button4");
inputs.Add("Slice2", "Axis10");
inputs.Add("Dash2", "Axis9");
inputs.Add("Interact", "Axis7");
inputs.Add("Pause", "Button7");
}
else if (controllerType == "Xbox360B")
{
inputs.Add("HorizontalLook", "Axis4");
inputs.Add("VerticalLook", "Axis5");
inputs.Add("Slice", "Button2");
inputs.Add("Attack", "Button3");
inputs.Add("Fire", "Button4");
inputs.Add("Dash", "Button0");
inputs.Add("Deflect", "Button5");
inputs.Add("Overclock", "Axis7");
inputs.Add("Slice2", "Axis10");
inputs.Add("Dash2", "Axis9");
inputs.Add("Interact", "Button1");
inputs.Add("Pause", "Button7");
}
else if (controllerType == "PS4A")
{
inputs.Add("HorizontalLook", "Axis3");
inputs.Add("VerticalLook", "Axis6");
inputs.Add("Slice", "Button0");
inputs.Add("Attack", "Button3");
inputs.Add("Fire", "Button2");
inputs.Add("Dash", "Button1");
inputs.Add("Deflect", "Button5");
inputs.Add("Overclock", "Button4");
inputs.Add("Slice2", "Axis5");
inputs.Add("Dash2", "Axis4");
inputs.Add("Interact", "Axis8");
inputs.Add("Pause", "Button9");
}
else // PS4 B
{
inputs.Add("HorizontalLook", "Axis3");
inputs.Add("VerticalLook", "Axis6");
inputs.Add("Slice", "Button0");
inputs.Add("Attack", "Button3");
inputs.Add("Fire", "Button4");
inputs.Add("Dash", "Button1");
inputs.Add("Deflect", "Button5");
inputs.Add("Overclock", "Axis8");
inputs.Add("Slice2", "Axis5");
inputs.Add("Dash2", "Axis4");
inputs.Add("Interact", "Button2");
inputs.Add("Pause", "Button9");
}
}
else // Mac, can add linux controller support later if desired
{
if (controllerType == "Xbox360A")
{
inputs.Add("HorizontalLook", "Axis3");
inputs.Add("VerticalLook", "Axis4");
inputs.Add("Slice", "Button18");
inputs.Add("Attack", "Button19");
inputs.Add("Fire", "Button17");
inputs.Add("Dash", "Button16");
inputs.Add("Deflect", "Button14");
inputs.Add("Overclock", "Button13");
inputs.Add("Slice2", "Axis6");
inputs.Add("Dash2", "Axis5");
inputs.Add("Interact", "Button6");
inputs.Add("Pause", "Button9");
}
else // Xbox360 B
{
inputs.Add("HorizontalLook", "Axis3");
inputs.Add("VerticalLook", "Axis4");
inputs.Add("Slice", "Button18");
inputs.Add("Attack", "Button19");
inputs.Add("Fire", "Button13");
inputs.Add("Dash", "Button16");
inputs.Add("Deflect", "Button14");
inputs.Add("Overclock", "Buton6");
inputs.Add("Slice2", "Axis6");
inputs.Add("Dash2", "Axis5");
inputs.Add("Interact", "Button17");
inputs.Add("Pause", "Button9");
}
}
}
}
private void checkIfLatest() // Runs until the latest key is either nothing or is being pressed
{
if (latestKeys[0] == 'd' && !(Input.GetButton(inputs["HorizontalMove"]) && Input.GetAxisRaw(inputs["HorizontalMove"]) > 0)) // D, this is still cross platform, just using key chars for clarity
{
pushKey('0');
checkIfLatest();
}
if (latestKeys[0] == 'a' && !(Input.GetButton(inputs["HorizontalMove"]) && Input.GetAxisRaw(inputs["HorizontalMove"]) < 0)) // A, set the latest key
{
pushKey('0');
checkIfLatest();
}
if (latestKeys[0] == 'w' && !(Input.GetButton(inputs["VerticalMove"]) && Input.GetAxisRaw(inputs["VerticalMove"]) > 0)) // W
{
pushKey('0');
checkIfLatest();
}
if (latestKeys[0] == 's' && !(Input.GetButton(inputs["VerticalMove"]) && Input.GetAxisRaw(inputs["VerticalMove"]) < 0)) // S
{
pushKey('0');
checkIfLatest();
}
}
private void pushKey(char val) // Pushes a key into the latestKeys array
{
latestKeys[3] = latestKeys[2];
latestKeys[2] = latestKeys[1];
latestKeys[1] = latestKeys[0];
latestKeys[0] = val;
}
//changes the control scheme on the fly based on the UI buttons
public void SetInputDevice(string type)
{
UI.ChangeControlImages(type.ToLower()[0]);
controllerType = type;
setControlScheme();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace _05cTokenBasedAuthentication.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using InfluxDB.Net.Enums;
using InfluxDB.Net.Models;
using Tharga.InfluxCapacitor.Collector.Entities;
using Tharga.InfluxCapacitor.Collector.Event;
using Tharga.InfluxCapacitor.Collector.Interface;
namespace Tharga.InfluxCapacitor.Collector.Handlers
{
public abstract class CollectorEngineBase : ICollectorEngine, IDisposable
{
private readonly IPerformanceCounterGroup _performanceCounterGroup;
private readonly ISendBusiness _sendBusiness;
private readonly string _name;
private readonly ITag[] _tags;
private int _refreshCountdown;
private readonly Timer _timer;
protected readonly bool _metadata;
//TODO: Cleanup
protected DateTime? _timestamp; //TODO: Rename to first Read
private readonly string _engineName;
protected CollectorEngineBase(IPerformanceCounterGroup performanceCounterGroup, ISendBusiness sendBusiness, ITagLoader tagLoader, bool metadata)
{
_engineName = GetType().Name;
_performanceCounterGroup = performanceCounterGroup;
_name = _performanceCounterGroup.Name;
_sendBusiness = sendBusiness;
_tags = tagLoader.GetGlobalTags().Union(_performanceCounterGroup.Tags).ToArray();
if (performanceCounterGroup.SecondsInterval > 0)
{
_timer = new Timer(1000 * performanceCounterGroup.SecondsInterval);
_timer.Elapsed += Elapsed;
}
_metadata = metadata;
}
public event EventHandler<CollectRegisterCounterValuesEventArgs> CollectRegisterCounterValuesEvent;
protected string EngineName
{
get
{
return _engineName;
}
}
protected int SecondsInterval
{
get
{
return _performanceCounterGroup.SecondsInterval;
}
}
protected string Name
{
get
{
return _name;
}
}
private ITag[] Tags
{
get
{
return _tags;
}
}
public async Task StartAsync()
{
if (_timer == null) return;
await CollectRegisterCounterValuesAsync();
_timer.Start();
}
public void StopTimer()
{
_timer.Stop();
}
protected void ResumeTimer()
{
_timer.Start();
}
public abstract Task<int> CollectRegisterCounterValuesAsync();
private async void Elapsed(object sender, ElapsedEventArgs e)
{
await CollectRegisterCounterValuesAsync();
}
protected void Enqueue(Point[] points)
{
_sendBusiness.Enqueue(points);
}
protected IPerformanceCounterInfo[] PrepareCounters()
{
if (_refreshCountdown == 0)
{
_refreshCountdown = _performanceCounterGroup.RefreshInstanceInterval - 1;
return _performanceCounterGroup.GetFreshCounters().ToArray();
}
_refreshCountdown--;
if (_refreshCountdown < 0)
_refreshCountdown = _performanceCounterGroup.RefreshInstanceInterval - 1;
return _performanceCounterGroup.GetCounters().ToArray();
}
protected void RemoveObsoleteCounters(float?[] values, IPerformanceCounterInfo[] performanceCounterInfos)
{
if (!values.Any(x => !x.HasValue))
return;
for (var i = 0; i < values.Count(); i++)
{
_performanceCounterGroup.RemoveCounter(performanceCounterInfos[i]);
}
Trace.TraceInformation("Removed {0} counters.", values.Count());
}
protected void SetTimerInterval(double interval)
{
_timer.Interval = interval;
}
protected void OnCollectRegisterCounterValuesEvent(CollectRegisterCounterValuesEventArgs e)
{
var handler = CollectRegisterCounterValuesEvent;
if (handler != null)
{
handler(this, e);
}
}
protected static DateTime Floor(DateTime dateTime, TimeSpan interval)
{
return dateTime.AddTicks(-(dateTime.Ticks % interval.Ticks));
}
protected static float?[] ReadValues(IPerformanceCounterInfo[] performanceCounterInfos)
{
var values = new float?[performanceCounterInfos.Length];
for (var i = 0; i < values.Count(); i++)
{
try
{
var infos = performanceCounterInfos[i];
var value = infos.NextValue();
if (infos.Reverse.HasValue)
{
value = infos.Reverse.Value - value;
}
// if the counter value is greater than the max limit, then we use the max value
// see https://support.microsoft.com/en-us/kb/310067
if (infos.Max.HasValue)
{
value = Math.Min(infos.Max.Value, value);
}
if (infos.Min.HasValue)
{
value = Math.Max(infos.Min.Value, value);
}
values[i] = value;
}
catch (InvalidOperationException)
{
values[i] = null;
}
}
return values;
}
protected IEnumerable<Point> FormatResult(IPerformanceCounterInfo[] performanceCounterInfos, float?[] values, TimeUnit precision, DateTime timestamp)
{
if (performanceCounterInfos.Any(i => !string.IsNullOrEmpty(i.FieldName)))
{
// WIDE SCHEMA
// If at least one field name is specified, then we use the "wide" schema format, where all values are stored as different fields.
// We will try to generate as few points as possible (only one per instance)
return FormatResultWide(performanceCounterInfos, values, precision, timestamp);
}
else
{
// LONG SCHEMA
// If no field name is specified we use the default format which result in each counter being sent as one point.
// Each point as counter, category and instance specified as tags
return FormatResultLong(performanceCounterInfos, values, precision, timestamp);
}
}
private IEnumerable<Point> FormatResultWide(IPerformanceCounterInfo[] performanceCounterInfos, float?[] values, TimeUnit precision, DateTime timestamp)
{
var valuesByInstance = new Dictionary<string, Dictionary<string, object>>();
// first pass: we group all values by instance name
// if no field name is specified, we store the value in default "value" field
// if no instance name is specified, we use a default empty instance name
for (var i = 0; i < values.Length; i++)
{
var value = values[i];
if (value != null)
{
var performanceCounterInfo = performanceCounterInfos[i];
var fieldName = performanceCounterInfo.FieldName ?? "value";
var key = performanceCounterInfo.InstanceName;
Dictionary<string, object> fields;
if (!valuesByInstance.TryGetValue(key.Name ?? string.Empty, out fields))
{
fields = new Dictionary<string, object>();
valuesByInstance[key.Name ?? string.Empty] = fields;
}
fields[fieldName] = value;
}
}
// second pass: for each instance name, we create a point
if (valuesByInstance.Count != 0)
{
foreach (var instanceValues in valuesByInstance)
{
var point = new Point
{
Measurement = Name,
Tags = GetTags(Tags, null, null, null),
Fields = instanceValues.Value,
Precision = precision,
Timestamp = timestamp
};
var instance = instanceValues.Key;
if (!string.IsNullOrEmpty(instance))
{
point.Tags.Add("instance", instance);
}
yield return point;
}
}
}
private IEnumerable<Point> FormatResultLong(IPerformanceCounterInfo[] performanceCounterInfos, float?[] values, TimeUnit precision, DateTime timestamp)
{
for (var i = 0; i < values.Count(); i++)
{
var value = values[i];
if (value != null)
{
var performanceCounterInfo = performanceCounterInfos[i];
var categoryName = performanceCounterInfo.CategoryName;
var counterName = performanceCounterInfo.CounterName;
var key = performanceCounterInfo.InstanceName;
var instanceAlias = performanceCounterInfo.InstanceName.Alias;
var machineName = performanceCounterInfo.MachineName;
var tags = GetTags(Tags.Union(performanceCounterInfo.Tags), categoryName, counterName, machineName);
var fields = new Dictionary<string, object>
{
{ "value", value },
};
var point = new Point
{
Measurement = Name,
Tags = tags,
Fields = fields,
Precision = precision,
Timestamp = timestamp
};
if (!string.IsNullOrEmpty(key.Name))
{
point.Tags.Add("instance", key);
if (!string.IsNullOrEmpty(instanceAlias))
{
point.Tags.Add(instanceAlias, key);
}
}
yield return point;
}
}
}
private static Dictionary<string, object> GetTags(IEnumerable<ITag> globalTags, string categoryName, Naming counterName, string machineName)
{
var dictionary = new Dictionary<string, object>();
if (string.IsNullOrEmpty(machineName) || machineName == ".")
{
dictionary.Add("hostname", Environment.MachineName);
}
else
{
dictionary.Add("hostname", machineName);
}
if (categoryName != null)
{
dictionary.Add("category", categoryName);
}
if (counterName != null)
{
dictionary.Add("counter", string.IsNullOrEmpty(counterName.Alias) ? counterName.Name : counterName.Alias);
}
foreach (var tag in globalTags)
{
dictionary.Add(tag.Name, tag.Value);
}
return dictionary;
}
public void Dispose()
{
_timer.Stop();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl.Runtime;
using MS.Internal.Xml.XPath;
using System.Collections;
using System.Runtime.Versioning;
internal class NamespaceInfo
{
internal string prefix;
internal string nameSpace;
internal int stylesheetId;
internal NamespaceInfo(string prefix, string nameSpace, int stylesheetId)
{
this.prefix = prefix;
this.nameSpace = nameSpace;
this.stylesheetId = stylesheetId;
}
}
internal class ContainerAction : CompiledAction
{
internal ArrayList containedActions;
internal CopyCodeAction lastCopyCodeAction; // non null if last action is CopyCodeAction;
private int _maxid = 0;
// Local execution states
protected const int ProcessingChildren = 1;
internal override void Compile(Compiler compiler)
{
throw new NotImplementedException();
}
internal void CompileStylesheetAttributes(Compiler compiler)
{
NavigatorInput input = compiler.Input;
string element = input.LocalName;
string badAttribute = null;
string version = null;
if (input.MoveToFirstAttribute())
{
do
{
string nspace = input.NamespaceURI;
string name = input.LocalName;
if (nspace.Length != 0) continue;
if (Ref.Equal(name, input.Atoms.Version))
{
version = input.Value;
if (1 <= XmlConvert.ToXPathDouble(version))
{
compiler.ForwardCompatibility = (version != "1.0");
}
else
{
// XmlConvert.ToXPathDouble(version) an be NaN!
if (!compiler.ForwardCompatibility)
{
throw XsltException.Create(SR.Xslt_InvalidAttrValue, "version", version);
}
}
}
else if (Ref.Equal(name, input.Atoms.ExtensionElementPrefixes))
{
compiler.InsertExtensionNamespace(input.Value);
}
else if (Ref.Equal(name, input.Atoms.ExcludeResultPrefixes))
{
compiler.InsertExcludedNamespace(input.Value);
}
else if (Ref.Equal(name, input.Atoms.Id))
{
// Do nothing here.
}
else
{
// We can have version attribute later. For now remember this attribute and continue
badAttribute = name;
}
}
while (input.MoveToNextAttribute());
input.ToParent();
}
if (version == null)
{
throw XsltException.Create(SR.Xslt_MissingAttribute, "version");
}
if (badAttribute != null && !compiler.ForwardCompatibility)
{
throw XsltException.Create(SR.Xslt_InvalidAttribute, badAttribute, element);
}
}
internal void CompileSingleTemplate(Compiler compiler)
{
NavigatorInput input = compiler.Input;
//
// find mandatory version attribute and launch compilation of single template
//
string version = null;
if (input.MoveToFirstAttribute())
{
do
{
string nspace = input.NamespaceURI;
string name = input.LocalName;
if (Ref.Equal(nspace, input.Atoms.UriXsl) &&
Ref.Equal(name, input.Atoms.Version))
{
version = input.Value;
}
}
while (input.MoveToNextAttribute());
input.ToParent();
}
if (version == null)
{
if (Ref.Equal(input.LocalName, input.Atoms.Stylesheet) &&
input.NamespaceURI == XmlReservedNs.NsWdXsl)
{
throw XsltException.Create(SR.Xslt_WdXslNamespace);
}
throw XsltException.Create(SR.Xslt_WrongStylesheetElement);
}
compiler.AddTemplate(compiler.CreateSingleTemplateAction());
}
/*
* CompileTopLevelElements
*/
protected void CompileDocument(Compiler compiler, bool inInclude)
{
NavigatorInput input = compiler.Input;
// SkipToElement :
while (input.NodeType != XPathNodeType.Element)
{
if (!compiler.Advance())
{
throw XsltException.Create(SR.Xslt_WrongStylesheetElement);
}
}
Debug.Assert(compiler.Input.NodeType == XPathNodeType.Element);
if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl))
{
if (
!Ref.Equal(input.LocalName, input.Atoms.Stylesheet) &&
!Ref.Equal(input.LocalName, input.Atoms.Transform)
)
{
throw XsltException.Create(SR.Xslt_WrongStylesheetElement);
}
compiler.PushNamespaceScope();
CompileStylesheetAttributes(compiler);
CompileTopLevelElements(compiler);
if (!inInclude)
{
CompileImports(compiler);
}
}
else
{
// single template
compiler.PushLiteralScope();
CompileSingleTemplate(compiler);
}
compiler.PopScope();
}
internal Stylesheet CompileImport(Compiler compiler, Uri uri, int id)
{
NavigatorInput input = compiler.ResolveDocument(uri);
compiler.PushInputDocument(input);
try
{
compiler.PushStylesheet(new Stylesheet());
compiler.Stylesheetid = id;
CompileDocument(compiler, /*inInclude*/ false);
}
catch (XsltCompileException)
{
throw;
}
catch (Exception e)
{
throw new XsltCompileException(e, input.BaseURI, input.LineNumber, input.LinePosition);
}
finally
{
compiler.PopInputDocument();
}
return compiler.PopStylesheet();
}
private void CompileImports(Compiler compiler)
{
ArrayList imports = compiler.CompiledStylesheet.Imports;
// We can't reverce imports order. Template lookup relyes on it after compilation
int saveStylesheetId = compiler.Stylesheetid;
for (int i = imports.Count - 1; 0 <= i; i--)
{ // Imports should be compiled in reverse order
Uri uri = imports[i] as Uri;
Debug.Assert(uri != null);
imports[i] = CompileImport(compiler, uri, ++_maxid);
}
compiler.Stylesheetid = saveStylesheetId;
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
private void CompileInclude(Compiler compiler)
{
Uri uri = compiler.ResolveUri(compiler.GetSingleAttribute(compiler.Input.Atoms.Href));
string resolved = uri.ToString();
if (compiler.IsCircularReference(resolved))
{
throw XsltException.Create(SR.Xslt_CircularInclude, resolved);
}
NavigatorInput input = compiler.ResolveDocument(uri);
compiler.PushInputDocument(input);
try
{
CompileDocument(compiler, /*inInclude*/ true);
}
catch (XsltCompileException)
{
throw;
}
catch (Exception e)
{
throw new XsltCompileException(e, input.BaseURI, input.LineNumber, input.LinePosition);
}
finally
{
compiler.PopInputDocument();
}
CheckEmpty(compiler);
}
internal void CompileNamespaceAlias(Compiler compiler)
{
NavigatorInput input = compiler.Input;
string element = input.LocalName;
string namespace1 = null, namespace2 = null;
string prefix1 = null, prefix2 = null;
if (input.MoveToFirstAttribute())
{
do
{
string nspace = input.NamespaceURI;
string name = input.LocalName;
if (nspace.Length != 0) continue;
if (Ref.Equal(name, input.Atoms.StylesheetPrefix))
{
prefix1 = input.Value;
namespace1 = compiler.GetNsAlias(ref prefix1);
}
else if (Ref.Equal(name, input.Atoms.ResultPrefix))
{
prefix2 = input.Value;
namespace2 = compiler.GetNsAlias(ref prefix2);
}
else
{
if (!compiler.ForwardCompatibility)
{
throw XsltException.Create(SR.Xslt_InvalidAttribute, name, element);
}
}
}
while (input.MoveToNextAttribute());
input.ToParent();
}
CheckRequiredAttribute(compiler, namespace1, "stylesheet-prefix");
CheckRequiredAttribute(compiler, namespace2, "result-prefix");
CheckEmpty(compiler);
//String[] resultarray = { prefix2, namespace2 };
compiler.AddNamespaceAlias(namespace1, new NamespaceInfo(prefix2, namespace2, compiler.Stylesheetid));
}
internal void CompileKey(Compiler compiler)
{
NavigatorInput input = compiler.Input;
string element = input.LocalName;
int MatchKey = Compiler.InvalidQueryKey;
int UseKey = Compiler.InvalidQueryKey;
XmlQualifiedName Name = null;
if (input.MoveToFirstAttribute())
{
do
{
string nspace = input.NamespaceURI;
string name = input.LocalName;
string value = input.Value;
if (nspace.Length != 0) continue;
if (Ref.Equal(name, input.Atoms.Name))
{
Name = compiler.CreateXPathQName(value);
}
else if (Ref.Equal(name, input.Atoms.Match))
{
MatchKey = compiler.AddQuery(value, /*allowVars:*/false, /*allowKey*/false, /*pattern*/true);
}
else if (Ref.Equal(name, input.Atoms.Use))
{
UseKey = compiler.AddQuery(value, /*allowVars:*/false, /*allowKey*/false, /*pattern*/false);
}
else
{
if (!compiler.ForwardCompatibility)
{
throw XsltException.Create(SR.Xslt_InvalidAttribute, name, element);
}
}
}
while (input.MoveToNextAttribute());
input.ToParent();
}
CheckRequiredAttribute(compiler, MatchKey != Compiler.InvalidQueryKey, "match");
CheckRequiredAttribute(compiler, UseKey != Compiler.InvalidQueryKey, "use");
CheckRequiredAttribute(compiler, Name != null, "name");
// It is a breaking change to check for emptiness, SQLBUDT 324364
//CheckEmpty(compiler);
compiler.InsertKey(Name, MatchKey, UseKey);
}
protected void CompileDecimalFormat(Compiler compiler)
{
NumberFormatInfo info = new NumberFormatInfo();
DecimalFormat format = new DecimalFormat(info, '#', '0', ';');
XmlQualifiedName Name = null;
NavigatorInput input = compiler.Input;
if (input.MoveToFirstAttribute())
{
do
{
if (input.Prefix.Length != 0) continue;
string name = input.LocalName;
string value = input.Value;
if (Ref.Equal(name, input.Atoms.Name))
{
Name = compiler.CreateXPathQName(value);
}
else if (Ref.Equal(name, input.Atoms.DecimalSeparator))
{
info.NumberDecimalSeparator = value;
}
else if (Ref.Equal(name, input.Atoms.GroupingSeparator))
{
info.NumberGroupSeparator = value;
}
else if (Ref.Equal(name, input.Atoms.Infinity))
{
info.PositiveInfinitySymbol = value;
}
else if (Ref.Equal(name, input.Atoms.MinusSign))
{
info.NegativeSign = value;
}
else if (Ref.Equal(name, input.Atoms.NaN))
{
info.NaNSymbol = value;
}
else if (Ref.Equal(name, input.Atoms.Percent))
{
info.PercentSymbol = value;
}
else if (Ref.Equal(name, input.Atoms.PerMille))
{
info.PerMilleSymbol = value;
}
else if (Ref.Equal(name, input.Atoms.Digit))
{
if (CheckAttribute(value.Length == 1, compiler))
{
format.digit = value[0];
}
}
else if (Ref.Equal(name, input.Atoms.ZeroDigit))
{
if (CheckAttribute(value.Length == 1, compiler))
{
format.zeroDigit = value[0];
}
}
else if (Ref.Equal(name, input.Atoms.PatternSeparator))
{
if (CheckAttribute(value.Length == 1, compiler))
{
format.patternSeparator = value[0];
}
}
}
while (input.MoveToNextAttribute());
input.ToParent();
}
info.NegativeInfinitySymbol = string.Concat(info.NegativeSign, info.PositiveInfinitySymbol);
if (Name == null)
{
Name = new XmlQualifiedName();
}
compiler.AddDecimalFormat(Name, format);
CheckEmpty(compiler);
}
internal bool CheckAttribute(bool valid, Compiler compiler)
{
if (!valid)
{
if (!compiler.ForwardCompatibility)
{
throw XsltException.Create(SR.Xslt_InvalidAttrValue, compiler.Input.LocalName, compiler.Input.Value);
}
return false;
}
return true;
}
protected void CompileSpace(Compiler compiler, bool preserve)
{
string value = compiler.GetSingleAttribute(compiler.Input.Atoms.Elements);
string[] elements = XmlConvert.SplitString(value);
for (int i = 0; i < elements.Length; i++)
{
double defaultPriority = NameTest(elements[i]);
compiler.CompiledStylesheet.AddSpace(compiler, elements[i], defaultPriority, preserve);
}
CheckEmpty(compiler);
}
private double NameTest(string name)
{
if (name == "*")
{
return -0.5;
}
int idx = name.Length - 2;
if (0 <= idx && name[idx] == ':' && name[idx + 1] == '*')
{
if (!PrefixQName.ValidatePrefix(name.Substring(0, idx)))
{
throw XsltException.Create(SR.Xslt_InvalidAttrValue, "elements", name);
}
return -0.25;
}
else
{
string prefix, localname;
PrefixQName.ParseQualifiedName(name, out prefix, out localname);
return 0;
}
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
protected void CompileTopLevelElements(Compiler compiler)
{
// Navigator positioned at parent root, need to move to child and then back
if (compiler.Recurse() == false)
{
return;
}
NavigatorInput input = compiler.Input;
bool notFirstElement = false;
do
{
switch (input.NodeType)
{
case XPathNodeType.Element:
string name = input.LocalName;
string nspace = input.NamespaceURI;
if (Ref.Equal(nspace, input.Atoms.UriXsl))
{
if (Ref.Equal(name, input.Atoms.Import))
{
if (notFirstElement)
{
throw XsltException.Create(SR.Xslt_NotFirstImport);
}
// We should compile imports in reverse order after all toplevel elements.
// remember it now and return to it in CompileImpoorts();
Uri uri = compiler.ResolveUri(compiler.GetSingleAttribute(compiler.Input.Atoms.Href));
string resolved = uri.ToString();
if (compiler.IsCircularReference(resolved))
{
throw XsltException.Create(SR.Xslt_CircularInclude, resolved);
}
compiler.CompiledStylesheet.Imports.Add(uri);
CheckEmpty(compiler);
}
else if (Ref.Equal(name, input.Atoms.Include))
{
notFirstElement = true;
CompileInclude(compiler);
}
else
{
notFirstElement = true;
compiler.PushNamespaceScope();
if (Ref.Equal(name, input.Atoms.StripSpace))
{
CompileSpace(compiler, false);
}
else if (Ref.Equal(name, input.Atoms.PreserveSpace))
{
CompileSpace(compiler, true);
}
else if (Ref.Equal(name, input.Atoms.Output))
{
CompileOutput(compiler);
}
else if (Ref.Equal(name, input.Atoms.Key))
{
CompileKey(compiler);
}
else if (Ref.Equal(name, input.Atoms.DecimalFormat))
{
CompileDecimalFormat(compiler);
}
else if (Ref.Equal(name, input.Atoms.NamespaceAlias))
{
CompileNamespaceAlias(compiler);
}
else if (Ref.Equal(name, input.Atoms.AttributeSet))
{
compiler.AddAttributeSet(compiler.CreateAttributeSetAction());
}
else if (Ref.Equal(name, input.Atoms.Variable))
{
VariableAction action = compiler.CreateVariableAction(VariableType.GlobalVariable);
if (action != null)
{
AddAction(action);
}
}
else if (Ref.Equal(name, input.Atoms.Param))
{
VariableAction action = compiler.CreateVariableAction(VariableType.GlobalParameter);
if (action != null)
{
AddAction(action);
}
}
else if (Ref.Equal(name, input.Atoms.Template))
{
compiler.AddTemplate(compiler.CreateTemplateAction());
}
else
{
if (!compiler.ForwardCompatibility)
{
throw compiler.UnexpectedKeyword();
}
}
compiler.PopScope();
}
}
else if (nspace == input.Atoms.UrnMsxsl && name == input.Atoms.Script)
{
AddScript(compiler);
}
else
{
if (nspace.Length == 0)
{
throw XsltException.Create(SR.Xslt_NullNsAtTopLevel, input.Name);
}
// Ignoring non-recognized namespace per XSLT spec 2.2
}
break;
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
case XPathNodeType.Whitespace:
case XPathNodeType.SignificantWhitespace:
break;
default:
throw XsltException.Create(SR.Xslt_InvalidContents, "stylesheet");
}
}
while (compiler.Advance());
compiler.ToParent();
}
protected void CompileTemplate(Compiler compiler)
{
do
{
CompileOnceTemplate(compiler);
}
while (compiler.Advance());
}
protected void CompileOnceTemplate(Compiler compiler)
{
NavigatorInput input = compiler.Input;
if (input.NodeType == XPathNodeType.Element)
{
string nspace = input.NamespaceURI;
if (Ref.Equal(nspace, input.Atoms.UriXsl))
{
compiler.PushNamespaceScope();
CompileInstruction(compiler);
compiler.PopScope();
}
else
{
compiler.PushLiteralScope();
compiler.InsertExtensionNamespace();
if (compiler.IsExtensionNamespace(nspace))
{
AddAction(compiler.CreateNewInstructionAction());
}
else
{
CompileLiteral(compiler);
}
compiler.PopScope();
}
}
else
{
CompileLiteral(compiler);
}
}
private void CompileInstruction(Compiler compiler)
{
NavigatorInput input = compiler.Input;
CompiledAction action = null;
Debug.Assert(Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl));
string name = input.LocalName;
if (Ref.Equal(name, input.Atoms.ApplyImports))
{
action = compiler.CreateApplyImportsAction();
}
else if (Ref.Equal(name, input.Atoms.ApplyTemplates))
{
action = compiler.CreateApplyTemplatesAction();
}
else if (Ref.Equal(name, input.Atoms.Attribute))
{
action = compiler.CreateAttributeAction();
}
else if (Ref.Equal(name, input.Atoms.CallTemplate))
{
action = compiler.CreateCallTemplateAction();
}
else if (Ref.Equal(name, input.Atoms.Choose))
{
action = compiler.CreateChooseAction();
}
else if (Ref.Equal(name, input.Atoms.Comment))
{
action = compiler.CreateCommentAction();
}
else if (Ref.Equal(name, input.Atoms.Copy))
{
action = compiler.CreateCopyAction();
}
else if (Ref.Equal(name, input.Atoms.CopyOf))
{
action = compiler.CreateCopyOfAction();
}
else if (Ref.Equal(name, input.Atoms.Element))
{
action = compiler.CreateElementAction();
}
else if (Ref.Equal(name, input.Atoms.Fallback))
{
return;
}
else if (Ref.Equal(name, input.Atoms.ForEach))
{
action = compiler.CreateForEachAction();
}
else if (Ref.Equal(name, input.Atoms.If))
{
action = compiler.CreateIfAction(IfAction.ConditionType.ConditionIf);
}
else if (Ref.Equal(name, input.Atoms.Message))
{
action = compiler.CreateMessageAction();
}
else if (Ref.Equal(name, input.Atoms.Number))
{
action = compiler.CreateNumberAction();
}
else if (Ref.Equal(name, input.Atoms.ProcessingInstruction))
{
action = compiler.CreateProcessingInstructionAction();
}
else if (Ref.Equal(name, input.Atoms.Text))
{
action = compiler.CreateTextAction();
}
else if (Ref.Equal(name, input.Atoms.ValueOf))
{
action = compiler.CreateValueOfAction();
}
else if (Ref.Equal(name, input.Atoms.Variable))
{
action = compiler.CreateVariableAction(VariableType.LocalVariable);
}
else
{
if (compiler.ForwardCompatibility)
action = compiler.CreateNewInstructionAction();
else
throw compiler.UnexpectedKeyword();
}
Debug.Assert(action != null);
AddAction(action);
}
private void CompileLiteral(Compiler compiler)
{
NavigatorInput input = compiler.Input;
switch (input.NodeType)
{
case XPathNodeType.Element:
this.AddEvent(compiler.CreateBeginEvent());
CompileLiteralAttributesAndNamespaces(compiler);
if (compiler.Recurse())
{
CompileTemplate(compiler);
compiler.ToParent();
}
this.AddEvent(new EndEvent(XPathNodeType.Element));
break;
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
this.AddEvent(compiler.CreateTextEvent());
break;
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
break;
default:
Debug.Fail("Unexpected node type.");
break;
}
}
private void CompileLiteralAttributesAndNamespaces(Compiler compiler)
{
NavigatorInput input = compiler.Input;
if (input.Navigator.MoveToAttribute("use-attribute-sets", input.Atoms.UriXsl))
{
AddAction(compiler.CreateUseAttributeSetsAction());
input.Navigator.MoveToParent();
}
compiler.InsertExcludedNamespace();
if (input.MoveToFirstNamespace())
{
do
{
string uri = input.Value;
if (uri == XmlReservedNs.NsXslt)
{
continue;
}
if (
compiler.IsExcludedNamespace(uri) ||
compiler.IsExtensionNamespace(uri) ||
compiler.IsNamespaceAlias(uri)
)
{
continue;
}
this.AddEvent(new NamespaceEvent(input));
}
while (input.MoveToNextNamespace());
input.ToParent();
}
if (input.MoveToFirstAttribute())
{
do
{
// Skip everything from Xslt namespace
if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl))
{
continue;
}
// Add attribute events
this.AddEvent(compiler.CreateBeginEvent());
this.AddEvents(compiler.CompileAvt(input.Value));
this.AddEvent(new EndEvent(XPathNodeType.Attribute));
}
while (input.MoveToNextAttribute());
input.ToParent();
}
}
private void CompileOutput(Compiler compiler)
{
Debug.Assert((object)this == (object)compiler.RootAction);
compiler.RootAction.Output.Compile(compiler);
}
internal void AddAction(Action action)
{
if (this.containedActions == null)
{
this.containedActions = new ArrayList();
}
this.containedActions.Add(action);
lastCopyCodeAction = null;
}
private void EnsureCopyCodeAction()
{
if (lastCopyCodeAction == null)
{
CopyCodeAction copyCode = new CopyCodeAction();
AddAction(copyCode);
lastCopyCodeAction = copyCode;
}
}
protected void AddEvent(Event copyEvent)
{
EnsureCopyCodeAction();
lastCopyCodeAction.AddEvent(copyEvent);
}
protected void AddEvents(ArrayList copyEvents)
{
EnsureCopyCodeAction();
lastCopyCodeAction.AddEvents(copyEvents);
}
private void AddScript(Compiler compiler)
{
NavigatorInput input = compiler.Input;
ScriptingLanguage lang = ScriptingLanguage.JScript;
string implementsNamespace = null;
if (input.MoveToFirstAttribute())
{
do
{
if (input.LocalName == input.Atoms.Language)
{
string langName = input.Value;
if (
string.Equals(langName, "jscript", StringComparison.OrdinalIgnoreCase) ||
string.Equals(langName, "javascript", StringComparison.OrdinalIgnoreCase)
)
{
lang = ScriptingLanguage.JScript;
}
else if (
string.Equals(langName, "c#", StringComparison.OrdinalIgnoreCase) ||
string.Equals(langName, "csharp", StringComparison.OrdinalIgnoreCase)
)
{
lang = ScriptingLanguage.CSharp;
}
#if !FEATURE_PAL // visualbasic
else if (
string.Equals(langName, "vb", StringComparison.OrdinalIgnoreCase) ||
string.Equals(langName, "visualbasic", StringComparison.OrdinalIgnoreCase)
)
{
lang = ScriptingLanguage.VisualBasic;
}
#endif // !FEATURE_PAL
else
{
throw XsltException.Create(SR.Xslt_ScriptInvalidLanguage, langName);
}
}
else if (input.LocalName == input.Atoms.ImplementsPrefix)
{
if (!PrefixQName.ValidatePrefix(input.Value))
{
throw XsltException.Create(SR.Xslt_InvalidAttrValue, input.LocalName, input.Value);
}
implementsNamespace = compiler.ResolveXmlNamespace(input.Value);
}
}
while (input.MoveToNextAttribute());
input.ToParent();
}
if (implementsNamespace == null)
{
throw XsltException.Create(SR.Xslt_MissingAttribute, input.Atoms.ImplementsPrefix);
}
if (!input.Recurse() || input.NodeType != XPathNodeType.Text)
{
throw XsltException.Create(SR.Xslt_ScriptEmpty);
}
compiler.AddScript(input.Value, lang, implementsNamespace, input.BaseURI, input.LineNumber);
input.ToParent();
}
internal override void Execute(Processor processor, ActionFrame frame)
{
Debug.Assert(processor != null && frame != null);
switch (frame.State)
{
case Initialized:
if (this.containedActions != null && this.containedActions.Count > 0)
{
processor.PushActionFrame(frame);
frame.State = ProcessingChildren;
}
else
{
frame.Finished();
}
break; // Allow children to run
case ProcessingChildren:
frame.Finished();
break;
default:
Debug.Fail("Invalid Container action execution state");
break;
}
}
internal Action GetAction(int actionIndex)
{
Debug.Assert(actionIndex == 0 || this.containedActions != null);
if (this.containedActions != null && actionIndex < this.containedActions.Count)
{
return (Action)this.containedActions[actionIndex];
}
else
{
return null;
}
}
internal void CheckDuplicateParams(XmlQualifiedName name)
{
if (this.containedActions != null)
{
foreach (CompiledAction action in this.containedActions)
{
WithParamAction param = action as WithParamAction;
if (param != null && param.Name == name)
{
throw XsltException.Create(SR.Xslt_DuplicateWithParam, name.ToString());
}
}
}
}
internal override void ReplaceNamespaceAlias(Compiler compiler)
{
if (this.containedActions == null)
{
return;
}
int count = this.containedActions.Count;
for (int i = 0; i < this.containedActions.Count; i++)
{
((Action)this.containedActions[i]).ReplaceNamespaceAlias(compiler);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.NetCore.Analyzers.InteropServices
{
using static MicrosoftNetCoreAnalyzersResources;
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class PInvokeDiagnosticAnalyzer : DiagnosticAnalyzer
{
public const string RuleCA1401Id = "CA1401";
public const string RuleCA2101Id = "CA2101";
internal static readonly DiagnosticDescriptor RuleCA1401 = DiagnosticDescriptorHelper.Create(
RuleCA1401Id,
CreateLocalizableResourceString(nameof(PInvokesShouldNotBeVisibleTitle)),
CreateLocalizableResourceString(nameof(PInvokesShouldNotBeVisibleMessage)),
DiagnosticCategory.Interoperability,
RuleLevel.IdeSuggestion,
description: CreateLocalizableResourceString(nameof(PInvokesShouldNotBeVisibleDescription)),
isPortedFxCopRule: true,
isDataflowRule: false);
private static readonly LocalizableString s_localizableMessageAndTitleCA2101 = CreateLocalizableResourceString(nameof(SpecifyMarshalingForPInvokeStringArgumentsTitle));
internal static readonly DiagnosticDescriptor RuleCA2101 = DiagnosticDescriptorHelper.Create(
RuleCA2101Id,
s_localizableMessageAndTitleCA2101,
s_localizableMessageAndTitleCA2101,
DiagnosticCategory.Globalization,
RuleLevel.BuildWarningCandidate,
description: CreateLocalizableResourceString(nameof(SpecifyMarshalingForPInvokeStringArgumentsDescription)),
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(RuleCA1401, RuleCA2101);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(
(context) =>
{
INamedTypeSymbol? dllImportType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute);
if (dllImportType == null)
{
return;
}
INamedTypeSymbol? marshalAsType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute);
if (marshalAsType == null)
{
return;
}
INamedTypeSymbol? stringBuilderType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextStringBuilder);
if (stringBuilderType == null)
{
return;
}
INamedTypeSymbol? unmanagedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesUnmanagedType);
if (unmanagedType == null)
{
return;
}
context.RegisterSymbolAction(new SymbolAnalyzer(dllImportType, marshalAsType, stringBuilderType, unmanagedType).AnalyzeSymbol, SymbolKind.Method);
});
}
private sealed class SymbolAnalyzer
{
private readonly INamedTypeSymbol _dllImportType;
private readonly INamedTypeSymbol _marshalAsType;
private readonly INamedTypeSymbol _stringBuilderType;
private readonly INamedTypeSymbol _unmanagedType;
public SymbolAnalyzer(
INamedTypeSymbol dllImportType,
INamedTypeSymbol marshalAsType,
INamedTypeSymbol stringBuilderType,
INamedTypeSymbol unmanagedType)
{
_dllImportType = dllImportType;
_marshalAsType = marshalAsType;
_stringBuilderType = stringBuilderType;
_unmanagedType = unmanagedType;
}
public void AnalyzeSymbol(SymbolAnalysisContext context)
{
var methodSymbol = (IMethodSymbol)context.Symbol;
if (methodSymbol == null)
{
return;
}
DllImportData dllImportData = methodSymbol.GetDllImportData();
if (dllImportData == null)
{
return;
}
AttributeData dllAttribute = methodSymbol.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Equals(_dllImportType));
Location defaultLocation = dllAttribute == null ? methodSymbol.Locations.FirstOrDefault() : GetAttributeLocation(dllAttribute);
// CA1401 - PInvoke methods should not be visible
if (methodSymbol.IsExternallyVisible())
{
context.ReportDiagnostic(context.Symbol.CreateDiagnostic(RuleCA1401, methodSymbol.Name));
}
// CA2101 - Specify marshalling for PInvoke string arguments
if (dllImportData.BestFitMapping != false ||
context.Options.GetMSBuildPropertyValue(MSBuildPropertyOptionNames.InvariantGlobalization, context.Compilation) is not "true")
{
bool appliedCA2101ToMethod = false;
foreach (IParameterSymbol parameter in methodSymbol.Parameters)
{
if (parameter.Type.SpecialType == SpecialType.System_String || parameter.Type.Equals(_stringBuilderType))
{
AttributeData marshalAsAttribute = parameter.GetAttributes().FirstOrDefault(attr => attr.AttributeClass.Equals(_marshalAsType));
CharSet? charSet = marshalAsAttribute == null
? dllImportData.CharacterSet
: MarshalingToCharSet(GetParameterMarshaling(marshalAsAttribute));
// only unicode marshaling is considered safe
if (charSet != CharSet.Unicode)
{
if (marshalAsAttribute != null)
{
// track the diagnostic on the [MarshalAs] attribute
Location marshalAsLocation = GetAttributeLocation(marshalAsAttribute);
context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, marshalAsLocation));
}
else if (!appliedCA2101ToMethod)
{
// track the diagnostic on the [DllImport] attribute
appliedCA2101ToMethod = true;
context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, defaultLocation));
}
}
}
}
// only unicode marshaling is considered safe, but only check this if we haven't already flagged the attribute
if (!appliedCA2101ToMethod && dllImportData.CharacterSet != CharSet.Unicode &&
(methodSymbol.ReturnType.SpecialType == SpecialType.System_String || methodSymbol.ReturnType.Equals(_stringBuilderType)))
{
context.ReportDiagnostic(Diagnostic.Create(RuleCA2101, defaultLocation));
}
}
}
private UnmanagedType? GetParameterMarshaling(AttributeData attributeData)
{
if (!attributeData.ConstructorArguments.IsEmpty)
{
TypedConstant argument = attributeData.ConstructorArguments.First();
if (argument.Type.Equals(_unmanagedType))
{
return (UnmanagedType)argument.Value;
}
else if (argument.Type.SpecialType == SpecialType.System_Int16)
{
return (UnmanagedType)(short)argument.Value;
}
}
return null;
}
private static CharSet? MarshalingToCharSet(UnmanagedType? type)
{
if (type == null)
{
return null;
}
#pragma warning disable CS0618 // Type or member is obsolete
switch (type)
{
case UnmanagedType.AnsiBStr:
case UnmanagedType.LPStr:
case UnmanagedType.VBByRefStr:
return CharSet.Ansi;
case UnmanagedType.BStr:
case UnmanagedType.LPWStr:
return CharSet.Unicode;
case UnmanagedType.ByValTStr:
case UnmanagedType.LPTStr:
case UnmanagedType.TBStr:
default:
// CharSet.Auto and CharSet.None are not available in the portable
// profiles. We are not interested in those values for our analysis and so simply
// return null
return null;
}
#pragma warning restore CS0618 // Type or member is obsolete
}
private static Location GetAttributeLocation(AttributeData attributeData)
{
return attributeData.ApplicationSyntaxReference.SyntaxTree.GetLocation(attributeData.ApplicationSyntaxReference.Span);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using Banshee.Base;
using Banshee.MediaEngine;
using Microsoft.Win32;
public static class PluginModuleEntry
{
public static Type[] GetTypes()
{
return new Type[] {
typeof(Banshee.MediaEngine.WMP10.WMP10PlayerEngine)
};
}
}
namespace Banshee.MediaEngine.WMP10
{
/// <summary>
/// Windows Media Player Based engine
/// </summary>
public class WMP10PlayerEngine:PlayerEngine
{
WMPLib.WindowsMediaPlayer Player;
public WMP10PlayerEngine()
{
Player = new WMPLib.WindowsMediaPlayer();
try
{
UInt32 dwValue = (UInt32)1;
RegistryKey hkcu = Registry.CurrentUser;
RegistryKey subkey = hkcu.OpenSubKey(@"Software\Microsoft\MediaPlayer\Preferences", true);
subkey.SetValue("CDAutoPlay", (Int32)dwValue);
// disable metadata lookup for CD's since we use MusicBrainz
dwValue = (UInt32)Convert.ToInt32(subkey.GetValue("MetadataRetrieval"));
dwValue |= 0;
subkey.SetValue("MetadataRetrieval", (Int32)dwValue);
}
catch (Exception) { }
Player.ModeChange += new WMPLib._WMPOCXEvents_ModeChangeEventHandler(Player_ModeChange);
Player.Warning += new WMPLib._WMPOCXEvents_WarningEventHandler(Player_Warning);
Player.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
Player.MediaError +=new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
Player.PositionChange += new WMPLib._WMPOCXEvents_PositionChangeEventHandler(Player_PositionChange);
Player.StatusChange += new WMPLib._WMPOCXEvents_StatusChangeEventHandler(Player_StatusChange);
Player.DeviceConnect += new WMPLib._WMPOCXEvents_DeviceConnectEventHandler(Player_DeviceConnect);
Player.CdromMediaChange += new WMPLib._WMPOCXEvents_CdromMediaChangeEventHandler(Player_CdromMediaChange);
Player.MediaChange += new WMPLib._WMPOCXEvents_MediaChangeEventHandler(Player_MediaChange);
Player.DurationUnitChange += new WMPLib._WMPOCXEvents_DurationUnitChangeEventHandler(Player_DurationUnitChange);
Player.EndOfStream += new WMPLib._WMPOCXEvents_EndOfStreamEventHandler(Player_EndOfStream);
}
void Player_EndOfStream(int Result)
{
OnEventChanged(PlayerEngineEvent.EndOfStream);
Player.controls.stop();
Console.WriteLine("Stream Ended");
}
void Player_DurationUnitChange(int NewDurationUnit)
{
Console.WriteLine("Duration {0}", NewDurationUnit);
}
void Player_MediaChange(object Item)
{
LogCore.Instance.PushInformation("Player Engine", string.Format(" Media changed to {0}", Position));
OnEventChanged(PlayerEngineEvent.Iterate);
}
void LoadCdromDevices()
{
for (int i = 0; i < Player.cdromCollection.count; i++)
{
string root = Player.cdromCollection.Item(i).driveSpecifier;
Console.WriteLine("Cdrom {0} detected", root);
}
}
void Player_CdromMediaChange(int CdromNum)
{
/* if (manager != null)
{
SetManager();
}
string devicename = Player.cdromCollection.Item(CdromNum).driveSpecifier;
manager.OnMediaChanged(devicename);
Console.WriteLine("Media Changed:{0}", devicename);*/
}
void Player_DeviceConnect(WMPLib.IWMPSyncDevice pDevice)
{
Console.WriteLine("Device connect:{0}", pDevice.friendlyName);
}
void Player_Warning(int WarningType, int Param, string Description)
{
Console.WriteLine("Player warning:{0}",Description);
}
void Player_ModeChange(string ModeName, bool NewValue)
{
Console.WriteLine("Mode {0}:{1}", ModeName, NewValue);
}
void Player_StatusChange()
{
Console.WriteLine("Player Status:{0}", Player.status);
}
void Player_PositionChange(double oldPosition, double newPosition)
{
OnEventChanged(PlayerEngineEvent.Iterate);
}
void Player_MediaError(object pMediaObject)
{
Console.WriteLine("Player Media Error:{0}", pMediaObject.ToString());
}
void Player_PlayStateChange(int NewState)
{
if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsPlaying)
{
OnStateChanged(PlayerEngineState.Playing);
}
else if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsWaiting)
{
OnStateChanged(PlayerEngineState.Idle);
}
else if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsPaused)
{
OnStateChanged(PlayerEngineState.Paused);
}
else if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsBuffering)
{
OnStateChanged(PlayerEngineState.Contacting);
}
else if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsReady)
{
OnStateChanged(PlayerEngineState.Loaded);
}
else if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
OnEventChanged(PlayerEngineEvent.EndOfStream);
}
else
{
Console.WriteLine("State {0}", (WMPLib.WMPPlayState)NewState);
}
}
protected override void OpenUri(SafeUri uri)
{
string url = uri.ToString();
// Cornel - I use this little hack so that i dont break the Banshee base code cdda://8#G:\
if (url.StartsWith("cdda"))
{
string[] res1 = url.Split(new string[] {"//"}, StringSplitOptions.None);
string[] res2 = res1[1].Split('#');
string tracknumber = res2[0];
Player.currentPlaylist = Player.cdromCollection.Item(0).Playlist;
object media = Player.currentPlaylist.get_Item(System.Convert.ToInt32(tracknumber));
Player.controls.playItem((WMPLib.IWMPMedia)media);
}
else
{
Player.controls.stop();
Player.URL = url;
Player.controls.play();
}
}
int vol;
public override ushort Volume
{
get
{
return (ushort)Player.settings.volume;
}
set
{
Player.settings.volume = (int)value;
}
}
public override uint Position
{
get
{
return System.Convert.ToUInt32(Player.controls.currentPosition);
}
set
{
Player.controls.currentPosition = System.Convert.ToDouble(value);
}
}
public override uint Length
{
get { return System.Convert.ToUInt32(Player.controls.currentItem.duration); }
}
private static string [] source_capabilities = { "file", "http", "cdda" };
public override IEnumerable SourceCapabilities
{
get { return source_capabilities; }
}
private static string [] decoder_capabilities = { "ogg", "wma", "asf", "flac" };
public override IEnumerable ExplicitDecoderCapabilities
{
get { return decoder_capabilities;}
}
public override string Id
{
get { return "wmp10"; }
}
public override string Name
{
get { return "Windows Media Player 11"; }
}
}
}
| |
#region Using directives
using SimpleFramework.Xml.Core;
using SimpleFramework.Xml;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
public class MapTest : ValidationTestCase {
private const String ENTRY_MAP =
"<entryMap>\n"+
" <map>\n"+
" <entry key='a'>" +
" <mapEntry>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='b'>" +
" <mapEntry>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='c'>" +
" <mapEntry>\n" +
" <name>c</name>\n"+
" <value>example 3</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry key='d'>" +
" <mapEntry>\n" +
" <name>d</name>\n"+
" <value>example 4</value>\n"+
" </mapEntry>" +
" </entry>" +
" </map>\n"+
"</entryMap>";
private const String STRING_MAP =
"<stringMap>\n"+
" <map>\n"+
" <entry letter='a'>example 1</entry>\n" +
" <entry letter='b'>example 2</entry>\n" +
" <entry letter='c'>example 3</entry>\n" +
" <entry letter='d'>example 4</entry>\n" +
" </map>\n"+
"</stringMap>";
private const String COMPLEX_VALUE_KEY_OVERRIDE_MAP =
"<complexMap>\n"+
" <map>\n"+
" <item>" +
" <key>\n" +
" <name>name 1</name>\n" +
" <address>address 1</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </value>" +
" </item>" +
" <item>" +
" <key>\n" +
" <name>name 2</name>\n" +
" <address>address 2</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </value>" +
" </item>" +
" <item>" +
" <key>\n" +
" <name>name 3</name>\n" +
" <address>address 3</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>c</name>\n"+
" <value>example 3</value>\n"+
" </value>" +
" </item>" +
" <item>" +
" <key>\n" +
" <name>name 4</name>\n" +
" <address>address 4</address>\n" +
" </key>\n" +
" <value>\n" +
" <name>d</name>\n"+
" <value>example 4</value>\n"+
" </value>" +
" </item>" +
" </map>\n"+
"</complexMap>";
private const String COMPLEX_MAP =
"<complexMap>\n"+
" <map>\n"+
" <entry>" +
" <compositeKey>\n" +
" <name>name 1</name>\n" +
" <address>address 1</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>a</name>\n"+
" <value>example 1</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 2</name>\n" +
" <address>address 2</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>b</name>\n"+
" <value>example 2</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 3</name>\n" +
" <address>address 3</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>c</name>\n"+
" <value>example 3</value>\n"+
" </mapEntry>" +
" </entry>" +
" <entry>" +
" <compositeKey>\n" +
" <name>name 4</name>\n" +
" <address>address 4</address>\n" +
" </compositeKey>\n" +
" <mapEntry>\n" +
" <name>d</name>\n"+
" <value>example 4</value>\n"+
" </mapEntry>" +
" </entry>" +
" </map>\n"+
"</complexMap>";
private const String PRIMITIVE_MAP =
"<primitiveMap>\n"+
" <table>\n"+
" <entry>\n" +
" <string>one</string>\n" +
" <bigDecimal>1.0</bigDecimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>two</string>\n" +
" <bigDecimal>2.0</bigDecimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>three</string>\n" +
" <bigDecimal>3.0</bigDecimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>four</string>\n" +
" <bigDecimal>4.0</bigDecimal>\n" +
" </entry>\n"+
" </table>\n"+
"</primitiveMap>";
private const String PRIMITIVE_VALUE_OVERRIDE_MAP =
"<primitiveValueOverrideMap>\n"+
" <map>\n"+
" <entry>\n" +
" <string>one</string>\n" +
" <decimal>1.0</decimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>two</string>\n" +
" <decimal>2.0</decimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>three</string>\n" +
" <decimal>3.0</decimal>\n" +
" </entry>\n"+
" <entry>" +
" <string>four</string>\n" +
" <decimal>4.0</decimal>\n" +
" </entry>\n"+
" </map>\n"+
"</primitiveValueOverrideMap>";
private const String PRIMITIVE_VALUE_KEY_OVERRIDE_MAP =
"<primitiveValueKeyOverrideMap>\n"+
" <map>\n"+
" <item>\n" +
" <text>one</text>\n" +
" <decimal>1.0</decimal>\n" +
" </item>\n"+
" <item>" +
" <text>two</text>\n" +
" <decimal>2.0</decimal>\n" +
" </item>\n"+
" <item>" +
" <text>three</text>\n" +
" <decimal>3.0</decimal>\n" +
" </item>\n"+
" <item>" +
" <text>four</text>\n" +
" <decimal>4.0</decimal>\n" +
" </item>\n"+
" </map>\n"+
"</primitiveValueKeyOverrideMap>";
private const String PRIMITIVE_INLINE_MAP =
"<primitiveInlineMap>\n"+
" <entity>\n" +
" <string>one</string>\n" +
" <bigDecimal>1.0</bigDecimal>\n" +
" </entity>\n"+
" <entity>" +
" <string>two</string>\n" +
" <bigDecimal>2.0</bigDecimal>\n" +
" </entity>\n"+
" <entity>" +
" <string>three</string>\n" +
" <bigDecimal>3.0</bigDecimal>\n" +
" </entity>\n"+
" <entity>" +
" <string>four</string>\n" +
" <bigDecimal>4.0</bigDecimal>\n" +
" </entity>\n"+
"</primitiveInlineMap>";
private const String INDEX_EXAMPLE =
"<?xml version='1.0' encoding='ISO-8859-1'?>\r\n" +
"<index id='users'>\r\n" +
" <database>xyz</database>\r\n" +
" <query>\r\n" +
" <columns>foo,bar</columns>\r\n" +
" <tables>a,b,c</tables>\r\n" +
" </query>\r\n" +
" <fields>\r\n" +
" <field id='foo'>\r\n" +
" <lucene>\r\n" +
" <index>TOKENIZED</index>\r\n" +
" <store>false</store>\r\n" +
" <default>true</default>\r\n" +
" </lucene>\r\n" +
" </field>\r\n" +
" <field id='bar'>\r\n" +
" <lucene>\r\n" +
" <index>TOKENIZED</index>\r\n" +
" <store>false</store>\r\n" +
" <default>true</default>\r\n" +
" </lucene>\r\n" +
" </field>\r\n" +
" </fields>\r\n" +
"</index>\r\n";
[Root(Name="index", Strict=false)]
public static class IndexConfig {
[Attribute]
private String id;
[Element]
private String database;
[Element]
private Query query;
[ElementMap(Name="fields", Entry="field", Key="id", Attribute=true, KeyType=String.class, ValueType=Lucene.class)]
private HashMap<String, Lucene> fields = new HashMap<String, Lucene>();
}
[Root]
public static class Field {
[Attribute]
private String id;
[Element]
private Lucene lucene;
}
[Root(Strict=false)]
public static class Lucene {
[Element]
private String index;
[Element]
private bool store;
[Element(Name="default")]
private bool flag;
}
[Root]
private static class Query {
[Element]
private String[] columns;
[Element]
private String[] tables;
}
[Root]
private static class EntryMap {
[ElementMap(Key="key", Attribute=true)]
private Map<String, MapEntry> map;
public String GetValue(String name) {
return map.get(name).value;
}
}
[Root]
private static class MapEntry {
[Element]
private String name;
[Element]
private String value;
public MapEntry() {
super();
}
public MapEntry(String name, String value) {
this.name = name;
this.value = value;
}
}
[Root]
private static class StringMap {
[ElementMap(Key="letter", Attribute=true, Data=true)]
private Map<String, String> map;
public String GetValue(String name) {
return map.get(name);
}
}
[Root]
private static class ComplexMap {
[ElementMap]
private Map<CompositeKey, MapEntry> map;
public ComplexMap() {
this.map = new HashMap<CompositeKey, MapEntry>();
}
public String GetValue(CompositeKey key) {
return map.get(key).value;
}
}
[Root]
private static class CompositeKey {
[Element]
private String name;
[Element]
private String address;
public CompositeKey() {
super();
}
public CompositeKey(String name, String address) {
this.name = name;
this.address = address;
}
public int HashCode() {
return name.HashCode() + address.HashCode();
}
public bool Equals(Object item) {
if(item instanceof CompositeKey) {
CompositeKey other = (CompositeKey)item;
return other.name.Equals(name) && other.address.Equals(address);
}
return false;
}
}
[Root]
private static class PrimitiveMap {
[ElementMap(Name="table")]
private Map<String, BigDecimal> map;
public PrimitiveMap() {
this.map = new HashMap<String, BigDecimal>();
}
public BigDecimal GetValue(String name) {
return map.get(name);
}
}
[Root]
private static class PrimitiveValueOverrideMap {
[ElementMap(Value="decimal")]
private Map<String, BigDecimal> map;
public BigDecimal GetValue(String name) {
return map.get(name);
}
}
[Root]
private static class PrimitiveValueKeyOverrideMap {
[ElementMap(Value="decimal", Key="text", Entry="item")]
private Map<String, BigDecimal> map;
public BigDecimal GetValue(String name) {
return map.get(name);
}
}
[Root]
private static class ComplexValueKeyOverrideMap {
[ElementMap(Key="key", Value="value", Entry="item")]
private Map<CompositeKey, MapEntry> map;
public ComplexValueKeyOverrideMap() {
this.map = new HashMap<CompositeKey, MapEntry>();
}
public String GetValue(CompositeKey key) {
return map.get(key).value;
}
}
[Root]
private static class PrimitiveInlineMap {
[ElementMap(Entry="entity", Inline=true)]
private Map<String, BigDecimal> map;
public BigDecimal GetValue(String name) {
return map.get(name);
}
}
public void TestEntryMap() {
Serializer serializer = new Persister();
EntryMap example = serializer.read(EntryMap.class, ENTRY_MAP);
AssertEquals("example 1", example.GetValue("a"));
AssertEquals("example 2", example.GetValue("b"));
AssertEquals("example 3", example.GetValue("c"));
AssertEquals("example 4", example.GetValue("d"));
validate(example, serializer);
}
public void TestStringMap() {
Serializer serializer = new Persister();
StringMap example = serializer.read(StringMap.class, STRING_MAP);
AssertEquals("example 1", example.GetValue("a"));
AssertEquals("example 2", example.GetValue("b"));
AssertEquals("example 3", example.GetValue("c"));
AssertEquals("example 4", example.GetValue("d"));
validate(example, serializer);
}
public void TestComplexMap() {
Serializer serializer = new Persister();
ComplexMap example = serializer.read(ComplexMap.class, COMPLEX_MAP);
AssertEquals("example 1", example.GetValue(new CompositeKey("name 1", "address 1")));
AssertEquals("example 2", example.GetValue(new CompositeKey("name 2", "address 2")));
AssertEquals("example 3", example.GetValue(new CompositeKey("name 3", "address 3")));
AssertEquals("example 4", example.GetValue(new CompositeKey("name 4", "address 4")));
validate(example, serializer);
}
public void TestPrimitiveMap() {
Serializer serializer = new Persister();
PrimitiveMap example = serializer.read(PrimitiveMap.class, PRIMITIVE_MAP);
AssertEquals(new BigDecimal("1.0"), example.GetValue("one"));
AssertEquals(new BigDecimal("2.0"), example.GetValue("two"));
AssertEquals(new BigDecimal("3.0"), example.GetValue("three"));
AssertEquals(new BigDecimal("4.0"), example.GetValue("four"));
validate(example, serializer);
}
public void TestPrimitiveValueOverrideMap() {
Serializer serializer = new Persister();
PrimitiveValueOverrideMap example = serializer.read(PrimitiveValueOverrideMap.class, PRIMITIVE_VALUE_OVERRIDE_MAP);
AssertEquals(new BigDecimal("1.0"), example.GetValue("one"));
AssertEquals(new BigDecimal("2.0"), example.GetValue("two"));
AssertEquals(new BigDecimal("3.0"), example.GetValue("three"));
AssertEquals(new BigDecimal("4.0"), example.GetValue("four"));
validate(example, serializer);
}
public void TestPrimitiveValueKeyOverrideMap() {
Serializer serializer = new Persister();
PrimitiveValueKeyOverrideMap example = serializer.read(PrimitiveValueKeyOverrideMap.class, PRIMITIVE_VALUE_KEY_OVERRIDE_MAP);
AssertEquals(new BigDecimal("1.0"), example.GetValue("one"));
AssertEquals(new BigDecimal("2.0"), example.GetValue("two"));
AssertEquals(new BigDecimal("3.0"), example.GetValue("three"));
AssertEquals(new BigDecimal("4.0"), example.GetValue("four"));
validate(example, serializer);
}
public void TestComplexValueKeyOverrideMap() {
Serializer serializer = new Persister();
ComplexValueKeyOverrideMap example = serializer.read(ComplexValueKeyOverrideMap.class, COMPLEX_VALUE_KEY_OVERRIDE_MAP);
AssertEquals("example 1", example.GetValue(new CompositeKey("name 1", "address 1")));
AssertEquals("example 2", example.GetValue(new CompositeKey("name 2", "address 2")));
AssertEquals("example 3", example.GetValue(new CompositeKey("name 3", "address 3")));
AssertEquals("example 4", example.GetValue(new CompositeKey("name 4", "address 4")));
validate(example, serializer);
}
public void TestPrimitiveInlineMap() {
Serializer serializer = new Persister();
PrimitiveInlineMap example = serializer.read(PrimitiveInlineMap.class, PRIMITIVE_INLINE_MAP);
AssertEquals(new BigDecimal("1.0"), example.GetValue("one"));
AssertEquals(new BigDecimal("2.0"), example.GetValue("two"));
AssertEquals(new BigDecimal("3.0"), example.GetValue("three"));
AssertEquals(new BigDecimal("4.0"), example.GetValue("four"));
validate(example, serializer);
}
public void TestNullValue() {
Serializer serializer = new Persister();
PrimitiveMap primitiveMap = new PrimitiveMap();
primitiveMap.map.put("a", new BigDecimal(1));
primitiveMap.map.put("b", new BigDecimal(2));
primitiveMap.map.put("c", null);
primitiveMap.map.put(null, new BigDecimal(4));
StringWriter out = new StringWriter();
serializer.write(primitiveMap, out);
primitiveMap = serializer.read(PrimitiveMap.class, out.toString());
AssertEquals(primitiveMap.map.get(null), new BigDecimal(4));
AssertEquals(primitiveMap.map.get("c"), null);
AssertEquals(primitiveMap.map.get("a"), new BigDecimal(1));
AssertEquals(primitiveMap.map.get("b"), new BigDecimal(2));
validate(primitiveMap, serializer);
ComplexMap complexMap = new ComplexMap();
complexMap.map.put(new CompositeKey("name.1", "address.1"), new MapEntry("1", "1"));
complexMap.map.put(new CompositeKey("name.2", "address.2"), new MapEntry("2", "2"));
complexMap.map.put(null, new MapEntry("3", "3"));
complexMap.map.put(new CompositeKey("name.4", "address.4"), null);
validate(complexMap, serializer);
}
public void TestIndexExample() {
Serializer serializer = new Persister();
IndexConfig config = serializer.read(IndexConfig.class, INDEX_EXAMPLE);
validate(config, serializer);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace System.Reflection
{
internal class RuntimeModule : Module
{
internal RuntimeModule() { throw new NotSupportedException(); }
#region FCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetType(QCallModule module, string className, bool throwOnError, bool ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
[DllImport(JitHelpers.QCall)]
private static extern bool nIsTransientInternal(QCallModule module);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetScopeName(QCallModule module, StringHandleOnStack retString);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetFullyQualifiedName(QCallModule module, StringHandleOnStack retString);
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern RuntimeType[] GetTypes(RuntimeModule module);
internal RuntimeType[] GetDefinedTypes()
{
return GetTypes(GetNativeHandle());
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool IsResource(RuntimeModule module);
#endregion
#region Module overrides
private static RuntimeTypeHandle[]? ConvertToTypeHandleArray(Type[]? genericArguments)
{
if (genericArguments == null)
return null;
int size = genericArguments.Length;
RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
for (int i = 0; i < size; i++)
{
Type typeArg = genericArguments[i];
if (typeArg == null)
throw new ArgumentException(SR.Argument_InvalidGenericInstArray);
typeArg = typeArg.UnderlyingSystemType;
if (typeArg == null)
throw new ArgumentException(SR.Argument_InvalidGenericInstArray);
if (!(typeArg is RuntimeType))
throw new ArgumentException(SR.Argument_InvalidGenericInstArray);
typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
}
return typeHandleArgs;
}
public override byte[] ResolveSignature(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
throw new ArgumentException(SR.Format(SR.Argument_InvalidToken, tk, this),
nameof(metadataToken));
ConstArray signature;
if (tk.IsMemberRef)
signature = MetadataImport.GetMemberRefProps(metadataToken);
else
signature = MetadataImport.GetSignatureFromToken(metadataToken);
byte[] sig = new byte[signature.Length];
for (int i = 0; i < signature.Length; i++)
sig[i] = signature[i];
return sig;
}
public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
if (!tk.IsMethodDef && !tk.IsMethodSpec)
{
if (!tk.IsMemberRef)
throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, tk, this),
nameof(metadataToken));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, tk, this),
nameof(metadataToken));
}
}
IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
if (declaringType.IsGenericType || declaringType.IsArray)
{
MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk));
if (tk.IsMethodSpec)
tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType));
declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
}
return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);
}
catch (BadImageFormatException e)
{
throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
}
}
private FieldInfo? ResolveLiteralField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
int tkDeclaringType;
string fieldName = MetadataImport.GetName(tk).ToString();
tkDeclaringType = MetadataImport.GetParentToken(tk);
Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
declaringType.GetFields();
try
{
return declaringType.GetField(fieldName,
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly);
}
catch
{
throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this), nameof(metadataToken));
}
}
public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
IRuntimeFieldInfo fieldHandle;
if (!tk.IsFieldDef)
{
if (!tk.IsMemberRef)
throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this),
nameof(metadataToken));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this),
nameof(metadataToken));
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs);
RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);
if (declaringType.IsGenericType || declaringType.IsArray)
{
int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken);
declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
}
return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
}
catch (MissingFieldException)
{
return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
}
catch (BadImageFormatException e)
{
throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
}
}
public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (tk.IsGlobalTypeDefToken)
throw new ArgumentException(SR.Format(SR.Argument_ResolveModuleType, tk), nameof(metadataToken));
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken));
RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
Type t = GetModuleHandleImpl().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
if (t == null)
throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken));
return t;
}
catch (BadImageFormatException e)
{
throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
}
}
public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (tk.IsProperty)
throw new ArgumentException(SR.InvalidOperation_PropertyInfoNotAvailable);
if (tk.IsEvent)
throw new ArgumentException(SR.InvalidOperation_EventInfoNotAvailable);
if (tk.IsMethodSpec || tk.IsMethodDef)
return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsFieldDef)
return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsMemberRef)
{
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
unsafe
{
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
{
return ResolveField(tk, genericTypeArguments, genericMethodArguments);
}
else
{
return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
}
}
}
throw new ArgumentException(SR.Format(SR.Argument_ResolveMember, tk, this),
nameof(metadataToken));
}
public override string ResolveString(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!tk.IsString)
throw new ArgumentException(
SR.Format(SR.Argument_ResolveString, metadataToken, this));
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
string? str = MetadataImport.GetUserString(metadataToken);
if (str == null)
throw new ArgumentException(
SR.Format(SR.Argument_ResolveString, metadataToken, this));
return str;
}
public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine);
}
public override int MDStreamVersion => ModuleHandle.GetMDStreamVersion(GetNativeHandle());
#endregion
#region Data Members
#pragma warning disable CA1823, 169
// If you add any data members, you need to update the native declaration ReflectModuleBaseObject.
private RuntimeType m_runtimeType;
private RuntimeAssembly m_runtimeAssembly;
private IntPtr m_pRefClass;
private IntPtr m_pData;
private IntPtr m_pGlobals;
private IntPtr m_pFields;
#pragma warning restore CA1823, 169
#endregion
#region Protected Virtuals
protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder,
CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
}
internal MethodInfo? GetMethodInternal(string name, BindingFlags bindingAttr, Binder? binder,
CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
if (RuntimeType == null)
return null;
if (types == null)
{
return RuntimeType.GetMethod(name, bindingAttr);
}
else
{
return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
}
}
#endregion
#region Internal Members
internal RuntimeType RuntimeType => m_runtimeType ??= ModuleHandle.GetModuleType(this);
internal bool IsTransientInternal()
{
RuntimeModule thisAsLocal = this;
return RuntimeModule.nIsTransientInternal(JitHelpers.GetQCallModuleOnStack(ref thisAsLocal));
}
internal MetadataImport MetadataImport => ModuleHandle.GetMetadataImport(this);
#endregion
#region ICustomAttributeProvider Members
public override object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region Public Virtuals
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public override Type? GetType(string className, bool throwOnError, bool ignoreCase)
{
// throw on null strings regardless of the value of "throwOnError"
if (className == null)
throw new ArgumentNullException(nameof(className));
RuntimeType? retType = null;
object? keepAlive = null;
RuntimeModule thisAsLocal = this;
GetType(JitHelpers.GetQCallModuleOnStack(ref thisAsLocal), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return retType;
}
internal string GetFullyQualifiedName()
{
string? fullyQualifiedName = null;
RuntimeModule thisAsLocal = this;
GetFullyQualifiedName(JitHelpers.GetQCallModuleOnStack(ref thisAsLocal), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName));
return fullyQualifiedName!;
}
public override string FullyQualifiedName => GetFullyQualifiedName();
public override Type[] GetTypes()
{
return GetTypes(GetNativeHandle());
}
#endregion
#region Public Members
public override Guid ModuleVersionId
{
get
{
MetadataImport.GetScopeProps(out Guid mvid);
return mvid;
}
}
public override int MetadataToken => ModuleHandle.GetToken(GetNativeHandle());
public override bool IsResource()
{
return IsResource(GetNativeHandle());
}
public override FieldInfo[] GetFields(BindingFlags bindingFlags)
{
if (RuntimeType == null)
return Array.Empty<FieldInfo>();
return RuntimeType.GetFields(bindingFlags);
}
public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (RuntimeType == null)
return null;
return RuntimeType.GetField(name, bindingAttr);
}
public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
{
if (RuntimeType == null)
return Array.Empty<MethodInfo>();
return RuntimeType.GetMethods(bindingFlags);
}
public override string ScopeName
{
get
{
string? scopeName = null;
RuntimeModule thisAsLocal = this;
GetScopeName(JitHelpers.GetQCallModuleOnStack(ref thisAsLocal), JitHelpers.GetStringHandleOnStack(ref scopeName));
return scopeName!;
}
}
public override string Name
{
get
{
string s = GetFullyQualifiedName();
#if !FEATURE_PAL
int i = s.LastIndexOf('\\');
#else
int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
#endif
if (i == -1)
return s;
return s.Substring(i + 1);
}
}
public override Assembly Assembly => GetRuntimeAssembly();
internal RuntimeAssembly GetRuntimeAssembly()
{
return m_runtimeAssembly;
}
protected override ModuleHandle GetModuleHandleImpl()
{
return new ModuleHandle(this);
}
internal RuntimeModule GetNativeHandle()
{
return this;
}
internal IntPtr GetUnderlyingNativeHandle()
{
return m_pData;
}
#endregion
}
}
| |
//
// BaseAssemblyResolver.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public delegate AssemblyDefinition AssemblyResolveEventHandler (object sender, AssemblyNameReference reference);
public sealed class AssemblyResolveEventArgs : EventArgs {
readonly AssemblyNameReference reference;
public AssemblyNameReference AssemblyReference {
get { return reference; }
}
public AssemblyResolveEventArgs (AssemblyNameReference reference)
{
this.reference = reference;
}
}
#if !SILVERLIGHT && !CF
[Serializable]
#endif
public class AssemblyResolutionException : FileNotFoundException {
readonly AssemblyNameReference reference;
public AssemblyNameReference AssemblyReference {
get { return reference; }
}
public AssemblyResolutionException (AssemblyNameReference reference)
: base (string.Format ("Failed to resolve assembly: '{0}'", reference))
{
this.reference = reference;
}
#if !SILVERLIGHT && !CF
protected AssemblyResolutionException (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base (info, context)
{
}
#endif
}
public abstract class BaseAssemblyResolver : IAssemblyResolver {
static readonly bool on_mono = Type.GetType ("Mono.Runtime") != null;
readonly Collection<string> directories;
#if !SILVERLIGHT && !CF
Collection<string> gac_paths;
#endif
public void AddSearchDirectory (string directory)
{
directories.Add (directory);
}
public void RemoveSearchDirectory (string directory)
{
directories.Remove (directory);
}
public string [] GetSearchDirectories ()
{
var directories = new string [this.directories.size];
Array.Copy (this.directories.items, directories, directories.Length);
return directories;
}
public virtual AssemblyDefinition Resolve (string fullName)
{
return Resolve (fullName, new ReaderParameters ());
}
public virtual AssemblyDefinition Resolve (string fullName, ReaderParameters parameters)
{
if (fullName == null)
throw new ArgumentNullException ("fullName");
return Resolve (AssemblyNameReference.Parse (fullName), parameters);
}
public event AssemblyResolveEventHandler ResolveFailure;
protected BaseAssemblyResolver ()
{
directories = new Collection<string> (2) { ".", "bin" };
}
AssemblyDefinition GetAssembly (string file, ReaderParameters parameters)
{
if (parameters.AssemblyResolver == null)
parameters.AssemblyResolver = this;
return ModuleDefinition.ReadModule (file, parameters).Assembly;
}
public virtual AssemblyDefinition Resolve (AssemblyNameReference name)
{
return Resolve (name, new ReaderParameters ());
}
public virtual AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters)
{
if (name == null)
throw new ArgumentNullException ("name");
if (parameters == null)
parameters = new ReaderParameters ();
var assembly = SearchDirectory (name, directories, parameters);
if (assembly != null)
return assembly;
#if !SILVERLIGHT && !CF
if (name.IsRetargetable) {
// if the reference is retargetable, zero it
name = new AssemblyNameReference (name.Name, new Version (0, 0, 0, 0)) {
PublicKeyToken = Empty<byte>.Array,
};
}
var framework_dir = Path.GetDirectoryName (typeof (object).Module.FullyQualifiedName);
if (IsZero (name.Version)) {
assembly = SearchDirectory (name, new [] { framework_dir }, parameters);
if (assembly != null)
return assembly;
}
if (name.Name == "mscorlib") {
assembly = GetCorlib (name, parameters);
if (assembly != null)
return assembly;
}
assembly = GetAssemblyInGac (name, parameters);
if (assembly != null)
return assembly;
assembly = SearchDirectory (name, new [] { framework_dir }, parameters);
if (assembly != null)
return assembly;
#endif
if (ResolveFailure != null) {
assembly = ResolveFailure (this, name);
if (assembly != null)
return assembly;
}
throw new AssemblyResolutionException (name);
}
AssemblyDefinition SearchDirectory (AssemblyNameReference name, IEnumerable<string> directories, ReaderParameters parameters)
{
var extensions = new [] { ".exe", ".dll" };
foreach (var directory in directories) {
foreach (var extension in extensions) {
string file = Path.Combine (directory, name.Name + extension);
if (File.Exists (file))
return GetAssembly (file, parameters);
}
}
return null;
}
static bool IsZero (Version version)
{
return version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0 && version.Revision == 0);
}
#if !SILVERLIGHT && !CF
AssemblyDefinition GetCorlib (AssemblyNameReference reference, ReaderParameters parameters)
{
var version = reference.Version;
var corlib = typeof (object).Assembly.GetName ();
if (corlib.Version == version || IsZero (version))
return GetAssembly (typeof (object).Module.FullyQualifiedName, parameters);
var path = Directory.GetParent (
Directory.GetParent (
typeof (object).Module.FullyQualifiedName).FullName
).FullName;
if (on_mono) {
if (version.Major == 1)
path = Path.Combine (path, "1.0");
else if (version.Major == 2) {
if (version.MajorRevision == 5)
path = Path.Combine (path, "2.1");
else
path = Path.Combine (path, "2.0");
} else if (version.Major == 4)
path = Path.Combine (path, "4.0");
else
throw new NotSupportedException ("Version not supported: " + version);
} else {
switch (version.Major) {
case 1:
if (version.MajorRevision == 3300)
path = Path.Combine (path, "v1.0.3705");
else
path = Path.Combine (path, "v1.0.5000.0");
break;
case 2:
path = Path.Combine (path, "v2.0.50727");
break;
case 4:
path = Path.Combine (path, "v4.0.30319");
break;
default:
throw new NotSupportedException ("Version not supported: " + version);
}
}
var file = Path.Combine (path, "mscorlib.dll");
if (File.Exists (file))
return GetAssembly (file, parameters);
return null;
}
static Collection<string> GetGacPaths ()
{
if (on_mono)
return GetDefaultMonoGacPaths ();
var paths = new Collection<string> (2);
var windir = Environment.GetEnvironmentVariable ("WINDIR");
if (windir == null)
return paths;
paths.Add (Path.Combine (windir, "assembly"));
paths.Add (Path.Combine (windir, Path.Combine ("Microsoft.NET", "assembly")));
return paths;
}
static Collection<string> GetDefaultMonoGacPaths ()
{
var paths = new Collection<string> (1);
var gac = GetCurrentMonoGac ();
if (gac != null)
paths.Add (gac);
var gac_paths_env = Environment.GetEnvironmentVariable ("MONO_GAC_PREFIX");
if (string.IsNullOrEmpty (gac_paths_env))
return paths;
var prefixes = gac_paths_env.Split (Path.PathSeparator);
foreach (var prefix in prefixes) {
if (string.IsNullOrEmpty (prefix))
continue;
var gac_path = Path.Combine (Path.Combine (Path.Combine (prefix, "lib"), "mono"), "gac");
if (Directory.Exists (gac_path) && !paths.Contains (gac))
paths.Add (gac_path);
}
return paths;
}
static string GetCurrentMonoGac ()
{
return Path.Combine (
Directory.GetParent (
Path.GetDirectoryName (typeof (object).Module.FullyQualifiedName)).FullName,
"gac");
}
AssemblyDefinition GetAssemblyInGac (AssemblyNameReference reference, ReaderParameters parameters)
{
if (reference.PublicKeyToken == null || reference.PublicKeyToken.Length == 0)
return null;
if (gac_paths == null)
gac_paths = GetGacPaths ();
if (on_mono)
return GetAssemblyInMonoGac (reference, parameters);
return GetAssemblyInNetGac (reference, parameters);
}
AssemblyDefinition GetAssemblyInMonoGac (AssemblyNameReference reference, ReaderParameters parameters)
{
for (int i = 0; i < gac_paths.Count; i++) {
var gac_path = gac_paths [i];
var file = GetAssemblyFile (reference, string.Empty, gac_path);
if (File.Exists (file))
return GetAssembly (file, parameters);
}
return null;
}
AssemblyDefinition GetAssemblyInNetGac (AssemblyNameReference reference, ReaderParameters parameters)
{
var gacs = new [] { "GAC_MSIL", "GAC_32", "GAC_64", "GAC" };
var prefixes = new [] { string.Empty, "v4.0_" };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < gacs.Length; j++) {
var gac = Path.Combine (gac_paths [i], gacs [j]);
var file = GetAssemblyFile (reference, prefixes [i], gac);
if (Directory.Exists (gac) && File.Exists (file))
return GetAssembly (file, parameters);
}
}
return null;
}
static string GetAssemblyFile (AssemblyNameReference reference, string prefix, string gac)
{
var gac_folder = new StringBuilder ()
.Append (prefix)
.Append (reference.Version)
.Append ("__");
for (int i = 0; i < reference.PublicKeyToken.Length; i++)
gac_folder.Append (reference.PublicKeyToken [i].ToString ("x2"));
return Path.Combine (
Path.Combine (
Path.Combine (gac, reference.Name), gac_folder.ToString ()),
reference.Name + ".dll");
}
#endif
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. 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.
#endregion
namespace MoreLinq.Test
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using NUnit.Framework;
[TestFixture]
public class ToDataTableTest
{
class TestObject
{
public int KeyField;
public Guid? ANullableGuidField;
public string AString { get; }
public decimal? ANullableDecimal { get; }
public object this[int index]
{
get => new object();
set { }
}
public TestObject(int key)
{
KeyField = key;
ANullableGuidField = Guid.NewGuid();
ANullableDecimal = key / 3;
AString = "ABCDEFGHIKKLMNOPQRSTUVWXYSZ";
}
}
readonly IReadOnlyCollection<TestObject> _testObjects;
public ToDataTableTest()
{
_testObjects = Enumerable.Range(0, 3)
.Select(i => new TestObject(i))
.ToArray();
}
[Test]
public void ToDataTableNullMemberExpressionMethod()
{
Expression<Func<TestObject, object>> expression = null;
AssertThrowsArgument.Exception("expressions",() =>
_testObjects.ToDataTable<TestObject>(expression));
}
[Test]
public void ToDataTableTableWithWrongColumnNames()
{
var dt = new DataTable();
dt.Columns.Add("Test");
AssertThrowsArgument.Exception("table",() =>
_testObjects.ToDataTable(dt));
}
[Test]
public void ToDataTableTableWithWrongColumnDataType()
{
var dt = new DataTable();
dt.Columns.Add("AString", typeof(int));
AssertThrowsArgument.Exception("table",() =>
_testObjects.ToDataTable(dt, t=>t.AString));
}
[Test]
public void ToDataTableMemberExpressionMethod()
{
AssertThrowsArgument.Exception("lambda", () =>
_testObjects.ToDataTable(t => t.ToString()));
}
[Test]
public void ToDataTableMemberExpressionNonMember()
{
AssertThrowsArgument.Exception("lambda", () =>
_testObjects.ToDataTable(t => t.ToString().Length));
}
[Test]
public void ToDataTableMemberExpressionIndexer()
{
AssertThrowsArgument.Exception("lambda",() =>
_testObjects.ToDataTable(t => t[0]));
}
[Test]
public void ToDataTableSchemaInDeclarationOrder()
{
var dt = _testObjects.ToDataTable();
// Assert properties first, then fields, then in declaration order
Assert.AreEqual("AString", dt.Columns[0].Caption);
Assert.AreEqual(typeof(string), dt.Columns[0].DataType);
Assert.AreEqual("ANullableDecimal", dt.Columns[1].Caption);
Assert.AreEqual(typeof(decimal), dt.Columns[1].DataType);
Assert.AreEqual("KeyField", dt.Columns[2].Caption);
Assert.AreEqual(typeof(int), dt.Columns[2].DataType);
Assert.AreEqual("ANullableGuidField", dt.Columns[3].Caption);
Assert.AreEqual(typeof(Guid), dt.Columns[3].DataType);
Assert.IsTrue(dt.Columns[3].AllowDBNull);
Assert.AreEqual(4, dt.Columns.Count);
}
[Test]
public void ToDataTableContainsAllElements()
{
var dt = _testObjects.ToDataTable();
Assert.AreEqual(_testObjects.Count, dt.Rows.Count);
}
[Test]
public void ToDataTableWithExpression()
{
var dt = _testObjects.ToDataTable(t => t.AString);
Assert.AreEqual("AString", dt.Columns[0].Caption);
Assert.AreEqual(typeof(string), dt.Columns[0].DataType);
Assert.AreEqual(1, dt.Columns.Count);
}
[Test]
public void ToDataTableWithSchema()
{
var dt = new DataTable();
var columns = dt.Columns;
columns.Add("Column1", typeof(int));
columns.Add("Value", typeof(string));
columns.Add("Column3", typeof(int));
columns.Add("Name", typeof(string));
var vars = Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.ToArray();
vars.Select(e => new { Name = e.Key.ToString(), Value = e.Value.ToString() })
.ToDataTable(dt, e => e.Name, e => e.Value);
var rows = dt.Rows.Cast<DataRow>().ToArray();
Assert.That(rows.Length, Is.EqualTo(vars.Length));
Assert.That(rows.Select(r => r["Name"]).ToArray(), Is.EqualTo(vars.Select(e => e.Key).ToArray()));
Assert.That(rows.Select(r => r["Value"]).ToArray(), Is.EqualTo(vars.Select(e => e.Value).ToArray()));
}
struct Point
{
public static Point Empty = new Point();
public bool IsEmpty => X == 0 && Y == 0;
public int X { get; }
public int Y { get; }
public Point(int x, int y) : this() { X = x; Y = y; }
}
[Test]
public void ToDataTableIgnoresStaticMembers()
{
var points = new[] { new Point(12, 34) }.ToDataTable();
Assert.AreEqual(3, points.Columns.Count);
DataColumn x, y, empty;
Assert.NotNull(x = points.Columns["X"]);
Assert.NotNull(y = points.Columns["Y"]);
Assert.NotNull(empty = points.Columns["IsEmpty"]);
var row = points.Rows.Cast<DataRow>().Single();
Assert.AreEqual(12, row[x]);
Assert.AreEqual(34, row[y]);
Assert.AreEqual(false, row[empty]);
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using DebuggerApi;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using YetiCommon.CastleAspects;
using YetiCommon.PerformanceTracing;
using YetiVSI.DebugEngine.Variables;
using YetiVSI.Metrics;
namespace YetiVSI.DebugEngine
{
public interface IAsyncExpressionEvaluator
{
Task<EvaluationResult> EvaluateExpressionAsync();
}
public class EvaluationResult
{
public IDebugProperty2 Result { get; }
public int Status { get; }
public static EvaluationResult Fail() => new EvaluationResult(null, VSConstants.E_FAIL);
public static EvaluationResult FromResult(IDebugProperty2 result) =>
new EvaluationResult(result, VSConstants.S_OK);
EvaluationResult(IDebugProperty2 result, int status)
{
Result = result;
Status = status;
}
}
public class AsyncExpressionEvaluator : SimpleDecoratorSelf<IAsyncExpressionEvaluator>,
IAsyncExpressionEvaluator
{
public class Factory
{
readonly IGgpDebugPropertyFactory _propertyFactory;
readonly VarInfoBuilder _varInfoBuilder;
readonly VsExpressionCreator _vsExpressionCreator;
readonly ErrorDebugProperty.Factory _errorDebugPropertyFactory;
readonly IDebugEngineCommands _debugEngineCommands;
readonly IExtensionOptions _extensionOptions;
readonly ExpressionEvaluationRecorder _expressionEvaluationRecorder;
readonly ITimeSource _timeSource;
[Obsolete("This constructor only exists to support mocking libraries.", error: true)]
protected Factory()
{
}
public Factory(IGgpDebugPropertyFactory propertyFactory,
VarInfoBuilder varInfoBuilder,
VsExpressionCreator vsExpressionCreator,
ErrorDebugProperty.Factory errorDebugPropertyFactory,
IDebugEngineCommands debugEngineCommands,
IExtensionOptions extensionOptions,
ExpressionEvaluationRecorder expressionEvaluationRecorder,
ITimeSource timeSource)
{
_propertyFactory = propertyFactory;
_varInfoBuilder = varInfoBuilder;
_vsExpressionCreator = vsExpressionCreator;
_errorDebugPropertyFactory = errorDebugPropertyFactory;
_debugEngineCommands = debugEngineCommands;
_extensionOptions = extensionOptions;
_expressionEvaluationRecorder = expressionEvaluationRecorder;
_timeSource = timeSource;
}
public virtual IAsyncExpressionEvaluator Create(
RemoteTarget target, RemoteFrame frame, string text)
{
// Get preferred expression evaluation option. This is performed here to
// pick up configuration changes in runtime (e.g. the user can enable and
// disable lldb-eval during a single debug session).
var expressionEvaluationStrategy = _extensionOptions.ExpressionEvaluationStrategy;
return new AsyncExpressionEvaluator(target, frame, text, _vsExpressionCreator,
_varInfoBuilder, _propertyFactory,
_errorDebugPropertyFactory,
_debugEngineCommands,
expressionEvaluationStrategy,
_expressionEvaluationRecorder, _timeSource);
}
}
const ExpressionEvaluationContext _expressionEvaluationContext =
ExpressionEvaluationContext.FRAME;
readonly VsExpressionCreator _vsExpressionCreator;
readonly VarInfoBuilder _varInfoBuilder;
readonly IGgpDebugPropertyFactory _propertyFactory;
readonly ErrorDebugProperty.Factory _errorDebugPropertyFactory;
readonly IDebugEngineCommands _debugEngineCommands;
readonly RemoteTarget _target;
readonly RemoteFrame _frame;
readonly string _text;
readonly ExpressionEvaluationStrategy _expressionEvaluationStrategy;
readonly ExpressionEvaluationRecorder _expressionEvaluationRecorder;
readonly ITimeSource _timeSource;
AsyncExpressionEvaluator(RemoteTarget target, RemoteFrame frame, string text,
VsExpressionCreator vsExpressionCreator,
VarInfoBuilder varInfoBuilder,
IGgpDebugPropertyFactory propertyFactory,
ErrorDebugProperty.Factory errorDebugPropertyFactory,
IDebugEngineCommands debugEngineCommands,
ExpressionEvaluationStrategy expressionEvaluationStrategy,
ExpressionEvaluationRecorder expressionEvaluationRecorder,
ITimeSource timeSource)
{
_target = target;
_frame = frame;
_text = text;
_vsExpressionCreator = vsExpressionCreator;
_varInfoBuilder = varInfoBuilder;
_propertyFactory = propertyFactory;
_errorDebugPropertyFactory = errorDebugPropertyFactory;
_debugEngineCommands = debugEngineCommands;
_expressionEvaluationStrategy = expressionEvaluationStrategy;
_expressionEvaluationRecorder = expressionEvaluationRecorder;
_timeSource = timeSource;
}
public async Task<EvaluationResult> EvaluateExpressionAsync()
{
VsExpression vsExpression = await _vsExpressionCreator.CreateAsync(
_text, EvaluateSizeSpecifierExpressionAsync);
if (vsExpression.Value.StartsWith("."))
{
EvaluateCommand(vsExpression.Value, out IDebugProperty2 res);
return EvaluationResult.FromResult(res);
}
RemoteValue remoteValue = await CreateValueFromExpressionAsync(vsExpression.Value);
if (remoteValue == null)
{
return EvaluationResult.Fail();
}
string displayName = vsExpression.ToString();
IVariableInformation varInfo = _varInfoBuilder.Create(
remoteValue, displayName, vsExpression.FormatSpecifier);
IDebugProperty2 result = _propertyFactory.Create(_target, varInfo);
return EvaluationResult.FromResult(result);
}
async Task<uint> EvaluateSizeSpecifierExpressionAsync(string expression)
{
RemoteValue value = await CreateValueFromExpressionAsync(expression);
var err = value.GetError();
if (err.Fail())
{
throw new ExpressionEvaluationFailed(err.GetCString());
}
if (!uint.TryParse(value.GetValue(ValueFormat.Default), out uint size))
{
throw new ExpressionEvaluationFailed("Expression isn't a uint");
}
return size;
}
void EvaluateCommand(string command, out IDebugProperty2 debugProperty)
{
debugProperty = _errorDebugPropertyFactory.Create(command, "", "Invalid Command");
command = command.Trim();
if (command == ".natvisreload")
{
debugProperty = new CommandDebugProperty(".natvisreload", "", () =>
{
Trace.WriteLine("Reloading Natvis - triggered by .natvisreload command.");
var writer = new StringWriter();
Trace.WriteLine(
_debugEngineCommands.ReloadNatvis(writer, out string resultDescription)
? $".natvisreload result: {writer}"
: $"Unable to reload Natvis. {resultDescription}");
return resultDescription;
});
}
}
async Task<RemoteValue> CreateValueFromExpressionAsync(string expression)
{
var stepsRecorder = new ExpressionEvaluationRecorder.StepsRecorder(_timeSource);
long startTimestampUs = _timeSource.GetTimestampUs();
RemoteValue remoteValue =
await CreateValueFromExpressionWithMetricsAsync(expression, stepsRecorder);
long endTimestampUs = _timeSource.GetTimestampUs();
_expressionEvaluationRecorder.Record(_expressionEvaluationStrategy,
_expressionEvaluationContext, stepsRecorder,
startTimestampUs, endTimestampUs);
return remoteValue;
}
/// <summary>
/// Asynchronously creates RemoteValue from the expression. Returns null in case of error.
/// </summary>
async Task<RemoteValue> CreateValueFromExpressionWithMetricsAsync(
string expression, ExpressionEvaluationRecorder.StepsRecorder stepsRecorder)
{
if (_text.StartsWith(ExpressionConstants.RegisterPrefix))
{
// If text is prefixed by '$', check if it refers to a register by trying to find
// a register named expression[1:]. If we can't, simply return false to prevent
// LLDB scratch variables, which also start with '$', from being accessible.
return _frame.FindValue(expression.Substring(1), DebuggerApi.ValueType.Register);
}
if (_expressionEvaluationStrategy == ExpressionEvaluationStrategy.LLDB_EVAL ||
_expressionEvaluationStrategy ==
ExpressionEvaluationStrategy.LLDB_EVAL_WITH_FALLBACK)
{
RemoteValue value;
LldbEvalErrorCode errorCode;
using (var step = stepsRecorder.NewStep(ExpressionEvaluationEngine.LLDB_EVAL))
{
value = await _frame.EvaluateExpressionLldbEvalAsync(expression);
// Convert an error code to the enum value.
errorCode = (LldbEvalErrorCode)Enum.ToObject(
typeof(LldbEvalErrorCode), value.GetError().GetError());
step.Finalize(errorCode);
}
if (errorCode == LldbEvalErrorCode.Ok)
{
return value;
}
if (errorCode == LldbEvalErrorCode.InvalidNumericLiteral ||
errorCode == LldbEvalErrorCode.InvalidOperandType ||
errorCode == LldbEvalErrorCode.UndeclaredIdentifier)
{
// Evaluation failed with a well-known error. Don't fallback to LLDB native
// expression evaluator, since it will fail too.
return value;
}
if (_expressionEvaluationStrategy !=
ExpressionEvaluationStrategy.LLDB_EVAL_WITH_FALLBACK)
{
// Don't fallback to LLDB native expression evaluator if that option is
// disabled.
return value;
}
}
else
{
RemoteValue value;
using (var step =
stepsRecorder.NewStep(ExpressionEvaluationEngine.LLDB_VARIABLE_PATH))
{
value = EvaluateWithLldbVariablePath(expression);
step.Finalize(ToErrorCodeLLDB(value));
}
if (value != null)
{
return value;
}
}
// Evaluate the expression using LLDB.
{
RemoteValue value;
using (var step = stepsRecorder.NewStep(ExpressionEvaluationEngine.LLDB))
{
value = await _frame.EvaluateExpressionAsync(expression);
step.Finalize(ToErrorCodeLLDB(value));
}
return value;
}
LLDBErrorCode ToErrorCodeLLDB(RemoteValue v)
{
if (v == null)
{
return LLDBErrorCode.ERROR;
}
return v.GetError().Success() ? LLDBErrorCode.OK : LLDBErrorCode.ERROR;
}
}
RemoteValue EvaluateWithLldbVariablePath(string expression)
{
// Variables created via RemoteFrame::EvaluateExpression() don't return a valid,
// non-contextual fullname so we attempt to use
// RemoteFrame::GetValueForVariablePath() and RemoteFrame::FindValue() first. This
// ensures some UI elements (ex variable tooltips) show a human readable expression
// that can be re-evaluated across debug sessions.
// RemoteFrame::GetValueForVariablePath() was not returning the proper address of
// reference types. ex. "&myIntRef".
if (!_text.Contains("&"))
{
RemoteValue remoteValue = _frame.GetValueForVariablePath(expression);
if (remoteValue != null)
{
return remoteValue;
}
}
// Resolve static class variables because GetValueForVariablePath() doesn't.
return _frame.FindValue(expression, DebuggerApi.ValueType.VariableGlobal);
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SubscriptionOperations.
/// </summary>
public static partial class SubscriptionOperationsExtensions
{
/// <summary>
/// Lists all subscriptions of the API Management service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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>
public static IPage<SubscriptionContract> List(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, ODataQuery<SubscriptionContract> odataQuery = default(ODataQuery<SubscriptionContract>))
{
return ((ISubscriptionOperations)operations).ListAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all subscriptions of the API Management service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <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='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SubscriptionContract>> ListAsync(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, ODataQuery<SubscriptionContract> odataQuery = default(ODataQuery<SubscriptionContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the specified Subscription entity.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
public static SubscriptionContract Get(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid)
{
return operations.GetAsync(resourceGroupName, serviceName, sid).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified Subscription entity.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionContract> GetAsync(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, sid, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates the subscription of specified user to the specified
/// product.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
public static SubscriptionContract CreateOrUpdate(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, SubscriptionCreateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, sid, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates the subscription of specified user to the specified
/// product.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionContract> CreateOrUpdateAsync(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, SubscriptionCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, sid, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the details of a subscription specificied by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Subscription Entity. ETag should match the current entity state
/// from the header response of the GET request or it should be * for
/// unconditional update.
/// </param>
public static void Update(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, SubscriptionUpdateParameters parameters, string ifMatch)
{
operations.UpdateAsync(resourceGroupName, serviceName, sid, parameters, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the details of a subscription specificied by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Subscription Entity. ETag should match the current entity state
/// from the header response of the GET request or it should be * for
/// unconditional update.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, SubscriptionUpdateParameters parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, sid, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Subscription Entity. ETag should match the current entity state
/// from the header response of the GET request or it should be * for
/// unconditional update.
/// </param>
public static void Delete(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, string ifMatch)
{
operations.DeleteAsync(resourceGroupName, serviceName, sid, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Subscription Entity. ETag should match the current entity state
/// from the header response of the GET request or it should be * for
/// unconditional update.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, sid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Regenerates primary key of existing subscription of the API Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
public static void RegeneratePrimaryKey(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid)
{
operations.RegeneratePrimaryKeyAsync(resourceGroupName, serviceName, sid).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates primary key of existing subscription of the API Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RegeneratePrimaryKeyAsync(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.RegeneratePrimaryKeyWithHttpMessagesAsync(resourceGroupName, serviceName, sid, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Regenerates secondary key of existing subscription of the API Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
public static void RegenerateSecondaryKey(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid)
{
operations.RegenerateSecondaryKeyAsync(resourceGroupName, serviceName, sid).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates secondary key of existing subscription of the API Management
/// service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='sid'>
/// Subscription entity Identifier. The entity represents the association
/// between a user and a product in API Management.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RegenerateSecondaryKeyAsync(this ISubscriptionOperations operations, string resourceGroupName, string serviceName, string sid, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.RegenerateSecondaryKeyWithHttpMessagesAsync(resourceGroupName, serviceName, sid, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists all subscriptions of the API Management service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SubscriptionContract> ListNext(this ISubscriptionOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all subscriptions of the API Management service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SubscriptionContract>> ListNextAsync(this ISubscriptionOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Jasper.Logging;
using Jasper.Runtime.Scheduled;
namespace Jasper.Persistence.Durability
{
public class NulloEnvelopePersistence : IEnvelopePersistence, IEnvelopeStorageAdmin
{
public IEnvelopeStorageAdmin Admin => this;
public IScheduledJobProcessor ScheduledJobs { get; set; }
public Task DeleteIncomingEnvelopes(Envelope[] envelopes)
{
return Task.CompletedTask;
}
public Task DeleteIncomingEnvelope(Envelope envelope)
{
return Task.CompletedTask;
}
public Task DeleteOutgoing(Envelope[] envelopes)
{
return Task.CompletedTask;
}
public Task DeleteOutgoing(Envelope envelope)
{
return Task.CompletedTask;
}
public Task StoreOutgoing(DbTransaction tx, Envelope[] envelopes)
{
throw new NotSupportedException();
}
public Task MoveToDeadLetterStorage(ErrorReport[] errors)
{
return Task.CompletedTask;
}
public Task MoveToDeadLetterStorage(Envelope envelope, Exception ex)
{
return Task.CompletedTask;
}
public Task ScheduleExecution(Envelope[] envelopes)
{
return Task.CompletedTask;
}
public Task<ErrorReport> LoadDeadLetterEnvelope(Guid id)
{
return Task.FromResult<ErrorReport>(null);
}
public Task<IReadOnlyList<Envelope>> AllIncomingEnvelopes()
{
return Task.FromResult((IReadOnlyList<Envelope>)new List<Envelope>());
}
public Task<IReadOnlyList<Envelope>> AllOutgoingEnvelopes()
{
return Task.FromResult((IReadOnlyList<Envelope>)new List<Envelope>());
}
public Task ReleaseAllOwnership()
{
return Task.CompletedTask;
}
public Task IncrementIncomingEnvelopeAttempts(Envelope envelope)
{
return Task.CompletedTask;
}
public Task StoreIncoming(Envelope envelope)
{
if (envelope.Status == EnvelopeStatus.Scheduled)
{
if (envelope.ExecutionTime == null) throw new ArgumentOutOfRangeException($"The envelope {envelope} is marked as Scheduled, but does not have an ExecutionTime");
ScheduledJobs?.Enqueue(envelope.ExecutionTime.Value, envelope);
}
return Task.CompletedTask;
}
public Task StoreIncoming(Envelope[] envelopes)
{
foreach (var envelope in envelopes.Where(x => x.Status == EnvelopeStatus.Scheduled))
{
ScheduledJobs?.Enqueue(envelope.ExecutionTime.Value, envelope);
}
return Task.CompletedTask;
}
public Task<Uri[]> FindAllDestinations()
{
throw new NotSupportedException();
}
public Task DiscardAndReassignOutgoing(Envelope[] discards, Envelope[] reassigned, int nodeId)
{
return Task.CompletedTask;
}
public Task StoreOutgoing(Envelope envelope, int ownerId)
{
return Task.CompletedTask;
}
public Task StoreOutgoing(Envelope[] envelopes, int ownerId)
{
return Task.CompletedTask;
}
public Task<PersistedCounts> GetPersistedCounts()
{
// Nothing to do, but keeps the metrics from blowing up
return Task.FromResult(new PersistedCounts());
}
public void Describe(TextWriter writer)
{
writer.WriteLine("No persistent envelope storage");
}
public Task ClearAllPersistedEnvelopes()
{
return Task.CompletedTask;
}
public Task RebuildSchemaObjects()
{
return Task.CompletedTask;
}
public string CreateSql()
{
return string.Empty;
}
public Task ScheduleJob(Envelope envelope)
{
ScheduledJobs?.Enqueue(envelope.ExecutionTime.Value, envelope);
return Task.CompletedTask;
}
public void Dispose()
{
// Nothing
}
public IDurableStorageSession Session { get; } = null;
public Task<IReadOnlyList<Envelope>> LoadScheduledToExecute(DateTimeOffset utcNow)
{
throw new NotSupportedException();
}
public Task ReassignDormantNodeToAnyNode(int nodeId)
{
throw new NotSupportedException();
}
public Task<int[]> FindUniqueOwners(int currentNodeId)
{
throw new NotSupportedException();
}
public Task<IReadOnlyList<Envelope>> LoadOutgoing(Uri destination)
{
throw new NotSupportedException();
}
public Task ReassignOutgoing(int ownerId, Envelope[] outgoing)
{
throw new NotSupportedException();
}
public Task DeleteByDestination(Uri destination)
{
throw new NotSupportedException();
}
public Task<IReadOnlyList<Envelope>> LoadPageOfGloballyOwnedIncoming()
{
throw new NotSupportedException();
}
public Task ReassignIncoming(int ownerId, IReadOnlyList<Envelope> incoming)
{
throw new NotSupportedException();
}
}
}
| |
namespace StockSharp.Localization
{
using Ecng.Common;
partial class LocalizedStrings
{
/// <summary>
///
/// </summary>
public const string Dot = nameof(Dot);
private static string AppendDot(string value)
{
return value + ".";
}
/// <summary>
///
/// </summary>
public static string AreaColorDot => AppendDot(AreaColor);
/// <summary>
///
/// </summary>
public static string LineColorDot => AppendDot(LineColor);
/// <summary>
///
/// </summary>
public static string FontColorDot => AppendDot(FontColor);
/// <summary>
///
/// </summary>
public static string Timeframe2GridColorDot => AppendDot(Timeframe2GridColor);
/// <summary>
///
/// </summary>
public static string Timeframe2FrameColorDot => AppendDot(Timeframe2FrameColor);
/// <summary>
///
/// </summary>
public static string Timeframe3GridColorDot => AppendDot(Timeframe3GridColor);
/// <summary>
///
/// </summary>
public static string MaxVolumeColorDot => AppendDot(MaxVolumeColor);
/// <summary>
///
/// </summary>
public static string ClusterLineColorDot => AppendDot(ClusterLineColor);
/// <summary>
///
/// </summary>
public static string ClusterSeparatorLineColorDot => AppendDot(ClusterLineColor);
/// <summary>
///
/// </summary>
public static string ClusterTextColorDot => AppendDot(ClusterTextColor);
/// <summary>
///
/// </summary>
public static string ClusterColorDot => AppendDot(ClusterColor);
/// <summary>
///
/// </summary>
public static string ClusterMaxVolumeColorDot => AppendDot(ClusterMaxVolumeColor);
/// <summary>
///
/// </summary>
public static string ShowHorizontalVolumesDot => AppendDot(ShowHorizontalVolumes);
/// <summary>
///
/// </summary>
public static string LocalHorizontalVolumesDot => AppendDot(LocalHorizontalVolumes);
/// <summary>
///
/// </summary>
public static string HorizontalVolumeWidthFractionDot => AppendDot(HorizontalVolumeWidthFraction);
/// <summary>
///
/// </summary>
public static string HorizontalVolumeColorDot => AppendDot(HorizontalVolumeColor);
/// <summary>
///
/// </summary>
public static string HorizontalVolumeFontColorDot => AppendDot(HorizontalVolumeFontColor);
/// <summary>
///
/// </summary>
public static string Str2933Dot => AppendDot(Str2933);
/// <summary>
///
/// </summary>
public static string BuyPendingColorDot => AppendDot(BuyPendingColor);
/// <summary>
///
/// </summary>
public static string BuyColorDot => AppendDot(BuyColor);
/// <summary>
///
/// </summary>
public static string BuyBlinkColorDot => AppendDot(BuyBlinkColor);
/// <summary>
///
/// </summary>
public static string SellPendingColorDot => AppendDot(SellPendingColor);
/// <summary>
///
/// </summary>
public static string SellColorDot => AppendDot(SellColor);
/// <summary>
///
/// </summary>
public static string SellBlinkColorDot => AppendDot(SellBlinkColor);
/// <summary>
///
/// </summary>
public static string CancelButtonColorDot => AppendDot(CancelButtonColor);
/// <summary>
///
/// </summary>
public static string CancelButtonBgColorDot => AppendDot(CancelButtonBgColor);
/// <summary>
///
/// </summary>
public static string AnimationDot => AppendDot(Animation);
/// <summary>
///
/// </summary>
public static string Str1924Dot => AppendDot(Str1924);
/// <summary>
///
/// </summary>
public static string Str1926Dot => AppendDot(Str1926);
/// <summary>
///
/// </summary>
public static string Str1938Dot => AppendDot(Str1938);
/// <summary>
///
/// </summary>
public static string LabelsFormatIntradayDescDot => AppendDot(LabelsFormatIntradayDesc);
/// <summary>
///
/// </summary>
public static string TemporaryFilesDot => AppendDot(TemporaryFiles);
/// <summary>
///
/// </summary>
public static string LoginDot => AppendDot(Login);
/// <summary>
///
/// </summary>
public static string PasswordDot => AppendDot(Password);
/// <summary>
///
/// </summary>
public static string Str3304Dot => AppendDot(Str3304);
/// <summary>
///
/// </summary>
public static string AddressDot => AppendDot(Address);
/// <summary>
///
/// </summary>
public static string PinDot => AppendDot(Pin);
/// <summary>
///
/// </summary>
public static string Str3451Dot => AppendDot(Str3451);
/// <summary>
///
/// </summary>
public static string ServerAddressDot => AppendDot(ServerAddress);
/// <summary>
///
/// </summary>
public static string Str2121Dot => AppendDot(Str2121);
/// <summary>
///
/// </summary>
public static string Str1197Dot => AppendDot(Str1197);
/// <summary>
///
/// </summary>
public static string Str3412Dot => AppendDot(Str3412);
/// <summary>
///
/// </summary>
public static string MainUDPDot => AppendDot(MainUDP);
/// <summary>
///
/// </summary>
public static string DuplicateUDPDot => AppendDot(DuplicateUDP);
/// <summary>
///
/// </summary>
public static string RecoveryServerDot => AppendDot(RecoveryServer);
/// <summary>
///
/// </summary>
public static string ReplayServerDot => AppendDot(ReplayServer);
/// <summary>
///
/// </summary>
public static string Str2137Dot => AppendDot(Str2137);
/// <summary>
///
/// </summary>
public static string GroupIdDot => AppendDot(GroupId);
/// <summary>
///
/// </summary>
public static string Str3131Dot => AppendDot(Str3131);
/// <summary>
///
/// </summary>
public static string OrderLogBuilderDot => AppendDot(OrderLogBuilder);
/// <summary>
///
/// </summary>
public static string Str3427Dot => AppendDot(Str3427);
/// <summary>
///
/// </summary>
public static string Str1405Dot => AppendDot(Str1405);
/// <summary>
///
/// </summary>
public static string PnLDot => AppendDot(PnL);
/// <summary>
///
/// </summary>
public static string Str862Dot => AppendDot(Str862);
/// <summary>
///
/// </summary>
public static string SecurityIdDot => AppendDot(SecurityId);
/// <summary>
///
/// </summary>
public static string Str349Dot => AppendDot(Str349);
/// <summary>
///
/// </summary>
public static string BestPairDot => AppendDot(BestPair);
/// <summary>
///
/// </summary>
public static string Str293Dot => AppendDot(Str293);
/// <summary>
///
/// </summary>
public static string Str299Dot => AppendDot(Str299);
/// <summary>
///
/// </summary>
public static string Str232Dot => AppendDot(Str232);
/// <summary>
///
/// </summary>
public static string Str321Dot => AppendDot(Str321);
/// <summary>
///
/// </summary>
public static string AveragePriceDot => AppendDot(AveragePrice);
/// <summary>
///
/// </summary>
public static string Str9Dot => AppendDot(Str9);
/// <summary>
///
/// </summary>
public static string Str345Dot => AppendDot(Str345);
/// <summary>
///
/// </summary>
public static string Str2223Dot => AppendDot(Str2223);
/// <summary>
///
/// </summary>
public static string Str2235Dot => AppendDot(Str2235);
/// <summary>
///
/// </summary>
public static string TimeZoneDot => AppendDot(TimeZone);
/// <summary>
///
/// </summary>
public static string Str2237Dot => AppendDot(Str2237);
/// <summary>
///
/// </summary>
public static string SecurityDot => AppendDot(Security);
/// <summary>
///
/// </summary>
public static string VersionDot => AppendDot(Version);
/// <summary>
///
/// </summary>
public static string TemplateDot => AppendDot(Template);
/// <summary>
///
/// </summary>
public static string CsvHeaderDot => AppendDot(CsvHeader);
/// <summary>
///
/// </summary>
public static string Str3526Dot => AppendDot(Str3526);
/// <summary>
///
/// </summary>
public static string Str135Dot => AppendDot(Str135);
/// <summary>
///
/// </summary>
public static string Str1864Dot => AppendDot(Str1864);
/// <summary>
///
/// </summary>
public static string Str2572TrailingDelta => Str2572.Put(TrailingDelta);
/// <summary>
///
/// </summary>
public static string Str2577TrailingReferencePrice => Str2572.Put(TrailingReferencePrice);
/// <summary>
///
/// </summary>
public static string Str3423Dot => AppendDot(Str3423);
/// <summary>
///
/// </summary>
public static string FastSettingsDot => AppendDot(FastSettings);
/// <summary>
///
/// </summary>
public static string NewsDot => AppendDot(News);
/// <summary>
///
/// </summary>
public static string NewsSkrinDot => AppendDot(NewsSkrin);
/// <summary>
///
/// </summary>
public static string EnabledDot => AppendDot(Enabled);
/// <summary>
///
/// </summary>
public static string SettingsFileDot => AppendDot(SettingsFile);
/// <summary>
///
/// </summary>
public static string FondMarketDot => AppendDot(FondMarket);
/// <summary>
///
/// </summary>
public static string CurrencyMarketDot => AppendDot(CurrencyMarket);
/// <summary>
///
/// </summary>
public static string Str436Dot => AppendDot(Str436);
/// <summary>
///
/// </summary>
public static string OrdersDot => AppendDot(Orders);
/// <summary>
///
/// </summary>
public static string Str985Dot => AppendDot(Str985);
/// <summary>
///
/// </summary>
public static string SecuritiesDot => AppendDot(Securities);
/// <summary>
///
/// </summary>
public static string Str1324Dot => AppendDot(Str1324);
/// <summary>
///
/// </summary>
public static string CancelOnDisconnectDot => AppendDot(CancelOnDisconnect);
/// <summary>
///
/// </summary>
public static string TurnoverDot => AppendDot(Turnover);
/// <summary>
///
/// </summary>
public static string ResultTypeDot => AppendDot(ResultType);
/// <summary>
///
/// </summary>
public static string IssueSizeDot => AppendDot(IssueSize);
/// <summary>
///
/// </summary>
public static string IssueDateDot => AppendDot(IssueDate);
/// <summary>
///
/// </summary>
public static string UnderlyingSecurityTypeDot => AppendDot(UnderlyingSecurityType);
/// <summary>
///
/// </summary>
public static string PassphraseDot => AppendDot(Passphrase);
/// <summary>
///
/// </summary>
public static string MiddleLineDot => AppendDot(MiddleLine);
/// <summary>
///
/// </summary>
public static string UpperLineDot => AppendDot(UpperLine);
/// <summary>
///
/// </summary>
public static string LowerLineDot => AppendDot(LowerLine);
/// <summary>
///
/// </summary>
public static string PnFBoxSizeDot => AppendDot(PnFBoxSize);
/// <summary>
///
/// </summary>
public static string TrailingStopLossDot => AppendDot(TrailingStopLoss);
/// <summary>
///
/// </summary>
public static string Str261Dot => AppendDot(Str261);
/// <summary>
///
/// </summary>
public static string OrderFlagsDot => AppendDot(OrderFlags);
/// <summary>
///
/// </summary>
public static string Str3400Dot => AppendDot(Str3400);
/// <summary>
///
/// </summary>
public static string CryptoAddressDot => AppendDot(CryptoAddress);
/// <summary>
///
/// </summary>
public static string PaymentIdDot => AppendDot(PaymentId);
/// <summary>
///
/// </summary>
public static string IbanDot => AppendDot(Iban);
/// <summary>
///
/// </summary>
public static string WithdrawDot => AppendDot(Withdraw);
/// <summary>
///
/// </summary>
public static string WithdrawInfoDot => AppendDot(WithdrawInfo);
/// <summary>
///
/// </summary>
public static string CurrencyDot => AppendDot(Currency);
/// <summary>
///
/// </summary>
public static string CountryDot => AppendDot(Country);
/// <summary>
///
/// </summary>
public static string CityDot => AppendDot(City);
/// <summary>
///
/// </summary>
public static string PostalCodeDot => AppendDot(PostalCode);
/// <summary>
///
/// </summary>
public static string NameDot => AppendDot(Name);
/// <summary>
///
/// </summary>
public static string ChargeFeeDot => AppendDot(ChargeFee);
/// <summary>
///
/// </summary>
public static string SslCertificateDot => AppendDot(SslCertificate);
/// <summary>
///
/// </summary>
public static string StorageFormatDot => AppendDot(StorageFormat);
/// <summary>
///
/// </summary>
public static string OrderSideDot => AppendDot(OrderSide);
/// <summary>
///
/// </summary>
public static string Str3506Dot => AppendDot(Str3506);
/// <summary>
///
/// </summary>
public static string DateTimeFormatDot => AppendDot(DateTimeFormat);
/// <summary>
///
/// </summary>
public static string TimeFormatDot => AppendDot(TimeFormat);
/// <summary>
///
/// </summary>
public static string Str437Dot => AppendDot(Str437);
/// <summary>
///
/// </summary>
public static string TransactionIdDot => AppendDot(TransactionId);
/// <summary>
///
/// </summary>
public static string Str254Dot => AppendDot(Str254);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.Messaging.WebPubSub
{
/// <summary>
/// Azure Web PubSub Service Client.
/// </summary>
[CodeGenSuppress("WebPubSubServiceClient", typeof(string), typeof(Uri), typeof(WebPubSubServiceClientOptions))]
[CodeGenSuppress("SendToAll", typeof(RequestContent), typeof(IEnumerable<string>), typeof(RequestContext))]
[CodeGenSuppress("SendToAllAsync", typeof(RequestContent), typeof(IEnumerable<string>), typeof(RequestContext))]
[CodeGenSuppress("SendToConnection", typeof(string), typeof(RequestContent), typeof(RequestContext))]
[CodeGenSuppress("SendToConnectionAsync", typeof(string), typeof(RequestContent), typeof(RequestContext))]
[CodeGenSuppress("SendToGroup", typeof(string), typeof(RequestContent), typeof(IEnumerable<string>), typeof(RequestContext))]
[CodeGenSuppress("SendToGroupAsync", typeof(string), typeof(RequestContent), typeof(IEnumerable<string>), typeof(RequestContext))]
[CodeGenSuppress("SendToUser", typeof(string), typeof(RequestContent), typeof(RequestContext))]
[CodeGenSuppress("SendToUserAsync", typeof(string), typeof(RequestContent), typeof(RequestContext))]
[CodeGenSuppress("AddUserToGroup", typeof(string), typeof(string), typeof(RequestContext))]
[CodeGenSuppress("AddUserToGroupAsync", typeof(string), typeof(string), typeof(RequestContext))]
[CodeGenSuppress("RemoveUserFromGroup", typeof(string), typeof(string), typeof(RequestContext))]
[CodeGenSuppress("RemoveUserFromGroupAsync", typeof(string), typeof(string), typeof(RequestContext))]
public partial class WebPubSubServiceClient
{
private AzureKeyCredential _credential;
private TokenCredential _tokenCredential;
/// <summary>
/// The hub.
/// </summary>
public virtual string Hub => _hub;
/// <summary>
/// The service endpoint.
/// </summary>
public virtual Uri Endpoint { get; }
/// <summary> Initializes a new instance of WebPubSubServiceClient. </summary>
/// <param name="endpoint"> server parameter. </param>
/// <param name="hub"> Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. </param>
/// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
public WebPubSubServiceClient(Uri endpoint, string hub, AzureKeyCredential credential)
: this(endpoint, hub, credential, new WebPubSubServiceClientOptions())
{
}
/// <summary> Initializes a new instance of WebPubSubServiceClient. </summary>
/// <param name="endpoint"> server parameter. </param>
/// <param name="hub"> Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. </param>
/// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
/// <param name="options"> The options for configuring the client. </param>
public WebPubSubServiceClient(Uri endpoint, string hub, AzureKeyCredential credential, WebPubSubServiceClientOptions options)
: this(endpoint, hub, options)
{
Argument.AssertNotNull(credential, nameof(credential));
_credential = credential;
HttpPipelinePolicy[] perCallPolicies;
if (options.ReverseProxyEndpoint != null)
{
perCallPolicies = new HttpPipelinePolicy[] { new ReverseProxyPolicy(options.ReverseProxyEndpoint) };
}
else
{
perCallPolicies = Array.Empty<HttpPipelinePolicy>();
}
_pipeline = HttpPipelineBuilder.Build(
options,
perCallPolicies: perCallPolicies,
perRetryPolicies: new HttpPipelinePolicy[] { new WebPubSubAuthenticationPolicy(credential) },
new ResponseClassifier()
);
}
/// <summary> Initializes a new instance of WebPubSubServiceClient. </summary>
/// <param name="endpoint"> server parameter. </param>
/// <param name="hub"> Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. </param>
/// <param name="credential"> A token credential used to authenticate to an Azure Service. </param>
public WebPubSubServiceClient(Uri endpoint, string hub, TokenCredential credential)
: this(endpoint, hub, credential, new WebPubSubServiceClientOptions())
{
}
/// <summary> Initializes a new instance of WebPubSubServiceClient. </summary>
/// <param name="endpoint"> server parameter. </param>
/// <param name="hub"> Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. </param>
/// <param name="credential"> A token credential used to authenticate to an Azure Service. </param>
/// <param name="options"> The options for configuring the client. </param>
public WebPubSubServiceClient(Uri endpoint, string hub, TokenCredential credential, WebPubSubServiceClientOptions options)
: this(endpoint, hub, options)
{
Argument.AssertNotNull(credential, nameof(credential));
_tokenCredential = credential;
HttpPipelinePolicy[] perCallPolicies;
if (options.ReverseProxyEndpoint != null)
{
perCallPolicies = new HttpPipelinePolicy[] { new ReverseProxyPolicy(options.ReverseProxyEndpoint) };
}
else
{
perCallPolicies = Array.Empty<HttpPipelinePolicy>();
}
_pipeline = HttpPipelineBuilder.Build(
options,
perCallPolicies: perCallPolicies,
perRetryPolicies: new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(credential, WebPubSubServiceClientOptions.CredentialScopeName) },
new ResponseClassifier()
);
}
/// <summary>
/// Initializes a new instance of the <see cref="WebPubSubServiceClient"/>.
/// </summary>
/// <param name="connectionString">Connection string contains Endpoint and AccessKey.</param>
/// <param name="hub">Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore.</param>
public WebPubSubServiceClient(string connectionString, string hub) : this(ParseConnectionString(connectionString), hub)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebPubSubServiceClient"/>.
/// </summary>
/// <param name="connectionString">Connection string contains Endpoint and AccessKey.</param>
/// <param name="hub">Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore.</param>
/// <param name="options"></param>
public WebPubSubServiceClient(string connectionString, string hub, WebPubSubServiceClientOptions options) :
this(ParseConnectionString(connectionString), hub, options)
{
}
private WebPubSubServiceClient((Uri Endpoint, AzureKeyCredential Credential) parsedConnectionString, string hub) :
this(parsedConnectionString.Endpoint, hub, parsedConnectionString.Credential)
{
}
private WebPubSubServiceClient((Uri Endpoint, AzureKeyCredential Credential) parsedConnectionString, string hub, WebPubSubServiceClientOptions options) :
this(parsedConnectionString.Endpoint, hub, parsedConnectionString.Credential, options)
{
}
private WebPubSubServiceClient(Uri endpoint, string hub, WebPubSubServiceClientOptions options)
{
Argument.AssertNotNull(endpoint, nameof(endpoint));
Argument.AssertNotNull(hub, nameof(hub));
_hub = hub;
_endpoint = endpoint.AbsoluteUri;
Endpoint = endpoint;
options ??= new WebPubSubServiceClientOptions();
ClientDiagnostics = new ClientDiagnostics(options);
_apiVersion = options.Version;
}
/// <summary>Broadcast message to all the connected client connections.</summary>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual async Task<Response> SendToAllAsync(string content, ContentType contentType = default)
{
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return await SendToAllAsync(RequestContent.Create(content), contentType.ToString(), default, context: default).ConfigureAwait(false);
}
/// <summary>Broadcast message to all the connected client connections.</summary>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual Response SendToAll(string content, ContentType contentType = default)
{
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return SendToAll(RequestContent.Create(content), contentType, excluded: default, context: default);
}
/// <summary>
/// Send message to the specific user.
/// </summary>
/// <param name="userId">The user Id.</param>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual async Task<Response> SendToUserAsync(string userId, string content, ContentType contentType = default)
{
Argument.AssertNotNull(userId, nameof(userId));
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return await SendToUserAsync(userId, RequestContent.Create(content), contentType, context: default).ConfigureAwait(false);
}
/// <summary>
/// Send message to the specific user.
/// </summary>
/// <param name="userId">The user Id.</param>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual Response SendToUser(string userId, string content, ContentType contentType = default)
{
Argument.AssertNotNull(userId, nameof(userId));
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return SendToUser(userId, RequestContent.Create(content), contentType, context: default);
}
/// <summary>
/// Send message to the specific connection.
/// </summary>
/// <param name="connectionId">The connection Id.</param>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual async Task<Response> SendToConnectionAsync(string connectionId, string content, ContentType contentType = default)
{
Argument.AssertNotNull(connectionId, nameof(connectionId));
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return await SendToConnectionAsync(connectionId, RequestContent.Create(content), contentType, context: default).ConfigureAwait(false);
}
/// <summary>
/// Send message to the specific connection.
/// </summary>
/// <param name="connectionId">The connection Id.</param>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual Response SendToConnection(string connectionId, string content, ContentType contentType = default)
{
Argument.AssertNotNull(connectionId, nameof(connectionId));
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return SendToConnection(connectionId, RequestContent.Create(content), contentType, context: default);
}
/// <summary>
/// Send message to a group of connections.
/// </summary>
/// <param name="group">Target group name, which length should be greater than 0 and less than 1025.</param>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual async Task<Response> SendToGroupAsync(string group, string content, ContentType contentType = default)
{
Argument.AssertNotNull(group, nameof(group));
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return await SendToGroupAsync(group, RequestContent.Create(content), contentType, excluded : default, context: default).ConfigureAwait(false);
}
/// <summary>
/// Send message to a group of connections.
/// </summary>
/// <param name="group">Target group name, which length should be greater than 0 and less than 1025.</param>
/// <param name="content"></param>
/// <param name="contentType">Defaults to ContentType.PlainText.</param>
/// <returns>A <see cref="Response"/> if successful.</returns>
public virtual Response SendToGroup(string group, string content, ContentType contentType = default)
{
Argument.AssertNotNull(group, nameof(group));
Argument.AssertNotNull(content, nameof(content));
if (contentType == default) contentType = ContentType.TextPlain;
return SendToGroup(group, RequestContent.Create(content), contentType, excluded: default, context: default);
}
/// <summary> Check if there are any client connections inside the given group. </summary>
/// <param name="group"> Target group name, which length should be greater than 0 and less than 1025. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual async Task<Response<bool>> GroupExistsAsync(string group, RequestContext context = default)
{
var response = await GroupExistsImplAsync(group, context).ConfigureAwait(false);
return Response.FromValue(response.Status == 200, response);
}
/// <summary> Check if there are any client connections inside the given group. </summary>
/// <param name="group"> Target group name, which length should be greater than 0 and less than 1025. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual Response<bool> GroupExists(string group, RequestContext context = default)
{
var response = GroupExistsImpl(group, context);
return Response.FromValue(response.Status == 200, response);
}
/// <summary> Check if there are any client connections connected for the given user. </summary>
/// <param name="userId"> Target user Id. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual async Task<Response<bool>> UserExistsAsync(string userId, RequestContext context = default)
{
var response = await UserExistsImplAsync(userId, context).ConfigureAwait(false);
return Response.FromValue(response.Status == 200, response);
}
/// <summary> Check if there are any client connections connected for the given user. </summary>
/// <param name="userId"> Target user Id. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual Response<bool> UserExists(string userId, RequestContext context = default)
{
var response = UserExistsImpl(userId, context);
return Response.FromValue(response.Status == 200, response);
}
/// <summary> Check if the connection with the given connectionId exists. </summary>
/// <param name="connectionId"> The connection Id. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual async Task<Response<bool>> ConnectionExistsAsync(string connectionId, RequestContext context = default)
{
var response = await ConnectionExistsImplAsync(connectionId, context).ConfigureAwait(false);
return Response.FromValue(response.Status == 200, response);
}
/// <summary> Check if the connection with the given connectionId exists. </summary>
/// <param name="connectionId"> The connection Id. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual Response<bool> ConnectionExists(string connectionId, RequestContext context = default)
{
var response = ConnectionExistsImpl(connectionId, context);
return Response.FromValue(response.Status == 200, response);
}
/// <summary> Grant permission to the connection. </summary>
/// <param name="permission"> The permission: current supported actions are joinLeaveGroup and sendToGroup. </param>
/// <param name="connectionId"> Target connection Id. </param>
/// <param name="targetName"> Optional. If not set, grant the permission to all the targets. If set, grant the permission to the specific target. The meaning of the target depends on the specific permission. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual async Task<Response> GrantPermissionAsync(WebPubSubPermission permission, string connectionId, string targetName = null, RequestContext context = default)
{
var response = await GrantPermissionAsync(PermissionToString(permission), connectionId, targetName, context).ConfigureAwait(false);
return response;
}
/// <summary> Grant permission to the connection. </summary>
/// <param name="permission"> The permission: current supported actions are joinLeaveGroup and sendToGroup. </param>
/// <param name="connectionId"> Target connection Id. </param>
/// <param name="targetName"> Optional. If not set, grant the permission to all the targets. If set, grant the permission to the specific target. The meaning of the target depends on the specific permission. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual Response GrantPermission(WebPubSubPermission permission, string connectionId, string targetName = null, RequestContext context = default)
{
var response = GrantPermission(PermissionToString(permission), connectionId, targetName, context);
return response;
}
/// <summary> Revoke permission for the connection. </summary>
/// <param name="permission"> The permission: current supported actions are joinLeaveGroup and sendToGroup. </param>
/// <param name="connectionId"> Target connection Id. </param>
/// <param name="targetName"> Optional. If not set, revoke the permission for all targets. If set, revoke the permission for the specific target. The meaning of the target depends on the specific permission. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual async Task<Response> RevokePermissionAsync(WebPubSubPermission permission, string connectionId, string targetName = null, RequestContext context = default)
{
var response = await RevokePermissionAsync(PermissionToString(permission), connectionId, targetName, context).ConfigureAwait(false);
return response;
}
/// <summary> Revoke permission for the connection. </summary>
/// <param name="permission"> The permission: current supported actions are joinLeaveGroup and sendToGroup. </param>
/// <param name="connectionId"> Target connection Id. </param>
/// <param name="targetName"> Optional. If not set, revoke the permission for all targets. If set, revoke the permission for the specific target. The meaning of the target depends on the specific permission. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual Response RevokePermission(WebPubSubPermission permission, string connectionId, string targetName = null, RequestContext context = default)
{
var response = RevokePermission(PermissionToString(permission), connectionId, targetName, context);
return response;
}
/// <summary> Check if a connection has permission to the specified action. </summary>
/// <param name="permission"> The permission: current supported actions are joinLeaveGroup and sendToGroup. </param>
/// <param name="connectionId"> Target connection Id. </param>
/// <param name="targetName"> Optional. If not set, get the permission for all targets. If set, get the permission for the specific target. The meaning of the target depends on the specific permission. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual async Task<Response<bool>> CheckPermissionAsync(WebPubSubPermission permission, string connectionId, string targetName = null, RequestContext context = default)
{
var response = await CheckPermissionAsync(PermissionToString(permission), connectionId, targetName, context).ConfigureAwait(false);
return Response.FromValue((response.Status == 200), response);
}
/// <summary> Check if a connection has permission to the specified action. </summary>
/// <param name="permission"> The permission: current supported actions are joinLeaveGroup and sendToGroup. </param>
/// <param name="connectionId"> Target connection Id. </param>
/// <param name="targetName"> Optional. If not set, get the permission for all targets. If set, get the permission for the specific target. The meaning of the target depends on the specific permission. </param>
/// <param name="context">Options specifying the cancellation token, controlling error reporting, etc.</param>
public virtual Response<bool> CheckPermission(WebPubSubPermission permission, string connectionId, string targetName = null, RequestContext context = default)
{
var response = CheckPermission(PermissionToString(permission), connectionId, targetName, context);
return Response.FromValue((response.Status == 200), response);
}
/// <summary> Add a user to the target group. </summary>
/// <param name="userId"> Target user Id. </param>
/// <param name="group"> Target group name, which length should be greater than 0 and less than 1025. </param>
/// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param>
/// <exception cref="ArgumentNullException"> <paramref name="userId"/> or <paramref name="group"/> is null. </exception>
/// <remarks>
/// Schema for <c>Response Error</c>:
/// <code>{
/// code: string,
/// message: string,
/// target: string,
/// details: [ErrorDetail],
/// inner: {
/// code: string,
/// inner: InnerError
/// }
/// }
/// </code>
/// </remarks>
#pragma warning disable AZC0002
public virtual async Task<Response> AddUserToGroupAsync(string group, string userId, RequestContext context = null)
#pragma warning restore AZC0002
{
using var scope = ClientDiagnostics.CreateScope("WebPubSubServiceClient.AddUserToGroup");
scope.Start();
try
{
using HttpMessage message = CreateAddUserToGroupRequest(userId, group, context);
return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Add a user to the target group. </summary>
/// <param name="userId"> Target user Id. </param>
/// <param name="group"> Target group name, which length should be greater than 0 and less than 1025. </param>
/// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param>
/// <exception cref="ArgumentNullException"> <paramref name="userId"/> or <paramref name="group"/> is null. </exception>
/// <remarks>
/// Schema for <c>Response Error</c>:
/// <code>{
/// code: string,
/// message: string,
/// target: string,
/// details: [ErrorDetail],
/// inner: {
/// code: string,
/// inner: InnerError
/// }
/// }
/// </code>
/// </remarks>
#pragma warning disable AZC0002
public virtual Response AddUserToGroup(string group, string userId, RequestContext context = null)
#pragma warning restore AZC0002
{
using var scope = ClientDiagnostics.CreateScope("WebPubSubServiceClient.AddUserToGroup");
scope.Start();
try
{
using HttpMessage message = CreateAddUserToGroupRequest(userId, group, context);
return _pipeline.ProcessMessage(message, context);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Remove a user from the target group. </summary>
/// <param name="userId"> Target user Id. </param>
/// <param name="group"> Target group name, which length should be greater than 0 and less than 1025. </param>
/// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param>
/// <exception cref="ArgumentNullException"> <paramref name="userId"/> or <paramref name="group"/> is null. </exception>
/// <remarks>
/// Schema for <c>Response Error</c>:
/// <code>{
/// code: string,
/// message: string,
/// target: string,
/// details: [ErrorDetail],
/// inner: {
/// code: string,
/// inner: InnerError
/// }
/// }
/// </code>
/// </remarks>
#pragma warning disable AZC0002
public virtual async Task<Response> RemoveUserFromGroupAsync(string group, string userId, RequestContext context = null)
#pragma warning restore AZC0002
{
using var scope = ClientDiagnostics.CreateScope("WebPubSubServiceClient.RemoveUserFromGroup");
scope.Start();
try
{
using HttpMessage message = CreateRemoveUserFromGroupRequest(userId, group, context);
return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Remove a user from the target group. </summary>
/// <param name="userId"> Target user Id. </param>
/// <param name="group"> Target group name, which length should be greater than 0 and less than 1025. </param>
/// <param name="context"> The request context, which can override default behaviors on the request on a per-call basis. </param>
/// <exception cref="ArgumentNullException"> <paramref name="userId"/> or <paramref name="group"/> is null. </exception>
/// <remarks>
/// Schema for <c>Response Error</c>:
/// <code>{
/// code: string,
/// message: string,
/// target: string,
/// details: [ErrorDetail],
/// inner: {
/// code: string,
/// inner: InnerError
/// }
/// }
/// </code>
/// </remarks>
#pragma warning disable AZC0002
public virtual Response RemoveUserFromGroup(string group, string userId, RequestContext context = null)
#pragma warning restore AZC0002
{
using var scope = ClientDiagnostics.CreateScope("WebPubSubServiceClient.RemoveUserFromGroup");
scope.Start();
try
{
using HttpMessage message = CreateRemoveUserFromGroupRequest(userId, group, context);
return _pipeline.ProcessMessage(message, context);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a control expression that handles multiple selections by passing control to a <see cref="SwitchCase"/>.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.SwitchExpressionProxy))]
public sealed class SwitchExpression : Expression
{
private readonly Type _type;
private readonly Expression _switchValue;
private readonly ReadOnlyCollection<SwitchCase> _cases;
private readonly Expression _defaultBody;
private readonly MethodInfo _comparison;
internal SwitchExpression(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, ReadOnlyCollection<SwitchCase> cases)
{
_type = type;
_switchValue = switchValue;
_defaultBody = defaultBody;
_comparison = comparison;
_cases = cases;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents.
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _type; }
}
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Switch; }
}
/// <summary>
/// Gets the test for the switch.
/// </summary>
public Expression SwitchValue
{
get { return _switchValue; }
}
/// <summary>
/// Gets the collection of <see cref="SwitchCase"/> objects for the switch.
/// </summary>
public ReadOnlyCollection<SwitchCase> Cases
{
get { return _cases; }
}
/// <summary>
/// Gets the test for the switch.
/// </summary>
public Expression DefaultBody
{
get { return _defaultBody; }
}
/// <summary>
/// Gets the equality comparison method, if any.
/// </summary>
public MethodInfo Comparison
{
get { return _comparison; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitSwitch(this);
}
internal bool IsLifted
{
get
{
if (_switchValue.Type.IsNullableType())
{
return (_comparison == null) ||
!TypeUtils.AreEquivalent(_switchValue.Type, _comparison.GetParametersCached()[0].ParameterType.GetNonRefType());
}
return false;
}
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="switchValue">The <see cref="SwitchValue" /> property of the result.</param>
/// <param name="cases">The <see cref="Cases" /> property of the result.</param>
/// <param name="defaultBody">The <see cref="DefaultBody" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public SwitchExpression Update(Expression switchValue, IEnumerable<SwitchCase> cases, Expression defaultBody)
{
if (switchValue == SwitchValue && cases == Cases && defaultBody == DefaultBody)
{
return this;
}
return Expression.Switch(Type, switchValue, defaultBody, Comparison, cases);
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, params SwitchCase[] cases)
{
return Switch(switchValue, null, null, (IEnumerable<SwitchCase>)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, params SwitchCase[] cases)
{
return Switch(switchValue, defaultBody, null, (IEnumerable<SwitchCase>)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases)
{
return Switch(switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="type">The result type of the switch.</param>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases)
{
return Switch(type, switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases)
{
return Switch(null, switchValue, defaultBody, comparison, cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="type">The result type of the switch.</param>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases)
{
RequiresCanRead(switchValue, nameof(switchValue));
if (switchValue.Type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid(nameof(switchValue));
var caseList = cases.ToReadOnly();
ContractUtils.RequiresNotNullItems(caseList, nameof(cases));
// Type of the result. Either provided, or it is type of the branches.
Type resultType;
if (type != null)
resultType = type;
else if (caseList.Count != 0)
resultType = caseList[0].Body.Type;
else if (defaultBody != null)
resultType = defaultBody.Type;
else
resultType = typeof(void);
bool customType = type != null;
if (comparison != null)
{
var pms = comparison.GetParametersCached();
if (pms.Length != 2)
{
throw Error.IncorrectNumberOfMethodCallArguments(comparison, nameof(comparison));
}
// Validate that the switch value's type matches the comparison method's
// left hand side parameter type.
var leftParam = pms[0];
bool liftedCall = false;
if (!ParameterIsAssignable(leftParam, switchValue.Type))
{
liftedCall = ParameterIsAssignable(leftParam, switchValue.Type.GetNonNullableType());
if (!liftedCall)
{
throw Error.SwitchValueTypeDoesNotMatchComparisonMethodParameter(switchValue.Type, leftParam.ParameterType);
}
}
var rightParam = pms[1];
foreach (var c in caseList)
{
ContractUtils.RequiresNotNull(c, nameof(cases));
ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases));
for (int i = 0; i < c.TestValues.Count; i++)
{
// When a comparison method is provided, test values can have different type but have to
// be reference assignable to the right hand side parameter of the method.
Type rightOperandType = c.TestValues[i].Type;
if (liftedCall)
{
if (!rightOperandType.IsNullableType())
{
throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType);
}
rightOperandType = rightOperandType.GetNonNullableType();
}
if (!ParameterIsAssignable(rightParam, rightOperandType))
{
throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType);
}
}
}
// if we have a non-boolean user-defined equals, we don't want it.
if (comparison.ReturnType != typeof(bool))
{
throw Error.EqualityMustReturnBoolean(comparison, nameof(comparison));
}
}
else if (caseList.Count != 0)
{
// When comparison method is not present, all the test values must have
// the same type. Use the first test value's type as the baseline.
var firstTestValue = caseList[0].TestValues[0];
foreach (var c in caseList)
{
ContractUtils.RequiresNotNull(c, nameof(cases));
ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases));
// When no comparison method is provided, require all test values to have the same type.
for (int i = 0; i < c.TestValues.Count; i++)
{
if (!TypeUtils.AreEquivalent(firstTestValue.Type, c.TestValues[i].Type))
{
throw new ArgumentException(Strings.AllTestValuesMustHaveSameType, nameof(cases));
}
}
}
// Now we need to validate that switchValue.Type and testValueType
// make sense in an Equal node. Fortunately, Equal throws a
// reasonable error, so just call it.
var equal = Equal(switchValue, firstTestValue, false, comparison);
// Get the comparison function from equals node.
comparison = equal.Method;
}
if (defaultBody == null)
{
if (resultType != typeof(void)) throw Error.DefaultBodyMustBeSupplied(nameof(defaultBody));
}
else
{
ValidateSwitchCaseType(defaultBody, customType, resultType, nameof(defaultBody));
}
return new SwitchExpression(resultType, switchValue, defaultBody, comparison, caseList);
}
/// <summary>
/// If custom type is provided, all branches must be reference assignable to the result type.
/// If no custom type is provided, all branches must have the same type - resultType.
/// </summary>
private static void ValidateSwitchCaseType(Expression @case, bool customType, Type resultType, string parameterName)
{
if (customType)
{
if (resultType != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(resultType, @case.Type))
{
throw new ArgumentException(Strings.ArgumentTypesMustMatch, parameterName);
}
}
}
else
{
if (!TypeUtils.AreEquivalent(resultType, @case.Type))
{
throw new ArgumentException(Strings.AllCaseBodiesMustHaveSameType, parameterName);
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CloudFileDataAdaptor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace DMLibTest
{
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.File;
using Microsoft.Azure.Storage.RetryPolicies;
using MS.Test.Common.MsTestLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
internal class CloudFileDataAdaptor : DataAdaptor<DMLibDataInfo>
{
private TestAccount testAccount;
public CloudFileHelper fileHelper;
private string tempFolder;
private readonly string defaultShareName;
private string shareName;
private DateTimeOffset? snapshotTime;
public override string StorageKey
{
get
{
return this.fileHelper.Account.Credentials.ExportBase64EncodedKey();
}
}
public CloudFileDataAdaptor(TestAccount testAccount, string shareName, SourceOrDest sourceOrDest)
{
this.testAccount = testAccount;
this.fileHelper = new CloudFileHelper(testAccount.Account);
this.shareName = shareName;
this.defaultShareName = shareName;
this.tempFolder = Guid.NewGuid().ToString();
this.SourceOrDest = sourceOrDest;
this.snapshotTime = null;
}
public string ShareName
{
get
{
return this.shareName;
}
set
{
this.shareName = value;
}
}
public CloudFileHelper FileHelper
{
get
{
return this.fileHelper;
}
private set
{
this.fileHelper = value;
}
}
public CloudFileShare GetBaseShare()
{
return fileHelper.FileClient.GetShareReference(ShareName);
}
public override object GetTransferObject(string rootPath, FileNode fileNode, StorageCredentials credentials = null)
{
return this.GetCloudFileReference(rootPath, fileNode, credentials);
}
public override object GetTransferObject(string rootPath, DirNode dirNode, StorageCredentials credentials = null)
{
return this.GetCloudFileDirReference(rootPath, dirNode, credentials);
}
public override string GetAddress(params string[] list)
{
StringBuilder builder = new StringBuilder();
builder.Append(this.testAccount.GetEndpointBaseUri(EndpointType.File) + "/" + this.shareName + "/");
foreach (string token in list)
{
if (!string.IsNullOrEmpty(token))
{
builder.Append(token);
builder.Append("/");
}
}
return builder.ToString();
}
public override string GetSecondaryAddress(params string[] list)
{
throw new NotSupportedException("GetSecondaryAddress is not supported in CloudFileDataAdaptor.");
}
public override void CreateIfNotExists()
{
this.fileHelper.CreateShare(this.shareName);
snapshotTime = null;
}
public override bool Exists()
{
return this.fileHelper.Exists(this.shareName);
}
public override void WaitForGEO()
{
throw new NotSupportedException("WaitForGEO is not supported in CloudFileDataAdaptor.");
}
public override void ValidateMD5ByDownloading(object file)
{
((CloudFile)file).DownloadToStream(Stream.Null, null, new FileRequestOptions()
{
RetryPolicy = DMLibTestConstants.DefaultRetryPolicy,
DisableContentMD5Validation = false,
UseTransactionalMD5 = true,
MaximumExecutionTime = DMLibTestConstants.DefaultExecutionTimeOut,
});
}
public string MountFileShare()
{
this.fileHelper.CreateShare(this.shareName);
CloudFileShare share = this.fileHelper.FileClient.GetShareReference(this.shareName);
string cmd = "net";
string args = string.Format(
"use * {0} {1} /USER:{2}",
string.Format(@"\\{0}\{1}", share.Uri.Host, this.shareName),
this.fileHelper.Account.Credentials.ExportBase64EncodedKey(),
this.fileHelper.Account.Credentials.AccountName);
string stdout, stderr;
int ret = TestHelper.RunCmd(cmd, args, out stdout, out stderr);
Test.Assert(0 == ret, "mounted to xsmb share successfully");
Test.Info("stdout={0}, stderr={1}", stdout, stderr);
Regex r = new Regex(@"Drive (\S+) is now connected to");
Match m = r.Match(stdout);
if (m.Success)
{
return m.Groups[1].Value;
}
else
{
return null;
}
}
public void UnmountFileShare(string deviceName)
{
string cmd = "net";
string args = string.Format("use {0} /DELETE", deviceName);
string stdout, stderr;
int ret = TestHelper.RunCmd(cmd, args, out stdout, out stderr);
Test.Assert(0 == ret, "unmounted {0} successfully", deviceName);
Test.Info("stdout={0}, stderr={1}", stdout, stderr);
}
public CloudFile GetCloudFileReference(string rootPath, FileNode fileNode, StorageCredentials credentials = null)
{
var share = this.fileHelper.FileClient.GetShareReference(this.shareName, snapshotTime);
if (credentials != null)
{
share = new CloudFileShare(share.SnapshotQualifiedStorageUri, credentials);
}
string fileName = fileNode.GetURLRelativePath();
if (fileName.StartsWith("/"))
{
fileName = fileName.Substring(1, fileName.Length - 1);
}
if (!string.IsNullOrEmpty(rootPath))
{
fileName = rootPath + "/" + fileName;
}
return share.GetRootDirectoryReference().GetFileReference(fileName);
}
public CloudFileDirectory GetCloudFileDirReference(string rootPath, DirNode dirNode, StorageCredentials credentials = null)
{
var share = this.fileHelper.FileClient.GetShareReference(this.shareName, snapshotTime);
if (credentials != null)
{
share = new CloudFileShare(share.SnapshotQualifiedStorageUri, credentials);
}
string dirName = dirNode.GetURLRelativePath();
if (dirName.StartsWith("/"))
{
dirName = dirName.Substring(1, dirName.Length - 1);
}
if (!string.IsNullOrEmpty(rootPath))
{
dirName = rootPath + "/" + dirName;
}
if (string.IsNullOrEmpty(dirName))
{
return share.GetRootDirectoryReference();
}
else
{
return share.GetRootDirectoryReference().GetDirectoryReference(dirName);
}
}
protected override void GenerateDataImp(DMLibDataInfo dataInfo)
{
fileHelper.CreateShare(this.shareName);
using (TemporaryTestFolder localTemp = new TemporaryTestFolder(this.tempFolder))
{
CloudFileDirectory rootCloudFileDir = this.fileHelper.GetDirReference(this.shareName, dataInfo.RootPath);
this.GenerateDir(dataInfo.RootNode, rootCloudFileDir, this.tempFolder);
if (dataInfo.IsFileShareSnapshot)
{
CloudFileShare baseShare = this.fileHelper.FileClient.GetShareReference(this.shareName);
this.snapshotTime = baseShare.SnapshotAsync().Result.SnapshotTime;
CloudFileHelper.CleanupFileDirectory(baseShare.GetRootDirectoryReference());
}
}
}
private void GenerateDir(DirNode dirNode, CloudFileDirectory cloudFileDir, string parentPath)
{
string dirPath = Path.Combine(parentPath, dirNode.Name);
DMLibDataHelper.CreateLocalDirIfNotExists(dirPath);
cloudFileDir.CreateIfNotExists(HelperConst.DefaultFileOptions);
if (null != cloudFileDir.Parent)
{
if (null != dirNode.SMBAttributes)
{
cloudFileDir.Properties.NtfsAttributes = dirNode.SMBAttributes;
}
if (dirNode.CreationTime.HasValue) cloudFileDir.Properties.CreationTime = dirNode.CreationTime;
if (dirNode.LastWriteTime.HasValue) cloudFileDir.Properties.LastWriteTime = dirNode.LastWriteTime;
if (null != dirNode.PortableSDDL) cloudFileDir.FilePermission = dirNode.PortableSDDL;
cloudFileDir.SetProperties(HelperConst.DefaultFileOptions);
cloudFileDir.FetchAttributes(null, HelperConst.DefaultFileOptions);
dirNode.CreationTime = cloudFileDir.Properties.CreationTime;
dirNode.LastWriteTime = cloudFileDir.Properties.LastWriteTime;
if ((null != dirNode.Metadata)
&& (dirNode.Metadata.Count > 0))
{
cloudFileDir.Metadata.Clear();
foreach (var keyValuePair in dirNode.Metadata)
{
cloudFileDir.Metadata.Add(keyValuePair);
}
cloudFileDir.SetMetadata(null, HelperConst.DefaultFileOptions);
}
}
foreach (var subDir in dirNode.DirNodes)
{
CloudFileDirectory subCloudFileDir = cloudFileDir.GetDirectoryReference(subDir.Name);
this.GenerateDir(subDir, subCloudFileDir, dirPath);
}
foreach (var file in dirNode.FileNodes)
{
CloudFile cloudFile = cloudFileDir.GetFileReference(file.Name);
this.GenerateFile(file, cloudFile, dirPath);
}
}
private void CheckFileNode(FileNode fileNode)
{
if (fileNode.LastModifiedTime != null)
{
throw new InvalidOperationException("Can't set LastModifiedTime to cloud file");
}
if (fileNode.FileAttr != null)
{
throw new InvalidOperationException("Can't set file attribute to cloud file");
}
}
private void GenerateFile(FileNode fileNode, CloudFile cloudFile, string parentPath)
{
this.CheckFileNode(fileNode);
string tempFileName = Guid.NewGuid().ToString();
string localFilePath = Path.Combine(parentPath, tempFileName);
DMLibDataHelper.CreateLocalFile(fileNode, localFilePath);
FileRequestOptions storeMD5Options = new FileRequestOptions()
{
RetryPolicy = DMLibTestConstants.DefaultRetryPolicy,
StoreFileContentMD5 = true,
MaximumExecutionTime = DMLibTestConstants.DefaultExecutionTimeOut
};
cloudFile.UploadFromFile(localFilePath, options: storeMD5Options);
if (null != fileNode.MD5 ||
null != fileNode.ContentType ||
null != fileNode.CacheControl ||
null != fileNode.ContentDisposition ||
null != fileNode.ContentEncoding ||
null != fileNode.ContentLanguage)
{
// set user defined MD5 to cloud file
cloudFile.Properties.ContentMD5 = fileNode.MD5;
cloudFile.Properties.ContentType = fileNode.ContentType;
cloudFile.Properties.CacheControl = fileNode.CacheControl;
cloudFile.Properties.ContentDisposition = fileNode.ContentDisposition;
cloudFile.Properties.ContentEncoding = fileNode.ContentEncoding;
cloudFile.Properties.ContentLanguage = fileNode.ContentLanguage;
cloudFile.SetProperties(options: HelperConst.DefaultFileOptions);
}
if (null != fileNode.SMBAttributes)
{
cloudFile.Properties.NtfsAttributes = fileNode.SMBAttributes;
cloudFile.Properties.CreationTime = fileNode.CreationTime;
cloudFile.Properties.LastWriteTime = fileNode.LastWriteTime;
cloudFile.SetProperties(options: HelperConst.DefaultFileOptions);
}
if (null != fileNode.PortableSDDL)
{
cloudFile.FilePermission = fileNode.PortableSDDL;
cloudFile.SetProperties(options: HelperConst.DefaultFileOptions);
}
if (null != fileNode.Metadata && fileNode.Metadata.Count > 0)
{
cloudFile.Metadata.Clear();
foreach (var metaData in fileNode.Metadata)
{
cloudFile.Metadata.Add(metaData);
}
cloudFile.SetMetadata(options: HelperConst.DefaultFileOptions);
}
this.BuildFileNode(cloudFile, fileNode);
}
public override DMLibDataInfo GetTransferDataInfo(string rootDir)
{
CloudFileDirectory fileDir = fileHelper.QueryFileDirectory(this.shareName, rootDir);
if (fileDir == null)
{
return null;
}
DMLibDataInfo dataInfo = new DMLibDataInfo(rootDir);
this.BuildDirNode(fileDir, dataInfo.RootNode);
return dataInfo;
}
public override void Cleanup()
{
this.fileHelper.CleanupShare(this.shareName);
snapshotTime = null;
}
public override void DeleteLocation()
{
this.fileHelper.DeleteShare(this.shareName);
snapshotTime = null;
}
public override void MakePublic()
{
throw new NotSupportedException("MakePublic is not supported in CloudFileDataAdaptor.");
}
public override void Reset()
{
this.shareName = defaultShareName;
}
public override string GenerateSAS(SharedAccessPermissions sap, int validatePeriod, string policySignedIdentifier = null)
{
if (null == policySignedIdentifier)
{
if (this.SourceOrDest == SourceOrDest.Dest)
{
this.fileHelper.CreateShare(this.shareName);
}
return this.fileHelper.GetSASofShare(this.shareName, sap.ToFilePermissions(), validatePeriod, false);
}
else
{
this.fileHelper.CreateShare(this.shareName);
return this.fileHelper.GetSASofShare(this.shareName, sap.ToFilePermissions(), validatePeriod, true, policySignedIdentifier);
}
}
public override void RevokeSAS()
{
this.fileHelper.ClearSASPolicyofShare(this.shareName);
}
private void BuildDirNode(CloudFileDirectory cloudDir, DirNode dirNode)
{
cloudDir.FetchAttributes(options: HelperConst.DefaultFileOptions);
dirNode.LastWriteTime = cloudDir.Properties.LastWriteTime;
dirNode.CreationTime = cloudDir.Properties.CreationTime;
dirNode.SMBAttributes = cloudDir.Properties.NtfsAttributes;
if (!string.IsNullOrEmpty(cloudDir.FilePermission))
{
dirNode.PortableSDDL = cloudDir.FilePermission;
}
else if (!string.IsNullOrEmpty(cloudDir.Properties.FilePermissionKey))
{
dirNode.PortableSDDL = cloudDir.Share.GetFilePermission(cloudDir.Properties.FilePermissionKey, options: HelperConst.DefaultFileOptions);
}
if (cloudDir.Metadata.Count > 0)
{
dirNode.Metadata = new Dictionary<string, string>(cloudDir.Metadata);
}
foreach (IListFileItem item in cloudDir.ListFilesAndDirectories(HelperConst.DefaultFileOptions))
{
CloudFile cloudFile = item as CloudFile;
CloudFileDirectory subCloudDir = item as CloudFileDirectory;
if (cloudFile != null)
{
// Cannot fetch attributes while listing, so do it for each cloud file.
cloudFile.FetchAttributes(options: HelperConst.DefaultFileOptions);
FileNode fileNode = new FileNode(cloudFile.Name);
this.BuildFileNode(cloudFile, fileNode);
dirNode.AddFileNode(fileNode);
}
else if (subCloudDir != null)
{
DirNode subDirNode = new DirNode(subCloudDir.Name);
this.BuildDirNode(subCloudDir, subDirNode);
dirNode.AddDirNode(subDirNode);
}
}
}
private void BuildFileNode(CloudFile cloudFile, FileNode fileNode)
{
fileNode.SizeInByte = cloudFile.Properties.Length;
fileNode.MD5 = cloudFile.Properties.ContentMD5;
fileNode.ContentType = cloudFile.Properties.ContentType;
fileNode.CacheControl = cloudFile.Properties.CacheControl;
fileNode.ContentDisposition = cloudFile.Properties.ContentDisposition;
fileNode.ContentEncoding = cloudFile.Properties.ContentEncoding;
fileNode.ContentLanguage = cloudFile.Properties.ContentLanguage;
fileNode.Metadata = cloudFile.Metadata;
fileNode.LastWriteTime = cloudFile.Properties.LastWriteTime;
fileNode.CreationTime = cloudFile.Properties.CreationTime;
fileNode.SMBAttributes = cloudFile.Properties.NtfsAttributes;
if (!string.IsNullOrEmpty(cloudFile.FilePermission))
{
fileNode.PortableSDDL = cloudFile.FilePermission;
}
else if (!string.IsNullOrEmpty(cloudFile.Properties.FilePermissionKey))
{
fileNode.PortableSDDL = cloudFile.Share.GetFilePermission(cloudFile.Properties.FilePermissionKey, options: HelperConst.DefaultFileOptions);
}
DateTimeOffset dateTimeOffset = (DateTimeOffset)cloudFile.Properties.LastModified;
fileNode.LastModifiedTime = dateTimeOffset.UtcDateTime;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Gui;
using FlatRedBall;
#if FRB_XNA
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
#endif
namespace EditorObjects.Gui
{
public class CopyTexturesMultiButtonMessageBox : Window
{
#region Fields
private ListBox mListBox;
Texture2D mCopyLocallyTexture;
Texture2D mMakeRelativeTexture;
Button mSaveButton;
Button mCancelButton;
Button mCopyAllButton;
Button mMakeAllRelativeButton;
TextDisplay mTextDisplay;
string mText;
List<string> mFilesMarkedDotDotRelative = new List<string>();
#endregion
#region Properties
public List<string> FilesMarkedDotDotRelative
{
get { return mFilesMarkedDotDotRelative; }
set
{
mFilesMarkedDotDotRelative = value;
removeFilesAlreadyMarkedRelative();
}
}
private void removeFilesAlreadyMarkedRelative()
{
foreach (string s in mFilesMarkedDotDotRelative)
{
CollapseItem item = mListBox.GetItemByName(s);
if(item != null)
{
mListBox.Items.Remove(item);
}
}
}
public string Text
{
get { return mTextDisplay.Text; }
set
{
mText = value;
UpdateText();
}
}
public override float ScaleY
{
get
{
return base.ScaleY;
}
set
{
base.ScaleY = value;
}
}
#endregion
#region Events
public event GuiMessage SaveClick;
#endregion
#region Event Methods
void Save(Window callingWindow)
{
if (mFilesMarkedDotDotRelative != null)
{
foreach (CollapseItem item in mListBox.Items)
{
if (item.Icons[0].Texture == mMakeRelativeTexture)
{
mFilesMarkedDotDotRelative.Add(item.Text);
}
}
}
SaveClick(this);
GuiManager.RemoveWindow(this);
}
void CancelClick(IWindow callingWindow)
{
GuiManager.RemoveWindow(this);
}
#endregion
#region Methods
public CopyTexturesMultiButtonMessageBox()
: base(GuiManager.Cursor)
{
HasMoveBar = true;
HasCloseButton = true;
LoadTextures();
addRelativeToggleButton();
addTextDisplay();
addListBox();
addCopyAllButton();
addMakeAllRelativeButton();
addSaveButton();
addCancelButton();
ScaleY = 21;
ScaleX = 23;
GuiManager.BringToFront(this.mListBox);
ResizeBox();
this.Resizable = true;
this.Resizing += new GuiMessage(ResizingThis);
}
private void addMakeAllRelativeButton()
{
mMakeAllRelativeButton = new Button(mCursor);
this.AddWindow(mMakeAllRelativeButton);
mMakeAllRelativeButton.Text = "Make all relative with \"../\"";
mMakeAllRelativeButton.ScaleX = 11;
mMakeAllRelativeButton.ScaleY = 2;
mMakeAllRelativeButton.Click += new GuiMessage(MakeAllRelativeButtonClick);
}
private void addCopyAllButton()
{
mCopyAllButton = new Button(mCursor);
this.AddWindow(mCopyAllButton);
mCopyAllButton.Text = "Copy All Locally";
mCopyAllButton.ScaleX = 11;
mCopyAllButton.ScaleY = 2;
mCopyAllButton.Click += new GuiMessage(CopyAllButtonClick);
}
private void addTextDisplay()
{
mTextDisplay = new TextDisplay(mCursor);
AddWindow(mTextDisplay);
mTextDisplay.X = .5f;
mTextDisplay.Y = mRelativeToggle.ScaleY * 2 + mRelativeToggle.Y + 1;
}
private void addCancelButton()
{
mCancelButton = new Button(mCursor);
AddWindow(mCancelButton);
mCancelButton.ScaleX = 3;
mCancelButton.Text = "Cancel";
mCancelButton.X = mCancelButton.ScaleX + 2 * mSaveButton.ScaleX + 1;
mCancelButton.Click += CancelClick;
}
private void addSaveButton()
{
mSaveButton = new Button(mCursor);
AddWindow(mSaveButton);
mSaveButton.ScaleX = 3;
mSaveButton.Text = "Save";
mSaveButton.X = mSaveButton.ScaleX + .5f;
mSaveButton.Click += Save;
}
private void addListBox()
{
mListBox = new ListBox(mCursor);
AddWindow(mListBox);
mListBox.ScaleY = 7;
mListBox.DistanceBetweenLines = 2.5f;
}
ToggleButton mRelativeToggle = null;
public bool AreAssetsRelative { get { return mRelativeToggle.IsPressed; } }
private void addRelativeToggleButton()
{
mRelativeToggle = new ToggleButton(mCursor);
mRelativeToggle.Press();
mRelativeToggle.Push += mRelativeToggle_Push;
AddWindow(mRelativeToggle);
mRelativeToggle.Name = "scnRelativeAssets";
mRelativeToggle.SetText("Use absolute path", ".scnx relative assets");
mRelativeToggle.ScaleX = 9f;
mRelativeToggle.X = mRelativeToggle.ScaleX + 1;
mRelativeToggle.Y = 2f;
//Hide the relative toggle, disabling ability to make absolute; for simpicity and ease of use
mRelativeToggle.Visible = false;
mRelativeToggle.Y = 0;
}
void mRelativeToggle_Push(Window callingWindow)
{
//TODO: disable apropriate controls when toggle IsPressed == false
mTextDisplay.Enabled = AreAssetsRelative;
mListBox.Enabled = AreAssetsRelative;
mCopyAllButton.Enabled = AreAssetsRelative;
mMakeAllRelativeButton.Enabled = AreAssetsRelative;
}
void ResizingThis(Window callingWindow)
{
ResizeBox();
}
void MakeAllRelativeButtonClick(Window callingWindow)
{
foreach (CollapseItem item in mListBox.Items)
{
item.Icons[0].Texture = mMakeRelativeTexture;
}
}
void CopyAllButtonClick(Window callingWindow)
{
foreach (CollapseItem item in mListBox.Items)
{
item.Icons[0].Texture = mCopyLocallyTexture;
}
}
public int ItemsCount { get { return mListBox.Items.Count; } }
public CollapseItem AddItem(string fileName)
{
CollapseItem newItem = mListBox.AddItem(fileName);
ListBoxIcon icon = newItem.AddIcon(mCopyLocallyTexture, "ActionIcon");
icon.IconClick += new ListBoxFunction(IconClick);
icon.ScaleX = icon.ScaleY = 1.1f;
removeFilesAlreadyMarkedRelative();
return newItem;
}
void IconClick(CollapseItem collapseItem, ListBoxBase listBoxBase, ListBoxIcon listBoxIcon)
{
if (listBoxIcon.Texture == mCopyLocallyTexture)
{
listBoxIcon.Texture = mMakeRelativeTexture;
}
else
{
listBoxIcon.Texture = mCopyLocallyTexture;
}
}
protected void ResizeBox()
{
mSaveButton.X = mSaveButton.ScaleX + .5f;
mCancelButton.X = mCancelButton.ScaleX + 2 * mSaveButton.ScaleX + 1;
UpdateText();
if (mListBox != null)
{
mListBox.ScaleX = mScaleX - .5f;
mListBox.X = this.ScaleX;
}
mSaveButton.Y = this.ScaleY * 2 - mSaveButton.ScaleY - .5f;
mCancelButton.Y = this.ScaleY * 2 - mCancelButton.ScaleY - .5f;
mListBox.Y = mTextDisplay.Y + 16.5f;
mListBox.ScaleX = this.ScaleX - .5f;
mListBox.X = this.ScaleX;
mCopyAllButton.Y = this.ScaleY * 2 - 9;
mCopyAllButton.X = .5f + mCopyAllButton.ScaleX;
mMakeAllRelativeButton.Y = this.ScaleY * 2 - 5;
mMakeAllRelativeButton.X = mCopyAllButton.X;
}
private void UpdateText()
{
mTextDisplay.Text = mText;
mTextDisplay.Wrap(this.ScaleX * 2 - 1);
}
private void LoadTextures()
{
try
{
mCopyLocallyTexture = FlatRedBallServices.Load<Texture2D>(
"Content/CopyLocally.png", FlatRedBallServices.GlobalContentManager);
mMakeRelativeTexture = FlatRedBallServices.Load<Texture2D>(
"Content/MakeRelativeKeepInPlace.png", FlatRedBallServices.GlobalContentManager);
}
catch
{
throw new Exception(
"Could not find the textures for the CopyTexturesMessageBox. Someone on the FRB team must have forgotten to add these to the release tool.");
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Remote.Protocol;
using Avalonia.Remote.Protocol.Viewport;
using InputProtocol = Avalonia.Remote.Protocol.Input;
namespace Avalonia.DesignerSupport.Remote.HtmlTransport
{
public class HtmlWebSocketTransport : IAvaloniaRemoteTransportConnection
{
private readonly IAvaloniaRemoteTransportConnection _signalTransport;
private readonly SimpleWebSocketHttpServer _simpleServer;
private readonly Dictionary<string, byte[]> _resources;
private SimpleWebSocket _pendingSocket;
private bool _disposed;
private object _lock = new object();
private AutoResetEvent _wakeup = new AutoResetEvent(false);
private FrameMessage _lastFrameMessage = null;
private FrameMessage _lastSentFrameMessage = null;
private RequestViewportResizeMessage _lastViewportRequest;
private Action<IAvaloniaRemoteTransportConnection, object> _onMessage;
private Action<IAvaloniaRemoteTransportConnection, Exception> _onException;
private static readonly Dictionary<string, string> Mime = new Dictionary<string, string>
{
["html"] = "text/html", ["htm"] = "text/html", ["js"] = "text/javascript", ["css"] = "text/css"
};
private static readonly byte[] NotFound = Encoding.UTF8.GetBytes("404 - Not Found");
public HtmlWebSocketTransport(IAvaloniaRemoteTransportConnection signalTransport, Uri listenUri)
{
if (listenUri.Scheme != "http")
throw new ArgumentException("URI scheme is not HTTP.", nameof(listenUri));
var resourcePrefix = "Avalonia.DesignerSupport.Remote.HtmlTransport.webapp.build.";
_resources = typeof(HtmlWebSocketTransport).Assembly.GetManifestResourceNames()
.Where(r => r.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase)
&& r.EndsWith(".gz", StringComparison.OrdinalIgnoreCase))
.ToDictionary(
r => r.Substring(resourcePrefix.Length).Substring(0,r.Length-resourcePrefix.Length-3),
r =>
{
using (var s =
new GZipStream(typeof(HtmlWebSocketTransport).Assembly.GetManifestResourceStream(r),
CompressionMode.Decompress))
{
var ms = new MemoryStream();
s.CopyTo(ms);
return ms.ToArray();
}
});
_signalTransport = signalTransport;
var address = IPAddress.Parse(listenUri.Host);
_simpleServer = new SimpleWebSocketHttpServer(address, listenUri.Port);
_simpleServer.Listen();
Task.Run(AcceptWorker);
Task.Run(SocketWorker);
_signalTransport.Send(new HtmlTransportStartedMessage { Uri = "http://" + address + ":" + listenUri.Port + "/" });
}
async void AcceptWorker()
{
while (true)
{
using (var req = await _simpleServer.AcceptAsync())
{
if (!req.IsWebsocketRequest)
{
var key = req.Path == "/" ? "index.html" : req.Path.TrimStart('/').Replace('/', '.');
if (_resources.TryGetValue(key, out var data))
{
var ext = Path.GetExtension(key).Substring(1);
string mime = null;
if (ext == null || !Mime.TryGetValue(ext, out mime))
mime = "application/octet-stream";
await req.RespondAsync(200, data, mime);
}
else
{
await req.RespondAsync(404, NotFound, "text/plain");
}
}
else
{
var socket = await req.AcceptWebSocket();
SocketReceiveWorker(socket);
lock (_lock)
{
_pendingSocket?.Dispose();
_pendingSocket = socket;
}
}
}
}
}
async void SocketReceiveWorker(SimpleWebSocket socket)
{
try
{
while (true)
{
var msg = await socket.ReceiveMessage().ConfigureAwait(false);
if(msg != null && msg.IsText)
{
var message = ParseMessage(msg.AsString());
if (message != null)
_onMessage?.Invoke(this, message);
}
}
}
catch(Exception e)
{
Console.Error.WriteLine(e.ToString());
}
}
async void SocketWorker()
{
try
{
SimpleWebSocket socket = null;
while (true)
{
if (_disposed)
{
socket?.Dispose();
return;
}
FrameMessage sendNow = null;
lock (_lock)
{
if (_pendingSocket != null)
{
socket?.Dispose();
socket = _pendingSocket;
_pendingSocket = null;
_lastSentFrameMessage = null;
}
if (_lastFrameMessage != _lastSentFrameMessage)
_lastSentFrameMessage = sendNow = _lastFrameMessage;
}
if (sendNow != null && socket != null)
{
await socket.SendMessage(
$"frame:{sendNow.SequenceId}:{sendNow.Width}:{sendNow.Height}:{sendNow.Stride}:{sendNow.DpiX}:{sendNow.DpiY}");
await socket.SendMessage(false, sendNow.Data);
}
_wakeup.WaitOne(TimeSpan.FromSeconds(1));
}
}
catch(Exception e)
{
Console.Error.WriteLine(e.ToString());
}
}
public void Dispose()
{
_pendingSocket?.Dispose();
_simpleServer.Dispose();
}
public Task Send(object data)
{
if (data is FrameMessage frame)
{
_lastFrameMessage = frame;
_wakeup.Set();
return Task.CompletedTask;
}
if (data is RequestViewportResizeMessage req)
{
return Task.CompletedTask;
}
return _signalTransport.Send(data);
}
public void Start()
{
_onMessage?.Invoke(this, new Avalonia.Remote.Protocol.Viewport.ClientSupportedPixelFormatsMessage
{
Formats = new []{PixelFormat.Rgba8888}
});
_signalTransport.Start();
}
#region Forward
public event Action<IAvaloniaRemoteTransportConnection, object> OnMessage
{
add
{
bool subscribeToInner;
lock (_lock)
{
subscribeToInner = _onMessage == null;
_onMessage += value;
}
if (subscribeToInner)
_signalTransport.OnMessage += OnSignalTransportMessage;
}
remove
{
lock (_lock)
{
_onMessage -= value;
if (_onMessage == null)
_signalTransport.OnMessage -= OnSignalTransportMessage;
}
}
}
private void OnSignalTransportMessage(IAvaloniaRemoteTransportConnection signal, object message) => _onMessage?.Invoke(this, message);
public event Action<IAvaloniaRemoteTransportConnection, Exception> OnException
{
add
{
lock (_lock)
{
var subscribeToInner = _onException == null;
_onException += value;
if (subscribeToInner)
_signalTransport.OnException += OnSignalTransportException;
}
}
remove
{
lock (_lock)
{
_onException -= value;
if(_onException==null)
_signalTransport.OnException -= OnSignalTransportException;
}
}
}
private void OnSignalTransportException(IAvaloniaRemoteTransportConnection arg1, Exception ex)
{
_onException?.Invoke(this, ex);
}
#endregion
private static object ParseMessage(string message)
{
var parts = message.Split(':');
var key = parts[0];
if (key.Equals("frame-received", StringComparison.OrdinalIgnoreCase))
{
return new FrameReceivedMessage { SequenceId = long.Parse(parts[1]) };
}
else if (key.Equals("pointer-released", StringComparison.OrdinalIgnoreCase))
{
return new InputProtocol.PointerReleasedEventMessage
{
Modifiers = ParseInputModifiers(parts[1]),
X = ParseDouble(parts[2]),
Y = ParseDouble(parts[3]),
Button = ParseMouseButton(parts[4]),
};
}
else if (key.Equals("pointer-pressed", StringComparison.OrdinalIgnoreCase))
{
return new InputProtocol.PointerPressedEventMessage
{
Modifiers = ParseInputModifiers(parts[1]),
X = ParseDouble(parts[2]),
Y = ParseDouble(parts[3]),
Button = ParseMouseButton(parts[4]),
};
}
else if (key.Equals("pointer-moved", StringComparison.OrdinalIgnoreCase))
{
return new InputProtocol.PointerMovedEventMessage
{
Modifiers = ParseInputModifiers(parts[1]),
X = ParseDouble(parts[2]),
Y = ParseDouble(parts[3]),
};
}
else if (key.Equals("scroll", StringComparison.OrdinalIgnoreCase))
{
return new InputProtocol.ScrollEventMessage
{
Modifiers = ParseInputModifiers(parts[1]),
X = ParseDouble(parts[2]),
Y = ParseDouble(parts[3]),
DeltaX = ParseDouble(parts[4]),
DeltaY = ParseDouble(parts[5]),
};
}
return null;
}
private static InputProtocol.InputModifiers[] ParseInputModifiers(string modifiersText) =>
string.IsNullOrWhiteSpace(modifiersText)
? null
: modifiersText
.Split(',')
.Select(x => (InputProtocol.InputModifiers)Enum.Parse(
typeof(InputProtocol.InputModifiers), x, true))
.ToArray();
private static InputProtocol.MouseButton ParseMouseButton(string buttonText) =>
string.IsNullOrWhiteSpace(buttonText)
? InputProtocol.MouseButton.None
: (InputProtocol.MouseButton)Enum.Parse(
typeof(InputProtocol.MouseButton), buttonText, true);
private static double ParseDouble(string text) =>
double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using GitTools.IssueTrackers;
namespace GitReleaseNotes
{
public class SemanticReleaseNotes
{
//readonly Regex _issueRegex = new Regex(" - (?<Issue>.*?)(?<IssueLink> \\[(?<IssueId>.*?)\\]\\((?<IssueUrl>.*?)\\))*( *\\+(?<Tag>[^ \\+]*))*", RegexOptions.Compiled);
static readonly Regex ReleaseRegex = new Regex("# (?<Title>.*?)( \\((?<Date>.*?)\\))?$", RegexOptions.Compiled);
static readonly Regex LinkRegex = new Regex(@"\[(?<Text>.*?)\]\((?<Link>.*?)\)$", RegexOptions.Compiled);
readonly Categories categories;
public SemanticReleaseNotes()
{
categories = new Categories();
Releases = new SemanticRelease[0];
}
public SemanticReleaseNotes(IEnumerable<SemanticRelease> releaseNoteItems, Categories categories)
{
this.categories = categories;
Releases = releaseNoteItems.ToArray();
}
public SemanticRelease[] Releases { get; private set; }
public override string ToString()
{
var builder = new StringBuilder();
var index = 0;
foreach (var release in Releases)
{
if (release.ReleaseNoteLines.Count == 0)
{
continue;
}
if (index++ > 0)
{
builder.AppendLine();
builder.AppendLine();
}
if (Releases.Length > 1)
{
var hasBeenReleased = String.IsNullOrEmpty(release.ReleaseName);
if (hasBeenReleased)
{
builder.AppendLine("# vNext");
}
else if (release.When != null)
{
builder.AppendLine(string.Format("# {0} ({1:dd MMMM yyyy})", release.ReleaseName,
release.When.Value.Date));
}
else
{
builder.AppendLine(string.Format("# {0}", release.ReleaseName));
}
builder.AppendLine();
}
IEnumerable<IReleaseNoteLine> releaseNoteItems = release.ReleaseNoteLines;
foreach (var releaseNoteItem in releaseNoteItems)
{
builder.AppendLine(releaseNoteItem.ToString(categories));
}
builder.AppendLine();
if (string.IsNullOrEmpty(release.DiffInfo.DiffUrlFormat))
{
builder.AppendLine(string.Format("Commits: {0}...{1}", release.DiffInfo.BeginningSha, release.DiffInfo.EndSha));
}
else
{
builder.AppendLine(string.Format("Commits: [{0}...{1}]({2})",
release.DiffInfo.BeginningSha, release.DiffInfo.EndSha,
string.Format(release.DiffInfo.DiffUrlFormat, release.DiffInfo.BeginningSha, release.DiffInfo.EndSha)));
}
}
return builder.ToString();
}
public static SemanticReleaseNotes Parse(string releaseNotes)
{
var releases = new List<SemanticRelease>();
var lines = releaseNotes.Replace("\r", string.Empty).Split('\n');
var currentRelease = new SemanticRelease();
foreach (var line in lines)
{
if (line.TrimStart().StartsWith("# "))
{
var match = ReleaseRegex.Match(line);
if (line != lines.First())
{
releases.Add(currentRelease);
}
currentRelease = new SemanticRelease
{
ReleaseName = match.Groups["Title"].Value
};
if (currentRelease.ReleaseName == "vNext")
{
currentRelease.ReleaseName = null;
}
if (match.Groups["Date"].Success)
{
DateTime parsed;
var toParse = match.Groups["Date"].Value;
if (DateTime.TryParse(toParse, out parsed))
{
currentRelease.When = parsed;
}
if (DateTime.TryParseExact(toParse, "dd MMMM yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out parsed))
{
currentRelease.When = parsed;
}
else if (DateTime.TryParseExact(toParse, "MMMM dd, yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out parsed))
{
currentRelease.When = parsed;
}
else
{
// We failed to parse the date, just append to the end
currentRelease.ReleaseName += " (" + toParse + ")";
}
}
}
else if (line.StartsWith("Commits: "))
{
var commitText = line.Replace("Commits: ", string.Empty);
var linkMatch = LinkRegex.Match(commitText);
if (linkMatch.Success)
{
commitText = linkMatch.Groups["Text"].Value;
currentRelease.DiffInfo.DiffUrlFormat = linkMatch.Groups["Link"].Value;
}
var commits = commitText.Split(new[] { "..." }, StringSplitOptions.None);
currentRelease.DiffInfo.BeginningSha = commits[0];
currentRelease.DiffInfo.EndSha = commits[1];
}
else if (line.StartsWith(" - "))
{
// Improve this parsing to extract issue numbers etc
var title = line.StartsWith(" - ") ? line.Substring(3) : line;
var releaseNoteItem = new ReleaseNoteItem(title, null, null, null, currentRelease.When, new Contributor[0]);
currentRelease.ReleaseNoteLines.Add(releaseNoteItem);
}
else if (string.IsNullOrWhiteSpace(line))
{
currentRelease.ReleaseNoteLines.Add(new BlankLine());
}
else
{
// This picks up comments and such
var title = line.StartsWith(" - ") ? line.Substring(3) : line;
var releaseNoteItem = new ReleaseNoteLine(title);
currentRelease.ReleaseNoteLines.Add(releaseNoteItem);
}
}
releases.Add(currentRelease);
// Remove additional blank lines
foreach (var semanticRelease in releases)
{
for (int i = 0; i < semanticRelease.ReleaseNoteLines.Count; i++)
{
if (semanticRelease.ReleaseNoteLines[i] is BlankLine)
{
semanticRelease.ReleaseNoteLines.RemoveAt(i--);
}
else
{
break;
}
}
for (int i = semanticRelease.ReleaseNoteLines.Count - 1; i >= 0; i--)
{
if (semanticRelease.ReleaseNoteLines[i] is BlankLine)
{
semanticRelease.ReleaseNoteLines.RemoveAt(i);
}
else
{
break;
}
}
}
return new SemanticReleaseNotes(releases, new Categories());
}
public SemanticReleaseNotes Merge(SemanticReleaseNotes previousReleaseNotes)
{
var semanticReleases = previousReleaseNotes.Releases
.Where(r => Releases.All(r2 => r.ReleaseName != r2.ReleaseName))
.Select(CreateMergedSemanticRelease);
var enumerable = Releases.Select(CreateMergedSemanticRelease);
var mergedReleases =
enumerable
.Union(semanticReleases)
.ToArray();
foreach (var semanticRelease in mergedReleases)
{
var releaseFromThis = Releases.SingleOrDefault(r => r.ReleaseName == semanticRelease.ReleaseName);
var releaseFromPrevious = previousReleaseNotes.Releases.SingleOrDefault(r => r.ReleaseName == semanticRelease.ReleaseName);
if (releaseFromThis != null)
{
semanticRelease.ReleaseNoteLines.AddRange(releaseFromThis.ReleaseNoteLines);
}
if (releaseFromPrevious != null)
{
semanticRelease.ReleaseNoteLines.AddRange(releaseFromPrevious.ReleaseNoteLines);
}
}
return new SemanticReleaseNotes(mergedReleases, new Categories(categories.AvailableCategories.Union(previousReleaseNotes.categories.AvailableCategories).Distinct().ToArray(), categories.AllLabels));
}
private static SemanticRelease CreateMergedSemanticRelease(SemanticRelease r)
{
return new SemanticRelease(r.ReleaseName, r.When, r.DiffInfo);
}
}
}
| |
/*
* Copyright (C) 2012, 2013 OUYA, 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 UnityEngine;
public class OuyaShowUnityInput : MonoBehaviour,
OuyaSDK.IJoystickCalibrationListener,
OuyaSDK.IPauseListener, OuyaSDK.IResumeListener,
OuyaSDK.IMenuButtonUpListener,
OuyaSDK.IMenuAppearingListener
{
#region Model reference fields
public Material ControllerMaterial;
public MeshRenderer RendererAxisLeft = null;
public MeshRenderer RendererAxisRight = null;
public MeshRenderer RendererButtonA = null;
public MeshRenderer RendererButtonO = null;
public MeshRenderer RendererButtonU = null;
public MeshRenderer RendererButtonY = null;
public MeshRenderer RendererDpadDown = null;
public MeshRenderer RendererDpadLeft = null;
public MeshRenderer RendererDpadRight = null;
public MeshRenderer RendererDpadUp = null;
public MeshRenderer RendererLB = null;
public MeshRenderer RendererLT = null;
public MeshRenderer RendererRB = null;
public MeshRenderer RendererRT = null;
#endregion
private bool m_showCursor = true;
private bool m_inputToggle = true;
#region Thumbstick plots
public Camera ThumbstickPlotCamera = null;
#endregion
#region New Input API - in progress
private bool m_useSDKForInput = false;
#endregion
void Awake()
{
OuyaSDK.registerJoystickCalibrationListener(this);
OuyaSDK.registerMenuButtonUpListener(this);
OuyaSDK.registerMenuAppearingListener(this);
OuyaSDK.registerPauseListener(this);
OuyaSDK.registerResumeListener(this);
}
void OnDestroy()
{
OuyaSDK.unregisterJoystickCalibrationListener(this);
OuyaSDK.unregisterMenuButtonUpListener(this);
OuyaSDK.unregisterMenuAppearingListener(this);
OuyaSDK.unregisterPauseListener(this);
OuyaSDK.unregisterResumeListener(this);
}
private void Start()
{
UpdatePlayerButtons();
Input.ResetInputAxes();
}
public void SetPlayer1()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player1;
UpdatePlayerButtons();
}
public void SetPlayer2()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player2;
UpdatePlayerButtons();
}
public void SetPlayer3()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player3;
UpdatePlayerButtons();
}
public void SetPlayer4()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player4;
UpdatePlayerButtons();
}
public void SetPlayer5()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player5;
UpdatePlayerButtons();
}
public void SetPlayer6()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player6;
UpdatePlayerButtons();
}
public void SetPlayer7()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player7;
UpdatePlayerButtons();
}
public void SetPlayer8()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player8;
UpdatePlayerButtons();
}
public void OuyaMenuButtonUp()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
m_showCursor = !m_showCursor;
Debug.Log(string.Format("OuyaMenuButtonUp: m_showCursor: {0}", m_showCursor));
OuyaSDK.OuyaJava.JavaShowCursor(m_showCursor);
}
public void OuyaMenuAppearing()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
public void OuyaOnPause()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
public void OuyaOnResume()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
public void OuyaOnJoystickCalibration()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
#region Presentation
private void UpdateLabels()
{
try
{
OuyaNGUIHandler nguiHandler = GameObject.Find("_NGUIHandler").GetComponent<OuyaNGUIHandler>();
if (nguiHandler != null &&
null != OuyaSDK.Joysticks)
{
for (int i = 0; i < OuyaSDK.Joysticks.Length || i < 8; i++)
{
string joyName = "N/A";
if (i < OuyaSDK.Joysticks.Length)
{
joyName = OuyaSDK.Joysticks[i];
}
switch (i)
{
case 0:
nguiHandler.controller1.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player1 ? string.Format("*{0}", joyName) : joyName;
break;
case 1:
nguiHandler.controller2.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player2 ? string.Format("*{0}", joyName) : joyName;
break;
case 2:
nguiHandler.controller3.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player3 ? string.Format("*{0}", joyName) : joyName;
break;
case 3:
nguiHandler.controller4.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player4 ? string.Format("*{0}", joyName) : joyName;
break;
case 4:
nguiHandler.controller5.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player5 ? string.Format("*{0}", joyName) : joyName;
break;
case 5:
nguiHandler.controller6.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player6 ? string.Format("*{0}", joyName) : joyName;
break;
case 6:
nguiHandler.controller7.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player7 ? string.Format("*{0}", joyName) : joyName;
break;
case 7:
nguiHandler.controller8.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player8 ? string.Format("*{0}", joyName) : joyName;
break;
}
}
nguiHandler.button1.text = OuyaExampleCommon.GetButton(0, OuyaExampleCommon.Player).ToString();
nguiHandler.button2.text = OuyaExampleCommon.GetButton(1, OuyaExampleCommon.Player).ToString();
nguiHandler.button3.text = OuyaExampleCommon.GetButton(2, OuyaExampleCommon.Player).ToString();
nguiHandler.button4.text = OuyaExampleCommon.GetButton(3, OuyaExampleCommon.Player).ToString();
nguiHandler.button5.text = OuyaExampleCommon.GetButton(4, OuyaExampleCommon.Player).ToString();
nguiHandler.button6.text = OuyaExampleCommon.GetButton(5, OuyaExampleCommon.Player).ToString();
nguiHandler.button7.text = OuyaExampleCommon.GetButton(6, OuyaExampleCommon.Player).ToString();
nguiHandler.button8.text = OuyaExampleCommon.GetButton(7, OuyaExampleCommon.Player).ToString();
nguiHandler.button9.text = OuyaExampleCommon.GetButton(8, OuyaExampleCommon.Player).ToString();
nguiHandler.button10.text = OuyaExampleCommon.GetButton(9, OuyaExampleCommon.Player).ToString();
nguiHandler.button11.text = OuyaExampleCommon.GetButton(10, OuyaExampleCommon.Player).ToString();
nguiHandler.button12.text = OuyaExampleCommon.GetButton(11, OuyaExampleCommon.Player).ToString();
nguiHandler.button13.text = OuyaExampleCommon.GetButton(12, OuyaExampleCommon.Player).ToString();
nguiHandler.button14.text = OuyaExampleCommon.GetButton(13, OuyaExampleCommon.Player).ToString();
nguiHandler.button15.text = OuyaExampleCommon.GetButton(14, OuyaExampleCommon.Player).ToString();
nguiHandler.button16.text = OuyaExampleCommon.GetButton(15, OuyaExampleCommon.Player).ToString();
nguiHandler.button17.text = OuyaExampleCommon.GetButton(16, OuyaExampleCommon.Player).ToString();
nguiHandler.button18.text = OuyaExampleCommon.GetButton(17, OuyaExampleCommon.Player).ToString();
nguiHandler.button19.text = OuyaExampleCommon.GetButton(18, OuyaExampleCommon.Player).ToString();
nguiHandler.button20.text = OuyaExampleCommon.GetButton(19, OuyaExampleCommon.Player).ToString();
//nguiHandler.rawOut.text = OuyaGameObject.InputData;
nguiHandler.device.text = SystemInfo.deviceModel;
}
}
catch (System.Exception)
{
}
}
void Update()
{
OuyaNGUIHandler nguiHandler = GameObject.Find("_NGUIHandler").GetComponent<OuyaNGUIHandler>();
if (nguiHandler != null)
{
// Input.GetAxis("Joy1 Axis1");
nguiHandler.axis1.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 1", (int) OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis2.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 2", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis3.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 3", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis4.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 4", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis5.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 5", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis6.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 6", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis7.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 7", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis8.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 8", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis9.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 9", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis10.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 10", (int)OuyaExampleCommon.Player)).ToString("F5");
#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1
nguiHandler.axis11.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 11", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis12.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 12", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis13.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 13", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis14.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 14", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis15.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 15", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis16.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 16", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis17.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 17", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis18.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 18", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis19.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 19", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis20.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 20", (int)OuyaExampleCommon.Player)).ToString("F5");
#else
nguiHandler.axis11.text = "N/A";
nguiHandler.axis12.text = "N/A";
nguiHandler.axis13.text = "N/A";
nguiHandler.axis14.text = "N/A";
nguiHandler.axis15.text = "N/A";
nguiHandler.axis16.text = "N/A";
nguiHandler.axis17.text = "N/A";
nguiHandler.axis18.text = "N/A";
nguiHandler.axis19.text = "N/A";
nguiHandler.axis20.text = "N/A";
#endif
}
}
void FixedUpdate()
{
UpdateController();
UpdateLabels();
}
void OnGUI()
{
int x = 300;
for (int index = 1; index <= 4; ++index)
{
if (GUI.Button(new Rect(x, 60, 50, 30), string.Format("JOY{0}", index)))
{
OuyaExampleCommon.Player = (OuyaSDK.OuyaPlayer)index;
UpdatePlayerButtons();
}
x += 52;
}
x = 300;
for (int index = 5; index <= 8; ++index)
{
if (GUI.Button(new Rect(x, 100, 50, 30), string.Format("JOY{0}", index)))
{
OuyaExampleCommon.Player = (OuyaSDK.OuyaPlayer)index;
UpdatePlayerButtons();
}
x += 52;
}
if (GUI.Button(new Rect(300, 140, 200, 20), m_inputToggle ? "[Toggle Unity Input]" : "Toggle Unity Input"))
{
m_inputToggle = !m_inputToggle;
OuyaSDK.enableUnityInput(m_inputToggle);
}
/*
// prototyping
GUILayout.BeginHorizontal();
GUILayout.Space(600);
m_useSDKForInput = GUILayout.Toggle(m_useSDKForInput, "Use OuyaSDK Mappings and Unity Input", GUILayout.MinHeight(45));
GUILayout.EndHorizontal();
*/
}
void UpdatePlayerButtons()
{
if (ThumbstickPlotCamera)
{
foreach (OuyaPlotMeshThumbstick plot in ThumbstickPlotCamera.GetComponents<OuyaPlotMeshThumbstick>())
{
plot.Player = OuyaExampleCommon.Player;
}
}
OuyaNGUIHandler nguiHandler = GameObject.Find("_NGUIHandler").GetComponent<OuyaNGUIHandler>();
if (nguiHandler != null)
{
nguiHandler.player1.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player1);
nguiHandler.player2.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player2);
nguiHandler.player3.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player3);
nguiHandler.player4.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player4);
nguiHandler.player5.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player5);
nguiHandler.player6.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player6);
nguiHandler.player7.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player7);
nguiHandler.player8.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player8);
}
}
#endregion
#region Extra
private void UpdateHighlight(MeshRenderer mr, bool highlight, bool instant = false)
{
float time = Time.deltaTime * 10;
if (instant) { time = 1000; }
if (highlight)
{
Color c = new Color(0, 10, 0, 1);
mr.material.color = Color.Lerp(mr.material.color, c, time);
}
else
{
mr.material.color = Color.Lerp(mr.material.color, Color.white, time);
}
}
private float GetAxis(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
// Check if we want the *new* SDK input or the example common
if (m_useSDKForInput)
{
// Get the Unity Axis Name for the Unity API
string axisName = OuyaSDK.GetUnityAxisName(keyCode, player);
// Check if the axis name is valid
if (!string.IsNullOrEmpty(axisName))
{
//use the Unity API to get the axis value, raw or otherwise
float axisValue = Input.GetAxisRaw(axisName);
//check if the axis should be inverted
if (OuyaSDK.GetAxisInverted(keyCode, player))
{
return -axisValue;
}
else
{
return axisValue;
}
}
}
// moving the common code into the sdk via above
else
{
return OuyaExampleCommon.GetAxis(keyCode, player);
}
return 0f;
}
private bool GetButton(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
// Check if we want the *new* SDK input or the example common
if (m_useSDKForInput)
{
// Get the Unity KeyCode for the Unity API
KeyCode unityKeyCode = OuyaSDK.GetUnityKeyCode(keyCode, player);
// Check if the KeyCode is valid
if (unityKeyCode != (KeyCode)(-1))
{
//use the Unity API to get the button value
bool buttonState = Input.GetKey(unityKeyCode);
return buttonState;
}
}
// moving the common code into the sdk via aboveUs
else
{
return OuyaExampleCommon.GetButton(keyCode, player);
}
return false;
}
private void UpdateController()
{
#region Axis Code
UpdateHighlight(RendererAxisLeft, Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_X, OuyaExampleCommon.Player)) > 0.25f ||
Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_Y, OuyaExampleCommon.Player)) > 0.25f);
RendererAxisLeft.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_Y, OuyaExampleCommon.Player) * 15, 0, GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_X, OuyaExampleCommon.Player) * 15);
UpdateHighlight(RendererAxisRight, Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_X, OuyaExampleCommon.Player)) > 0.25f ||
Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_Y, OuyaExampleCommon.Player)) > 0.25f);
RendererAxisRight.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_Y, OuyaExampleCommon.Player) * 15, 0, GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_X, OuyaExampleCommon.Player) * 15);
RendererLT.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.BUTTON_LT, OuyaExampleCommon.Player) * -15, 0, 0);
RendererRT.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.BUTTON_RT, OuyaExampleCommon.Player) * -15, 0, 0);
if (GetButton(OuyaSDK.KeyEnum.BUTTON_L3, OuyaExampleCommon.Player))
{
RendererAxisLeft.transform.localPosition = Vector3.Lerp(RendererAxisLeft.transform.localPosition,
new Vector3(5.503977f, 0.75f, -3.344945f), Time.fixedDeltaTime);
}
else
{
RendererAxisLeft.transform.localPosition = Vector3.Lerp(RendererAxisLeft.transform.localPosition,
new Vector3(5.503977f, 1.127527f, -3.344945f), Time.fixedDeltaTime);
}
if (GetButton(OuyaSDK.KeyEnum.BUTTON_R3, OuyaExampleCommon.Player))
{
RendererAxisRight.transform.localPosition = Vector3.Lerp(RendererAxisRight.transform.localPosition,
new Vector3(-2.707688f, 0.75f, -1.354063f), Time.fixedDeltaTime);
}
else
{
RendererAxisRight.transform.localPosition = Vector3.Lerp(RendererAxisRight.transform.localPosition,
new Vector3(-2.707688f, 1.11295f, -1.354063f), Time.fixedDeltaTime);
}
#endregion
#region Button Code
#region BUTTONS O - A
//Check O button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_O, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonO, true, true);
}
else
{
UpdateHighlight(RendererButtonO, false, true);
}
//Check U button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_U, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonU, true, true);
}
else
{
UpdateHighlight(RendererButtonU, false, true);
}
//Check Y button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_Y, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonY, true, true);
}
else
{
UpdateHighlight(RendererButtonY, false, true);
}
//Check A button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_A, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonA, true, true);
}
else
{
UpdateHighlight(RendererButtonA, false, true);
}
//Check L3 button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_L3, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererAxisLeft, true, true);
}
else
{
UpdateHighlight(RendererAxisLeft, false, true);
}
//Check R3 button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_R3, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererAxisRight, true, true);
}
else
{
UpdateHighlight(RendererAxisRight, false, true);
}
#endregion
#region Bumpers
//Check LB button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_LB, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererLB, true, true);
}
else
{
UpdateHighlight(RendererLB, false, true);
}
//Check RB button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_RB, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererRB, true, true);
}
else
{
UpdateHighlight(RendererRB, false, true);
}
#endregion
#region triggers
//Check LT button for down state
if (GetAxis(OuyaSDK.KeyEnum.BUTTON_LT, OuyaExampleCommon.Player) > 0.25f)
{
UpdateHighlight(RendererLT, true, true);
}
else
{
UpdateHighlight(RendererLT, false, true);
}
//Check RT button for down state
if (GetAxis(OuyaSDK.KeyEnum.BUTTON_RT, OuyaExampleCommon.Player) > 0.25f)
{
UpdateHighlight(RendererRT, true, true);
}
else
{
UpdateHighlight(RendererRT, false, true);
}
#endregion
#region DPAD
//Check DPAD UP button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_UP, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadUp, true, true);
}
else
{
UpdateHighlight(RendererDpadUp, false, true);
}
//Check DPAD DOWN button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_DOWN, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadDown, true, true);
}
else
{
UpdateHighlight(RendererDpadDown, false, true);
}
//Check DPAD LEFT button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_LEFT, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadLeft, true, true);
}
else
{
UpdateHighlight(RendererDpadLeft, false, true);
}
//Check DPAD RIGHT button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_RIGHT, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadRight, true, true);
}
else
{
UpdateHighlight(RendererDpadRight, false, true);
}
#endregion
#endregion
}
#endregion
}
| |
//
// TableViewBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Gtk;
using System.Collections.Generic;
using System.Linq;
#if XWT_GTK3
using TreeModel = Gtk.ITreeModel;
#endif
namespace Xwt.GtkBackend
{
public class TableViewBackend: WidgetBackend, ICellRendererTarget
{
Dictionary<CellView,CellInfo> cellViews = new Dictionary<CellView, CellInfo> ();
class CellInfo {
public CellViewBackend Renderer;
public Gtk.TreeViewColumn Column;
}
protected override void OnSetBackgroundColor (Xwt.Drawing.Color color)
{
// Gtk3 workaround (by rpc-scandinavia, see https://github.com/mono/xwt/pull/411)
var selectedColor = Widget.GetBackgroundColor(StateType.Selected);
Widget.SetBackgroundColor (StateType.Normal, Xwt.Drawing.Colors.Transparent);
Widget.SetBackgroundColor (StateType.Selected, selectedColor);
base.OnSetBackgroundColor (color);
}
public TableViewBackend ()
{
var sw = new Gtk.ScrolledWindow ();
sw.ShadowType = Gtk.ShadowType.In;
sw.Child = new CustomTreeView (this);
sw.Child.Show ();
sw.Show ();
base.Widget = sw;
Widget.EnableSearch = false;
}
protected new Gtk.TreeView Widget {
get { return (Gtk.TreeView)ScrolledWindow.Child; }
}
protected Gtk.ScrolledWindow ScrolledWindow {
get { return (Gtk.ScrolledWindow)base.Widget; }
}
protected new ITableViewEventSink EventSink {
get { return (ITableViewEventSink)base.EventSink; }
}
protected override Gtk.Widget EventsRootWidget {
get {
return ScrolledWindow.Child;
}
}
public ScrollPolicy VerticalScrollPolicy {
get {
return ScrolledWindow.VscrollbarPolicy.ToXwtValue ();
}
set {
ScrolledWindow.VscrollbarPolicy = value.ToGtkValue ();
}
}
public ScrollPolicy HorizontalScrollPolicy {
get {
return ScrolledWindow.HscrollbarPolicy.ToXwtValue ();
}
set {
ScrolledWindow.HscrollbarPolicy = value.ToGtkValue ();
}
}
public GridLines GridLinesVisible
{
get { return Widget.EnableGridLines.ToXwtValue (); }
set { Widget.EnableGridLines = value.ToGtkValue (); }
}
public IScrollControlBackend CreateVerticalScrollControl ()
{
return new ScrollControltBackend (ScrolledWindow.Vadjustment);
}
public IScrollControlBackend CreateHorizontalScrollControl ()
{
return new ScrollControltBackend (ScrolledWindow.Hadjustment);
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is TableViewEvent) {
if (((TableViewEvent)eventId) == TableViewEvent.SelectionChanged)
Widget.Selection.Changed += HandleWidgetSelectionChanged;
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is TableViewEvent) {
if (((TableViewEvent)eventId) == TableViewEvent.SelectionChanged)
Widget.Selection.Changed -= HandleWidgetSelectionChanged;
}
}
void HandleWidgetSelectionChanged (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
});
}
public object AddColumn (ListViewColumn col)
{
Gtk.TreeViewColumn tc = new Gtk.TreeViewColumn ();
tc.Title = col.Title;
tc.Resizable = col.CanResize;
tc.Alignment = col.Alignment.ToGtkAlignment ();
tc.SortIndicator = col.SortIndicatorVisible;
tc.SortOrder = (SortType)col.SortDirection;
if (col.SortDataField != null)
tc.SortColumnId = col.SortDataField.Index;
Widget.AppendColumn (tc);
MapTitle (col, tc);
MapColumn (col, tc);
return tc;
}
void MapTitle (ListViewColumn col, Gtk.TreeViewColumn tc)
{
if (col.HeaderView == null)
tc.Title = col.Title;
else
tc.Widget = CellUtil.CreateCellRenderer (ApplicationContext, col.HeaderView);
}
void MapColumn (ListViewColumn col, Gtk.TreeViewColumn tc)
{
foreach (var k in cellViews.Where (e => e.Value.Column == tc).Select (e => e.Key).ToArray ())
cellViews.Remove (k);
foreach (var v in col.Views) {
var r = CellUtil.CreateCellRenderer (ApplicationContext, Frontend, this, tc, v);
cellViews [v] = new CellInfo {
Column = tc,
Renderer = r
};
}
}
public void RemoveColumn (ListViewColumn col, object handle)
{
Widget.RemoveColumn ((Gtk.TreeViewColumn)handle);
}
public void UpdateColumn (ListViewColumn col, object handle, ListViewColumnChange change)
{
Gtk.TreeViewColumn tc = (Gtk.TreeViewColumn) handle;
switch (change) {
case ListViewColumnChange.Cells:
tc.Clear ();
MapColumn (col, tc);
break;
case ListViewColumnChange.Title:
MapTitle (col, tc);
break;
case ListViewColumnChange.CanResize:
tc.Resizable = col.CanResize;
break;
case ListViewColumnChange.SortIndicatorVisible:
tc.SortIndicator = col.SortIndicatorVisible;
break;
case ListViewColumnChange.SortDirection:
tc.SortOrder = (SortType)col.SortDirection;
break;
case ListViewColumnChange.SortDataField:
if (col.SortDataField != null)
tc.SortColumnId = col.SortDataField.Index;
break;
case ListViewColumnChange.Alignment:
tc.Alignment = col.Alignment.ToGtkAlignment ();
break;
}
}
public void ScrollToRow (TreeIter pos)
{
if (Widget.Columns.Length > 0)
Widget.ScrollToCell (Widget.Model.GetPath (pos), Widget.Columns[0], false, 0, 0);
}
public void SelectAll ()
{
Widget.Selection.SelectAll ();
}
public void UnselectAll ()
{
Widget.Selection.UnselectAll ();
}
public void SetSelectionMode (SelectionMode mode)
{
switch (mode) {
case SelectionMode.Single: Widget.Selection.Mode = Gtk.SelectionMode.Single; break;
case SelectionMode.Multiple: Widget.Selection.Mode = Gtk.SelectionMode.Multiple; break;
}
}
protected Gtk.CellRenderer GetCellRenderer (CellView cell)
{
return cellViews [cell].Renderer.CellRenderer;
}
protected Gtk.TreeViewColumn GetCellColumn (CellView cell)
{
CellInfo ci;
if (cellViews.TryGetValue (cell, out ci))
return ci.Column;
return null;
}
#region ICellRendererTarget implementation
public void PackStart (object target, Gtk.CellRenderer cr, bool expand)
{
#if !XWT_GTK3
// Gtk2 tree background color workaround
if (UsingCustomBackgroundColor)
cr.CellBackgroundGdk = BackgroundColor.ToGtkValue ();
#endif
((Gtk.TreeViewColumn)target).PackStart (cr, expand);
}
public void PackEnd (object target, Gtk.CellRenderer cr, bool expand)
{
((Gtk.TreeViewColumn)target).PackEnd (cr, expand);
}
public void AddAttribute (object target, Gtk.CellRenderer cr, string field, int col)
{
((Gtk.TreeViewColumn)target).AddAttribute (cr, field, col);
}
public void SetCellDataFunc (object target, Gtk.CellRenderer cr, Gtk.CellLayoutDataFunc dataFunc)
{
((Gtk.TreeViewColumn)target).SetCellDataFunc (cr, dataFunc);
}
Rectangle ICellRendererTarget.GetCellBounds (object target, Gtk.CellRenderer cra, Gtk.TreeIter iter)
{
var col = (TreeViewColumn)target;
var path = Widget.Model.GetPath (iter);
col.CellSetCellData (Widget.Model, iter, false, false);
Gdk.Rectangle column_cell_area = Widget.GetCellArea (path, col);
CellRenderer[] renderers = col.GetCellRenderers();
for (int i = 0; i < renderers.Length; i++)
{
var cr = renderers [i];
if (cr == cra) {
int position_x, width, height;
int position_y = column_cell_area.Y;
col.CellGetPosition (cr, out position_x, out width);
if (i == renderers.Length - 1) {
#if XWT_GTK3
// Gtk3 allocates all available space to the last cell in the column
width = column_cell_area.Width - position_x;
#else
// Gtk2 sets the cell_area size to fit the largest cell in the inner column (row-wise)
// since we would have to scan the tree for the largest cell at this (horizontal) cell position
// we return the width of the current cell.
int padding_x, padding_y;
var cell_area = new Gdk.Rectangle(column_cell_area.X + position_x, position_y, width, column_cell_area.Height);
cr.GetSize (col.TreeView, ref cell_area, out padding_x, out padding_y, out width, out height);
position_x += padding_x;
// and add some padding at the end if it would not exceed column bounds
if (position_x + width + 2 <= column_cell_area.Width)
width += 2;
#endif
} else {
int position_x_next, width_next;
col.CellGetPosition (renderers [i + 1], out position_x_next, out width_next);
width = position_x_next - position_x;
}
position_x += column_cell_area.X;
height = column_cell_area.Height;
Widget.ConvertBinWindowToWidgetCoords (position_x, position_y, out position_x, out position_y);
return new Rectangle (position_x, position_y, width, height);
}
}
return Rectangle.Zero;
}
Rectangle ICellRendererTarget.GetCellBackgroundBounds (object target, Gtk.CellRenderer cra, Gtk.TreeIter iter)
{
var col = (TreeViewColumn)target;
var path = Widget.Model.GetPath (iter);
col.CellSetCellData (Widget.Model, iter, false, false);
Gdk.Rectangle column_cell_area = Widget.GetCellArea (path, col);
Gdk.Rectangle column_cell_bg_area = Widget.GetBackgroundArea (path, col);
CellRenderer[] renderers = col.Cells;
foreach (var cr in renderers) {
if (cr == cra) {
int position_x, width;
col.CellGetPosition (cr, out position_x, out width);
// Gtk aligns the bg area of a renderer to the cell area and not the bg area
// so we add the cell area offset to the position here
position_x += column_cell_bg_area.X + (column_cell_area.X - column_cell_bg_area.X);
// last widget gets the rest
if (cr == renderers[renderers.Length - 1])
width = column_cell_bg_area.Width - (position_x - column_cell_bg_area.X);
var cell_bg_bounds = new Gdk.Rectangle (position_x,
column_cell_bg_area.Y,
width,
column_cell_bg_area.Height);
Widget.ConvertBinWindowToWidgetCoords (cell_bg_bounds.X, cell_bg_bounds.Y, out cell_bg_bounds.X, out cell_bg_bounds.Y);
return new Rectangle (cell_bg_bounds.X, cell_bg_bounds.Y, cell_bg_bounds.Width, cell_bg_bounds.Height);
}
}
return Rectangle.Zero;
}
protected Rectangle GetRowBounds (Gtk.TreeIter iter)
{
var rect = Rectangle.Zero;
foreach (var col in Widget.Columns) {
foreach (var cr in col.GetCellRenderers()) {
Rectangle cell_rect = ((ICellRendererTarget)this).GetCellBounds (col, cr, iter);
if (rect == Rectangle.Zero)
rect = new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height);
else
rect = rect.Union (new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height));
}
}
return rect;
}
protected Rectangle GetRowBackgroundBounds (Gtk.TreeIter iter)
{
var path = Widget.Model.GetPath (iter);
var rect = Rectangle.Zero;
foreach (var col in Widget.Columns) {
Gdk.Rectangle cell_rect = Widget.GetBackgroundArea (path, col);
Widget.ConvertBinWindowToWidgetCoords (cell_rect.X, cell_rect.Y, out cell_rect.X, out cell_rect.Y);
if (rect == Rectangle.Zero)
rect = new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height);
else
rect = rect.Union (new Rectangle (cell_rect.X, cell_rect.Y, cell_rect.Width, cell_rect.Height));
}
return rect;
}
protected Gtk.TreePath GetPathAtPosition (Point p)
{
Gtk.TreePath path;
int x, y;
Widget.ConvertWidgetToBinWindowCoords ((int)p.X, (int)p.Y, out x, out y);
if (Widget.GetPathAtPos (x, y, out path))
return path;
return null;
}
protected override ButtonEventArgs GetButtonPressEventArgs (ButtonPressEventArgs args)
{
int x, y;
Widget.ConvertBinWindowToWidgetCoords ((int)args.Event.X, (int)args.Event.Y, out x, out y);
var xwt_args = base.GetButtonPressEventArgs (args);
xwt_args.X = x;
xwt_args.Y = y;
return xwt_args;
}
protected override ButtonEventArgs GetButtonReleaseEventArgs (ButtonReleaseEventArgs args)
{
int x, y;
Widget.ConvertBinWindowToWidgetCoords ((int)args.Event.X, (int)args.Event.Y, out x, out y);
var xwt_args = base.GetButtonReleaseEventArgs (args);
xwt_args.X = x;
xwt_args.Y = y;
return xwt_args;
}
protected override MouseMovedEventArgs GetMouseMovedEventArgs (MotionNotifyEventArgs args)
{
int x, y;
Widget.ConvertBinWindowToWidgetCoords ((int)args.Event.X, (int)args.Event.Y, out x, out y);
return new MouseMovedEventArgs ((long) args.Event.Time, x, y);
}
public virtual void SetCurrentEventRow (string path)
{
}
Gtk.Widget ICellRendererTarget.EventRootWidget {
get { return Widget; }
}
TreeModel ICellRendererTarget.Model {
get { return Widget.Model; }
}
Gtk.TreeIter ICellRendererTarget.PressedIter { get; set; }
CellViewBackend ICellRendererTarget.PressedCell { get; set; }
public bool GetCellPosition (Gtk.CellRenderer r, int ex, int ey, out int cx, out int cy, out Gtk.TreeIter it)
{
Gtk.TreeViewColumn col;
Gtk.TreePath path;
int cellx, celly;
cx = cy = 0;
it = Gtk.TreeIter.Zero;
if (!Widget.GetPathAtPos (ex, ey, out path, out col, out cellx, out celly))
return false;
if (!Widget.Model.GetIterFromString (out it, path.ToString ()))
return false;
int sp, w;
if (col.CellGetPosition (r, out sp, out w)) {
if (cellx >= sp && cellx < sp + w) {
Widget.ConvertBinWindowToWidgetCoords (ex, ey, out cx, out cy);
return true;
}
}
return false;
}
public void QueueDraw (object target, Gtk.TreeIter iter)
{
var p = Widget.Model.GetPath (iter);
var r = Widget.GetBackgroundArea (p, (Gtk.TreeViewColumn)target);
int x, y;
Widget.ConvertBinWindowToWidgetCoords (r.X, r.Y, out x, out y);
Widget.QueueDrawArea (x, y, r.Width, r.Height);
}
#endregion
}
class CustomTreeView: Gtk.TreeView
{
WidgetBackend backend;
public CustomTreeView (WidgetBackend b)
{
backend = b;
}
static CustomTreeView ()
{
// On Mac we want to be able to handle the backspace key (labeled "delete") in a custom way
// through a normal keypressed event but a default binding prevents this from happening because
// it maps it to "select-cursor-parent". However, that event is also bound to Ctrl+Backspace anyway
// so we can just kill one of those binding
if (Platform.IsMac)
GtkWorkarounds.RemoveKeyBindingFromClass (Gtk.TreeView.GType, Gdk.Key.BackSpace, Gdk.ModifierType.None);
}
protected override void OnDragDataDelete (Gdk.DragContext context)
{
// This method is override to avoid the default implementation
// being called. The default implementation deletes the
// row being dragged, and we don't want that
backend.DoDragaDataDelete ();
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Point.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.WindowsBase;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Windows.Markup;
using System.Windows.Converters;
using System.Windows;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows
{
[Serializable]
[TypeConverter(typeof(PointConverter))]
[ValueSerializer(typeof(PointValueSerializer))] // Used by MarkupWriter
partial struct Point : IFormattable
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Compares two Point instances for exact equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// </summary>
/// <returns>
/// bool - true if the two Point instances are exactly equal, false otherwise
/// </returns>
/// <param name='point1'>The first Point to compare</param>
/// <param name='point2'>The second Point to compare</param>
public static bool operator == (Point point1, Point point2)
{
return point1.X == point2.X &&
point1.Y == point2.Y;
}
/// <summary>
/// Compares two Point instances for exact inequality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// </summary>
/// <returns>
/// bool - true if the two Point instances are exactly unequal, false otherwise
/// </returns>
/// <param name='point1'>The first Point to compare</param>
/// <param name='point2'>The second Point to compare</param>
public static bool operator != (Point point1, Point point2)
{
return !(point1 == point2);
}
/// <summary>
/// Compares two Point instances for object equality. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if the two Point instances are exactly equal, false otherwise
/// </returns>
/// <param name='point1'>The first Point to compare</param>
/// <param name='point2'>The second Point to compare</param>
public static bool Equals (Point point1, Point point2)
{
return point1.X.Equals(point2.X) &&
point1.Y.Equals(point2.Y);
}
/// <summary>
/// Equals - compares this Point with the passed in object. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if the object is an instance of Point and if it's equal to "this".
/// </returns>
/// <param name='o'>The object to compare to "this"</param>
public override bool Equals(object o)
{
if ((null == o) || !(o is Point))
{
return false;
}
Point value = (Point)o;
return Point.Equals(this,value);
}
/// <summary>
/// Equals - compares this Point with the passed in object. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if "value" is equal to "this".
/// </returns>
/// <param name='value'>The Point to compare to "this"</param>
public bool Equals(Point value)
{
return Point.Equals(this, value);
}
/// <summary>
/// Returns the HashCode for this Point
/// </summary>
/// <returns>
/// int - the HashCode for this Point
/// </returns>
public override int GetHashCode()
{
// Perform field-by-field XOR of HashCodes
return X.GetHashCode() ^
Y.GetHashCode();
}
/// <summary>
/// Parse - returns an instance converted from the provided string using
/// the culture "en-US"
/// <param name="source"> string with Point data </param>
/// </summary>
public static Point Parse(string source)
{
IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
TokenizerHelper th = new TokenizerHelper(source, formatProvider);
Point value;
String firstToken = th.NextTokenRequired();
value = new Point(
Convert.ToDouble(firstToken, formatProvider),
Convert.ToDouble(th.NextTokenRequired(), formatProvider));
// There should be no more tokens in this string.
th.LastTokenRequired();
return value;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// X - double. Default value is 0.
/// </summary>
public double X
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// Y - double. Default value is 0.
/// </summary>
public double Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Creates a string representation of this object based on the current culture.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public override string ToString()
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
/// <summary>
/// Creates a string representation of this object based on the IFormatProvider
/// passed in. If the provider is null, the CurrentCulture is used.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public string ToString(IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
string IFormattable.ToString(string format, IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
internal string ConvertToString(string format, IFormatProvider provider)
{
// Helper to get the numeric list separator for a given culture.
char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider);
return String.Format(provider,
"{1:" + format + "}{0}{2:" + format + "}",
separator,
_x,
_y);
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal double _x;
internal double _y;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#endregion Constructors
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Azure.Storage.Blobs.Models;
namespace Azure.Storage.Blobs.ChangeFeed
{
internal class LazyLoadingBlobStream : Stream
{
/// <summary>
/// BlobClient to make download calls with.
/// </summary>
private readonly BlobClient _blobClient;
/// <summary>
/// The offset within the blob of the next block we will download.
/// </summary>
private long _offset;
/// <summary>
/// The number of bytes we'll download with each download call.
/// </summary>
private readonly long _blockSize;
/// <summary>
/// Underlying Stream.
/// </summary>
private Stream _stream;
/// <summary>
/// If this LazyLoadingBlobStream has been initalized.
/// </summary>
private bool _initalized;
/// <summary>
/// The number of bytes in the last download call.
/// </summary>
private long _lastDownloadBytes;
/// <summary>
/// The current length of the blob.
/// </summary>
private long _blobLength;
public LazyLoadingBlobStream(BlobClient blobClient, long offset, long blockSize)
{
_blobClient = blobClient;
_offset = offset;
_blockSize = blockSize;
_initalized = false;
}
/// <summary>
/// Constructor for mocking.
/// </summary>
public LazyLoadingBlobStream() { }
/// <inheritdoc/>
public override int Read(
byte[] buffer,
int offset,
int count)
=> ReadInternal(
async: false,
buffer,
offset,
count).EnsureCompleted();
/// <inheritdoc/>
public override async Task<int> ReadAsync(
byte[] buffer,
int offset,
int count,
CancellationToken cancellationToken)
=> await ReadInternal(
async: true,
buffer,
offset,
count,
cancellationToken).ConfigureAwait(false);
/// <summary>
/// Initalizes this LazyLoadingBlobStream.
/// </summary>
private async Task Initalize(bool async, CancellationToken cancellationToken)
{
await DownloadBlock(async, cancellationToken).ConfigureAwait(false);
_initalized = true;
}
/// <summary>
/// Downloads the next block.
/// </summary>
private async Task DownloadBlock(bool async, CancellationToken cancellationToken)
{
Response<BlobDownloadInfo> response;
HttpRange range = new HttpRange(_offset, _blockSize);
response = async
? await _blobClient.DownloadAsync(range, cancellationToken: cancellationToken).ConfigureAwait(false)
: _blobClient.Download(range, cancellationToken: cancellationToken);
_stream = response.Value.Content;
_offset += response.Value.ContentLength;
_lastDownloadBytes = response.Value.ContentLength;
_blobLength = GetBlobLength(response);
}
/// <summary>
/// Shared sync and async Read implementation.
/// </summary>
private async Task<int> ReadInternal(
bool async,
byte[] buffer,
int offset,
int count,
CancellationToken cancellationToken = default)
{
ValidateReadParameters(buffer, offset, count);
if (!_initalized)
{
await Initalize(async, cancellationToken: cancellationToken).ConfigureAwait(false);
if (_lastDownloadBytes == 0)
{
return 0;
}
}
int totalCopiedBytes = 0;
do
{
int copiedBytes = async
? await _stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false)
: _stream.Read(buffer, offset, count);
offset += copiedBytes;
count -= copiedBytes;
totalCopiedBytes += copiedBytes;
// We've run out of bytes in the current block.
if (copiedBytes == 0)
{
// We hit the end of the blob with the last download call.
if (_offset == _blobLength)
{
return totalCopiedBytes;
}
// Download the next block
else
{
await DownloadBlock(async, cancellationToken).ConfigureAwait(false);
}
}
}
while (count > 0);
return totalCopiedBytes;
}
private static void ValidateReadParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException($"{nameof(buffer)}", $"{nameof(buffer)} cannot be null.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot be less than 0.");
}
if (offset > buffer.Length)
{
throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot exceed {nameof(buffer)} length.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException($"{nameof(count)} cannot be less than 0.");
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException($"{nameof(offset)} + {nameof(count)} cannot exceed {nameof(buffer)} length.");
}
}
private static long GetBlobLength(Response<BlobDownloadInfo> response)
{
string lengthString = response.Value.Details.ContentRange;
string[] split = lengthString.Split('/');
return long.Parse(split[1], CultureInfo.InvariantCulture);
}
/// <inheritdoc/>
public override bool CanRead => true;
/// <inheritdoc/>
public override bool CanSeek => false;
/// <inheritdoc/>
public override bool CanWrite => throw new NotSupportedException();
public override long Length => throw new NotSupportedException();
/// <inheritdoc/>
public override long Position {
get => _stream.Position;
set => throw new NotSupportedException();
}
/// <inheritdoc/>
public override void Flush()
{
}
/// <inheritdoc/>
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_stream.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.DirectoryServices.ActiveDirectory
{
using System;
using System.Net;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
internal sealed class Locator
{
// To disable public/protected constructors for this class
private Locator() { }
internal static DomainControllerInfo GetDomainControllerInfo(string computerName, string domainName, string siteName, long flags)
{
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = DsGetDcNameWrapper(computerName, domainName, siteName, flags, out domainControllerInfo);
if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode, domainName);
}
return domainControllerInfo;
}
internal static int DsGetDcNameWrapper(string computerName, string domainName, string siteName, long flags, out DomainControllerInfo domainControllerInfo)
{
IntPtr pDomainControllerInfo = IntPtr.Zero;
int result = 0;
// empty siteName/computerName should be treated as null
if ((computerName != null) && (computerName.Length == 0))
{
computerName = null;
}
if ((siteName != null) && (siteName.Length == 0))
{
siteName = null;
}
result = NativeMethods.DsGetDcName(computerName, domainName, IntPtr.Zero, siteName, (int)(flags | (long)PrivateLocatorFlags.ReturnDNSName), out pDomainControllerInfo);
if (result == 0)
{
try
{
// success case
domainControllerInfo = new DomainControllerInfo();
Marshal.PtrToStructure(pDomainControllerInfo, domainControllerInfo);
}
finally
{
// free the buffer
// what to do with error code??
if (pDomainControllerInfo != IntPtr.Zero)
{
result = NativeMethods.NetApiBufferFree(pDomainControllerInfo);
}
}
}
else
{
domainControllerInfo = new DomainControllerInfo();
}
return result;
}
internal static ArrayList EnumerateDomainControllers(DirectoryContext context, string domainName, string siteName, long dcFlags)
{
Hashtable allDCs = null;
ArrayList dcs = new ArrayList();
//
// this api obtains the list of DCs/GCs based on dns records. The DCs/GCs that have registered
// non site specific records for the domain/forest are returned. Additonally DCs/GCs that have registered site specific records
// (site is either specified or defaulted to the site of the local machine) are also returned in this list.
//
if (siteName == null)
{
//
// if the site name is not specified then we get the site specific records for the local machine's site (in the context of the domain/forest/application partition that is specified)
// (sitename could still be null if the machine is not in any site for the specified domain/forest, in that case we don't look for any site specific records)
//
DomainControllerInfo domainControllerInfo;
int errorCode = DsGetDcNameWrapper(null, domainName, null, dcFlags & (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DSWriteableRequired | PrivateLocatorFlags.OnlyLDAPNeeded), out domainControllerInfo);
if (errorCode == 0)
{
siteName = domainControllerInfo.ClientSiteName;
}
else if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// return an empty collection
return dcs;
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
}
// this will get both the non site specific and the site specific records
allDCs = DnsGetDcWrapper(domainName, siteName, dcFlags);
foreach (string dcName in allDCs.Keys)
{
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
if ((dcFlags & (long)PrivateLocatorFlags.GCRequired) != 0)
{
// add a GlobalCatalog object
dcs.Add(new GlobalCatalog(dcContext, dcName));
}
else
{
// add a domain controller object
dcs.Add(new DomainController(dcContext, dcName));
}
}
return dcs;
}
private static Hashtable DnsGetDcWrapper(string domainName, string siteName, long dcFlags)
{
Hashtable domainControllers = new Hashtable();
int optionFlags = 0;
IntPtr retGetDcContext = IntPtr.Zero;
IntPtr dcDnsHostNamePtr = IntPtr.Zero;
int sockAddressCount = 0;
IntPtr sockAddressCountPtr = new IntPtr(sockAddressCount);
IntPtr sockAddressList = IntPtr.Zero;
string dcDnsHostName = null;
int result = 0;
result = NativeMethods.DsGetDcOpen(domainName, (int)optionFlags, siteName, IntPtr.Zero, null, (int)dcFlags, out retGetDcContext);
if (result == 0)
{
try
{
result = NativeMethods.DsGetDcNext(retGetDcContext, ref sockAddressCountPtr, out sockAddressList, out dcDnsHostNamePtr);
if (result != 0 && result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR && result != NativeMethods.ERROR_NO_MORE_ITEMS)
{
throw ExceptionHelper.GetExceptionFromErrorCode(result);
}
while (result != NativeMethods.ERROR_NO_MORE_ITEMS)
{
if (result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR)
{
try
{
dcDnsHostName = Marshal.PtrToStringUni(dcDnsHostNamePtr);
string key = dcDnsHostName.ToLower(CultureInfo.InvariantCulture);
if (!domainControllers.Contains(key))
{
domainControllers.Add(key, null);
}
}
finally
{
// what to do with the error?
if (dcDnsHostNamePtr != IntPtr.Zero)
{
result = NativeMethods.NetApiBufferFree(dcDnsHostNamePtr);
}
}
}
result = NativeMethods.DsGetDcNext(retGetDcContext, ref sockAddressCountPtr, out sockAddressList, out dcDnsHostNamePtr);
if (result != 0 && result != NativeMethods.ERROR_FILE_MARK_DETECTED && result != NativeMethods.DNS_ERROR_RCODE_NAME_ERROR && result != NativeMethods.ERROR_NO_MORE_ITEMS)
{
throw ExceptionHelper.GetExceptionFromErrorCode(result);
}
}
}
finally
{
NativeMethods.DsGetDcClose(retGetDcContext);
}
}
else if (result != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(result);
}
return domainControllers;
}
private static Hashtable DnsQueryWrapper(string domainName, string siteName, long dcFlags)
{
Hashtable domainControllers = new Hashtable();
string recordName = "_ldap._tcp.";
int result = 0;
int options = 0;
IntPtr dnsResults = IntPtr.Zero;
// construct the record name
if ((siteName != null) && (!(siteName.Length == 0)))
{
// only looking for domain controllers / global catalogs within a
// particular site
recordName = recordName + siteName + "._sites.";
}
// check if gc or dc
if (((long)dcFlags & (long)(PrivateLocatorFlags.GCRequired)) != 0)
{
// global catalog
recordName += "gc._msdcs.";
}
else if (((long)dcFlags & (long)(PrivateLocatorFlags.DSWriteableRequired)) != 0)
{
// domain controller
recordName += "dc._msdcs.";
}
// now add the domainName
recordName = recordName + domainName;
// set the BYPASS CACHE option is specified
if (((long)dcFlags & (long)LocatorOptions.ForceRediscovery) != 0)
{
options |= NativeMethods.DnsQueryBypassCache;
}
// Call DnsQuery
result = NativeMethods.DnsQuery(recordName, NativeMethods.DnsSrvData, options, IntPtr.Zero, out dnsResults, IntPtr.Zero);
if (result == 0)
{
try
{
IntPtr currentDnsRecord = dnsResults;
while (currentDnsRecord != IntPtr.Zero)
{
// partial marshalling of dns record data
PartialDnsRecord partialDnsRecord = new PartialDnsRecord();
Marshal.PtrToStructure(currentDnsRecord, partialDnsRecord);
//check if the record is of type DNS_SRV_DATA
if (partialDnsRecord.type == NativeMethods.DnsSrvData)
{
// remarshal to get the srv record data
DnsRecord dnsRecord = new DnsRecord();
Marshal.PtrToStructure(currentDnsRecord, dnsRecord);
string targetName = dnsRecord.data.targetName;
string key = targetName.ToLower(CultureInfo.InvariantCulture);
if (!domainControllers.Contains(key))
{
domainControllers.Add(key, null);
}
}
// move to next record
currentDnsRecord = partialDnsRecord.next;
}
}
finally
{
// release the dns results buffer
if (dnsResults != IntPtr.Zero)
{
NativeMethods.DnsRecordListFree(dnsResults, true);
}
}
}
else if (result != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(result);
}
return domainControllers;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class MaxTests
{
// Get a set of ranges from 0 to each count, having an extra parameter describing the maximum (count - 1)
public static IEnumerable<object[]> MaxData(int[] counts)
{
counts = counts.DefaultIfEmpty(Sources.OuterLoopCount).ToArray();
Func<int, int> max = x => x - 1;
foreach (int count in counts)
{
yield return new object[] { Labeled.Label("Default", UnorderedSources.Default(0, count)), count, max(count) };
}
// A source with data explicitly created out of order
foreach (int count in counts)
{
int[] data = Enumerable.Range(0, count).ToArray();
for (int i = 0; i < count / 2; i += 2)
{
int tmp = data[i];
data[i] = data[count - i - 1];
data[count - i - 1] = tmp;
}
yield return new object[] { Labeled.Label("Out-of-order input", data.AsParallel()), count, max(count) };
}
}
//
// Max
//
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Int(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Max());
Assert.Equal(max, query.Select(x => (int?)x).Max());
Assert.Equal(0, query.Max(x => -x));
Assert.Equal(0, query.Max(x => -(int?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(MaxData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Max_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
Max_Int(labeled, count, max);
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => x >= count / 2 ? (int?)x : null).Max());
Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(int?)x : null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (int?)null).Max());
Assert.Null(query.Max(x => (int?)null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Long(Labeled<ParallelQuery<int>> labeled, int count, long max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => (long)x).Max());
Assert.Equal(max, query.Select(x => (long?)x).Max());
Assert.Equal(0, query.Max(x => -(long)x));
Assert.Equal(0, query.Max(x => -(long?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(MaxData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Max_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long max)
{
Max_Long(labeled, count, max);
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => x >= count / 2 ? (long?)x : null).Max());
Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(long?)x : null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (long?)null).Max());
Assert.Null(query.Max(x => (long?)null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Float(Labeled<ParallelQuery<int>> labeled, int count, float max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => (float)x).Max());
Assert.Equal(max, query.Select(x => (float?)x).Max());
Assert.Equal(0, query.Max(x => -(float)x));
Assert.Equal(0, query.Max(x => -(float?)x));
Assert.Equal(float.PositiveInfinity, query.Select(x => x == count / 2 ? float.PositiveInfinity : x).Max());
Assert.Equal(float.PositiveInfinity, query.Select(x => x == count / 2 ? (float?)float.PositiveInfinity : x).Max());
}
[Theory]
[OuterLoop]
[MemberData(nameof(MaxData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Max_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float max)
{
Max_Float(labeled, count, max);
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => x >= count / 2 ? (float?)x : null).Max());
Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(float?)x : null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (float?)null).Max());
Assert.Null(query.Max(x => (float?)null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Double(Labeled<ParallelQuery<int>> labeled, int count, double max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => (double)x).Max());
Assert.Equal(max, query.Select(x => (double?)x).Max());
Assert.Equal(0, query.Max(x => -(double)x));
Assert.Equal(0, query.Max(x => -(double?)x));
Assert.Equal(double.PositiveInfinity, query.Select(x => x == count / 2 ? double.PositiveInfinity : x).Max());
Assert.Equal(double.PositiveInfinity, query.Select(x => x == count / 2 ? (double?)double.PositiveInfinity : x).Max());
}
[Theory]
[OuterLoop]
[MemberData(nameof(MaxData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Max_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double max)
{
Max_Double(labeled, count, max);
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => x >= count / 2 ? (double?)x : null).Max());
Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(double?)x : null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (double?)null).Max());
Assert.Null(query.Max(x => (double?)null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => (decimal)x).Max());
Assert.Equal(max, query.Select(x => (decimal?)x).Max());
Assert.Equal(0, query.Max(x => -(decimal)x));
Assert.Equal(0, query.Max(x => -(decimal?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(MaxData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Max_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal max)
{
Max_Decimal(labeled, count, max);
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => x >= count / 2 ? (decimal?)x : null).Max());
Assert.Equal(-count / 2, query.Max(x => x >= count / 2 ? -(decimal?)x : null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (decimal?)null).Max());
Assert.Null(query.Max(x => (decimal?)null));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Other(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Select(x => DelgatedComparable.Delegate(x, Comparer<int>.Default)).Max().Value);
Assert.Equal(0, query.Select(x => DelgatedComparable.Delegate(x, ReverseComparer.Instance)).Max().Value);
}
[Theory]
[OuterLoop]
[MemberData(nameof(MaxData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Max_Other_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
Max_Other(labeled, count, max);
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1 })]
public static void Max_NotComparable(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
NotComparable a = new NotComparable(0);
Assert.Equal(a, labeled.Item.Max(x => a));
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Other_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(max, query.Max(x => x >= count / 2 ? DelgatedComparable.Delegate(x, Comparer<int>.Default) : null).Value);
Assert.Equal(count / 2, query.Max(x => x >= count / 2 ? DelgatedComparable.Delegate(x, ReverseComparer.Instance) : null).Value);
}
[Theory]
[MemberData(nameof(MaxData), new[] { 1, 2, 16 })]
public static void Max_Other_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int max)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (string)null).Max());
Assert.Null(query.Max(x => (string)null));
}
[Fact]
public static void Max_EmptyNullable()
{
Assert.Null(ParallelEnumerable.Empty<int?>().Max());
Assert.Null(ParallelEnumerable.Empty<long?>().Max());
Assert.Null(ParallelEnumerable.Empty<float?>().Max());
Assert.Null(ParallelEnumerable.Empty<double?>().Max());
Assert.Null(ParallelEnumerable.Empty<decimal?>().Max());
Assert.Null(ParallelEnumerable.Empty<object>().Max());
Assert.Null(ParallelEnumerable.Empty<int>().Max(x => (int?)x));
Assert.Null(ParallelEnumerable.Empty<int>().Max(x => (long?)x));
Assert.Null(ParallelEnumerable.Empty<int>().Max(x => (float?)x));
Assert.Null(ParallelEnumerable.Empty<int>().Max(x => (double?)x));
Assert.Null(ParallelEnumerable.Empty<int>().Max(x => (decimal?)x));
Assert.Null(ParallelEnumerable.Empty<int>().Max(x => new object()));
}
[Fact]
public static void Max_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Max());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Max());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Max());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Max());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Max());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<NotComparable>().Max());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Max(x => (int)x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Max(x => (long)x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Max(x => (float)x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Max(x => (double)x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Max(x => (decimal)x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Max(x => new NotComparable(x)));
}
[Fact]
public static void Max_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (int?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (long)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (long?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (float)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (float?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (double)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (double?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (decimal)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Max(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Max_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (int?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (long)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (long?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (float)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (float?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (double)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (double?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (decimal)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Max(x => { canceler(); return (decimal?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (int?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (long)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (long?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (float)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (float?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (double)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (double?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (decimal)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Max(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Max_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.Max(x => x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (int?)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (long)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (long?)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (float)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (float?)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (double)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (double?)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (decimal)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => (decimal?)x));
AssertThrows.AlreadyCanceled(source => source.Max(x => new NotComparable(x)));
}
[Fact]
public static void Max_AggregateException()
{
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, int>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, long>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, float>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, double>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => ParallelEnumerable.Range(0, 1).Max((Func<int, NotComparable>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Max_AggregateException_NotComparable()
{
ArgumentException e = AssertThrows.Wrapped<ArgumentException>(() => ParallelEnumerable.Repeat(new NotComparable(0), 2).Max());
Assert.Null(e.ParamName);
e = AssertThrows.Wrapped<ArgumentException>(() => ParallelEnumerable.Range(0, 2).Max(x => new NotComparable(x)));
Assert.Null(e.ParamName);
}
[Fact]
public static void Max_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Range(0, 1).Max((Func<int, int>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int?>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((int?)0, 1).Max((Func<int?, int?>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<long>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((long)0, 1).Max((Func<long, long>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<long?>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((long?)0, 1).Max((Func<long?, long?>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<float>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((float)0, 1).Max((Func<float, float>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<float?>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((float?)0, 1).Max((Func<float?, float>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<double>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((double)0, 1).Max((Func<double, double>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<double?>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((double?)0, 1).Max((Func<double?, double>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<decimal>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((decimal)0, 1).Max((Func<decimal, decimal>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<decimal?>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((decimal?)0, 1).Max((Func<decimal?, decimal>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<NotComparable>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat(0, 1).Max((Func<int, NotComparable>)null));
Assert.Throws<ArgumentNullException>("source", () => ((ParallelQuery<object>)null).Max());
Assert.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat(new object(), 1).Max((Func<object, object>)null));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace LinqToDB
{
using Linq;
/// <summary>
/// Provides helper methods for asynchronous operations.
/// </summary>
[PublicAPI]
public static partial class AsyncExtensions
{
#region Helpers
/// <summary>
/// Executes provided action using task scheduler.
/// </summary>
/// <param name="action">Action to execute.</param>
/// <param name="token">Asynchronous operation cancellation token.</param>
/// <returns>Asynchronous operation completion task.</returns>
internal static Task GetActionTask(Action action, CancellationToken token)
{
var task = new Task(action, token);
task.Start();
return task;
}
/// <summary>
/// Executes provided function using task scheduler.
/// </summary>
/// <typeparam name="T">Function result type.</typeparam>
/// <param name="func">Function to execute.</param>
/// <returns>Asynchronous operation completion task.</returns>
static Task<T> GetTask<T>(Func<T> func)
{
var task = new Task<T>(func);
task.Start();
return task;
}
/// <summary>
/// Executes provided function using task scheduler.
/// </summary>
/// <typeparam name="T">Function result type.</typeparam>
/// <param name="func">Function to execute.</param>
/// <param name="token">Asynchronous operation cancellation token.</param>
/// <returns>Asynchronous operation completion task.</returns>
static Task<T> GetTask<T>(Func<T> func, CancellationToken token)
{
var task = new Task<T>(func, token);
task.Start();
return task;
}
#endregion
#region ForEachAsync
/// <summary>
/// Asynchronously apply provided action to each element in source sequence.
/// Sequence elements processed sequentially.
/// </summary>
/// <typeparam name="TSource">Source sequence element type.</typeparam>
/// <param name="source">Source sequence.</param>
/// <param name="action">Action to apply to each sequence element.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>Asynchronous operation completion task.</returns>
public static Task ForEachAsync<TSource>(
this IQueryable<TSource> source, Action<TSource> action,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
return query.GetForEachAsync(action, token);
return GetActionTask(() =>
{
foreach (var item in source)
{
if (token.IsCancellationRequested)
break;
action(item);
}
},
token);
}
/// <summary>
/// Asynchronously apply provided function to each element in source sequence sequentially.
/// Sequence enumeration stops if function returns <c>false</c>.
/// </summary>
/// <typeparam name="TSource">Source sequence element type.</typeparam>
/// <param name="source">Source sequence.</param>
/// <param name="func">Function to apply to each sequence element. Returning <c>false</c> from function will stop numeration.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>Asynchronous operation completion task.</returns>
public static Task ForEachUntilAsync<TSource>(
this IQueryable<TSource> source, Func<TSource,bool> func,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
return query.GetForEachUntilAsync(func, token);
return GetActionTask(() =>
{
foreach (var item in source)
if (token.IsCancellationRequested || !func(item))
break;
},
token);
}
#endregion
#region ToListAsync
/// <summary>
/// Asynchronously loads data from query to a list.
/// </summary>
/// <typeparam name="TSource">Query element type.</typeparam>
/// <param name="source">Source query.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>List with query results.</returns>
public static async Task<List<TSource>> ToListAsync<TSource>(
this IQueryable<TSource> source,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
{
var list = new List<TSource>();
await query.GetForEachAsync(list.Add, token);
return list;
}
return await GetTask(() => source.AsEnumerable().TakeWhile(_ => !token.IsCancellationRequested).ToList(), token);
}
#endregion
#region ToArrayAsync
/// <summary>
/// Asynchronously loads data from query to an array.
/// </summary>
/// <typeparam name="TSource">Query element type.</typeparam>
/// <param name="source">Source query.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>Array with query results.</returns>
public static async Task<TSource[]> ToArrayAsync<TSource>(
this IQueryable<TSource> source,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
{
var list = new List<TSource>();
await query.GetForEachAsync(list.Add, token);
return list.ToArray();
}
return await GetTask(() => source.AsEnumerable().TakeWhile(_ => !token.IsCancellationRequested).ToArray(), token);
}
#endregion
#region ToDictionaryAsync
/// <summary>
/// Asynchronously loads data from query to a dictionary.
/// </summary>
/// <typeparam name="TSource">Query element type.</typeparam>
/// <typeparam name="TKey">Dictionary key type.</typeparam>
/// <param name="source">Source query.</param>
/// <param name="keySelector">Source element key selector.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>Dictionary with query results.</returns>
public static async Task<Dictionary<TKey,TSource>> ToDictionaryAsync<TSource,TKey>(
this IQueryable<TSource> source,
Func<TSource,TKey> keySelector,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
{
var dic = new Dictionary<TKey,TSource>();
await query.GetForEachAsync(item => dic.Add(keySelector(item), item), token);
return dic;
}
return await GetTask(() => source.AsEnumerable().TakeWhile(_ => !token.IsCancellationRequested).ToDictionary(keySelector), token);
}
/// <summary>
/// Asynchronously loads data from query to a dictionary.
/// </summary>
/// <typeparam name="TSource">Query element type.</typeparam>
/// <typeparam name="TKey">Dictionary key type.</typeparam>
/// <param name="source">Source query.</param>
/// <param name="keySelector">Source element key selector.</param>
/// <param name="comparer">Dictionary key comparer.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>Dictionary with query results.</returns>
public static async Task<Dictionary<TKey,TSource>> ToDictionaryAsync<TSource,TKey>(
this IQueryable<TSource> source,
Func<TSource,TKey> keySelector,
IEqualityComparer<TKey> comparer,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
{
var dic = new Dictionary<TKey,TSource>(comparer);
await query.GetForEachAsync(item => dic.Add(keySelector(item), item), token);
return dic;
}
return await GetTask(() => source.AsEnumerable().TakeWhile(_ => !token.IsCancellationRequested).ToDictionary(keySelector, comparer), token);
}
/// <summary>
/// Asynchronously loads data from query to a dictionary.
/// </summary>
/// <typeparam name="TSource">Query element type.</typeparam>
/// <typeparam name="TKey">Dictionary key type.</typeparam>
/// <typeparam name="TElement">Dictionary element type.</typeparam>
/// <param name="source">Source query.</param>
/// <param name="keySelector">Source element key selector.</param>
/// <param name="elementSelector">Dictionary element selector.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>Dictionary with query results.</returns>
public static async Task<Dictionary<TKey,TElement>> ToDictionaryAsync<TSource,TKey,TElement>(
this IQueryable<TSource> source,
Func<TSource,TKey> keySelector,
Func<TSource,TElement> elementSelector,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
{
var dic = new Dictionary<TKey,TElement>();
await query.GetForEachAsync(item => dic.Add(keySelector(item), elementSelector(item)), token);
return dic;
}
return await GetTask(() => source.AsEnumerable().TakeWhile(_ => !token.IsCancellationRequested).ToDictionary(keySelector, elementSelector), token);
}
/// <summary>
/// Asynchronously loads data from query to a dictionary.
/// </summary>
/// <typeparam name="TSource">Query element type.</typeparam>
/// <typeparam name="TKey">Dictionary key type.</typeparam>
/// <typeparam name="TElement">Dictionary element type.</typeparam>
/// <param name="source">Source query.</param>
/// <param name="keySelector">Source element key selector.</param>
/// <param name="elementSelector">Dictionary element selector.</param>
/// <param name="comparer">Dictionary key comparer.</param>
/// <param name="token">Optional asynchronous operation cancellation token.</param>
/// <returns>Dictionary with query results.</returns>
public static async Task<Dictionary<TKey,TElement>> ToDictionaryAsync<TSource,TKey,TElement>(
this IQueryable<TSource> source,
Func<TSource,TKey> keySelector,
Func<TSource,TElement> elementSelector,
IEqualityComparer<TKey> comparer,
CancellationToken token = default)
{
if (source is ExpressionQuery<TSource> query)
{
var dic = new Dictionary<TKey,TElement>();
await query.GetForEachAsync(item => dic.Add(keySelector(item), elementSelector(item)), token);
return dic;
}
return await GetTask(() => source.AsEnumerable().TakeWhile(_ => !token.IsCancellationRequested).ToDictionary(keySelector, elementSelector, comparer), token);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using QiHe.CodeLib;
namespace ExcelLibrary.BinaryFileFormat
{
public partial class Record
{
public UInt16 Type;
public UInt16 Size;
public byte[] Data;
public List<Record> ContinuedRecords;
public const UInt16 MaxContentLength = 8224;
public Record()
{
ContinuedRecords = new List<Record>();
}
public Record(Record record)
{
Type = record.Type;
Size = record.Size;
Data = record.Data;
ContinuedRecords = record.ContinuedRecords;
}
public virtual void Decode()
{
}
public virtual void Encode()
{
this.ContinuedRecords.Clear();
if (Size > 0 && Data.Length > MaxContentLength)
{
int index = MaxContentLength;
while (index < Data.Length)
{
CONTINUE continuedRecord = new CONTINUE();
int size = Math.Min(MaxContentLength, Data.Length - index);
continuedRecord.Data = Algorithm.ArraySection(Data, index, size);
continuedRecord.Size = (ushort)size;
this.ContinuedRecords.Add(continuedRecord);
index += size;
}
this.Size = MaxContentLength;
this.Data = Algorithm.ArraySection(Data, 0, MaxContentLength);
}
}
public static Record ReadBase(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
Record record = new Record();
record.Type = reader.ReadUInt16();
record.Size = reader.ReadUInt16();
record.Data = reader.ReadBytes(record.Size);
return record;
}
/// <summary>
/// Data size plus header size
/// </summary>
public int FullSize
{
get
{
int full_size = 4 + Size;
foreach (Record record in ContinuedRecords)
{
full_size += 4 + record.Size;
}
return full_size;
}
}
public int TotalSize
{
get
{
int total_size = Size;
foreach (Record record in ContinuedRecords)
{
total_size += record.Size;
}
return total_size;
}
}
public byte[] AllData
{
get
{
if (ContinuedRecords.Count == 0) return Data;
else
{
List<byte> data = new List<byte>(TotalSize);
data.AddRange(Data);
foreach (Record record in ContinuedRecords)
{
data.AddRange(record.AllData);
}
return data.ToArray();
}
}
}
public static object DecodeRK(uint value)
{
bool muled = (value & 0x01) == 1;
bool isFloat = (value & 0x02) == 0;
if (isFloat)
{
UInt64 data = ((UInt64)(value & 0xFFFFFFFC)) << 32;
double num = TreatUInt64AsDouble(data);
if (muled) num /= 100;
return num;
}
else
{
Int32 num = (int)(value & 0xFFFFFFFC) >> 2;
if (muled)
{
return (decimal)num / 100;
}
return num;
}
}
public static double TreatUInt64AsDouble(UInt64 data)
{
//byte[] bytes = new byte[8];
//MemoryStream stream = new MemoryStream(bytes);
//BinaryWriter writer = new BinaryWriter(stream);
//BinaryReader reader = new BinaryReader(stream);
//writer.Write(data);
//stream.Position = 0;
//return reader.ReadDouble();
byte[] bytes = BitConverter.GetBytes(data);
return BitConverter.ToDouble(bytes, 0);
}
public void Write(BinaryWriter writer)
{
writer.Write(this.Type);
writer.Write(this.Size);
if (this.Size > 0)
{
writer.Write(this.Data);
if (this.ContinuedRecords.Count > 0)
{
foreach (Record record in ContinuedRecords)
{
writer.Write(record.Type);
writer.Write(record.Size);
writer.Write(record.Data);
}
}
}
}
public string ReadString(BinaryReader reader, int lengthbits)
{
StringDecoder stringDecoder = new StringDecoder(this, reader);
return stringDecoder.ReadString(lengthbits);
}
public static void WriteString(BinaryWriter writer, string text, int lengthbits)
{
if (lengthbits == 8)
{
writer.Write((byte)text.Length);
}
else if (lengthbits == 16)
{
writer.Write((ushort)text.Length);
}
else
{
throw new ArgumentException("Invalid lengthbits, must be 8 or 16.");
}
if (TextEncoding.FitsInASCIIEncoding(text))
{
writer.Write((byte)0);
writer.Write(Encoding.ASCII.GetBytes(text));
}
else
{
writer.Write((byte)1);
writer.Write(Encoding.Unicode.GetBytes(text));
}
}
public static int GetStringDataLength(string text)
{
if (TextEncoding.FitsInASCIIEncoding(text))
{
return Encoding.ASCII.GetByteCount(text) + 3;
}
else
{
return text.Length * 2 + 3;
}
}
public static void EncodeRecords(List<Record> records)
{
foreach (Record record in records)
{
record.Encode();
}
}
public static int CountDataLength(List<Record> records)
{
int dataLength = 0;
foreach (Record record in records)
{
dataLength += record.FullSize;
}
return dataLength;
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A tunnel for network traffic
/// First published in XenServer 5.6 FP1.
/// </summary>
public partial class Tunnel : XenObject<Tunnel>
{
public Tunnel()
{
}
public Tunnel(string uuid,
XenRef<PIF> access_PIF,
XenRef<PIF> transport_PIF,
Dictionary<string, string> status,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.access_PIF = access_PIF;
this.transport_PIF = transport_PIF;
this.status = status;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Tunnel from a Proxy_Tunnel.
/// </summary>
/// <param name="proxy"></param>
public Tunnel(Proxy_Tunnel proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Tunnel.
/// </summary>
public override void UpdateFrom(Tunnel update)
{
uuid = update.uuid;
access_PIF = update.access_PIF;
transport_PIF = update.transport_PIF;
status = update.status;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Tunnel proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
access_PIF = proxy.access_PIF == null ? null : XenRef<PIF>.Create(proxy.access_PIF);
transport_PIF = proxy.transport_PIF == null ? null : XenRef<PIF>.Create(proxy.transport_PIF);
status = proxy.status == null ? null : Maps.convert_from_proxy_string_string(proxy.status);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Tunnel ToProxy()
{
Proxy_Tunnel result_ = new Proxy_Tunnel();
result_.uuid = uuid ?? "";
result_.access_PIF = access_PIF ?? "";
result_.transport_PIF = transport_PIF ?? "";
result_.status = Maps.convert_to_proxy_string_string(status);
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Tunnel from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Tunnel(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Tunnel
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("access_PIF"))
access_PIF = Marshalling.ParseRef<PIF>(table, "access_PIF");
if (table.ContainsKey("transport_PIF"))
transport_PIF = Marshalling.ParseRef<PIF>(table, "transport_PIF");
if (table.ContainsKey("status"))
status = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "status"));
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Tunnel other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._access_PIF, other._access_PIF) &&
Helper.AreEqual2(this._transport_PIF, other._transport_PIF) &&
Helper.AreEqual2(this._status, other._status) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<Tunnel> ProxyArrayToObjectList(Proxy_Tunnel[] input)
{
var result = new List<Tunnel>();
foreach (var item in input)
result.Add(new Tunnel(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Tunnel server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_status, server._status))
{
Tunnel.set_status(session, opaqueRef, _status);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Tunnel.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static Tunnel get_record(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_record(session.opaque_ref, _tunnel);
else
return new Tunnel((Proxy_Tunnel)session.proxy.tunnel_get_record(session.opaque_ref, _tunnel ?? "").parse());
}
/// <summary>
/// Get a reference to the tunnel instance with the specified UUID.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Tunnel> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Tunnel>.Create(session.proxy.tunnel_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static string get_uuid(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_uuid(session.opaque_ref, _tunnel);
else
return (string)session.proxy.tunnel_get_uuid(session.opaque_ref, _tunnel ?? "").parse();
}
/// <summary>
/// Get the access_PIF field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static XenRef<PIF> get_access_PIF(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_access_pif(session.opaque_ref, _tunnel);
else
return XenRef<PIF>.Create(session.proxy.tunnel_get_access_pif(session.opaque_ref, _tunnel ?? "").parse());
}
/// <summary>
/// Get the transport_PIF field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static XenRef<PIF> get_transport_PIF(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_transport_pif(session.opaque_ref, _tunnel);
else
return XenRef<PIF>.Create(session.proxy.tunnel_get_transport_pif(session.opaque_ref, _tunnel ?? "").parse());
}
/// <summary>
/// Get the status field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static Dictionary<string, string> get_status(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_status(session.opaque_ref, _tunnel);
else
return Maps.convert_from_proxy_string_string(session.proxy.tunnel_get_status(session.opaque_ref, _tunnel ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static Dictionary<string, string> get_other_config(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_other_config(session.opaque_ref, _tunnel);
else
return Maps.convert_from_proxy_string_string(session.proxy.tunnel_get_other_config(session.opaque_ref, _tunnel ?? "").parse());
}
/// <summary>
/// Set the status field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_status">New value to set</param>
public static void set_status(Session session, string _tunnel, Dictionary<string, string> _status)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.tunnel_set_status(session.opaque_ref, _tunnel, _status);
else
session.proxy.tunnel_set_status(session.opaque_ref, _tunnel ?? "", Maps.convert_to_proxy_string_string(_status)).parse();
}
/// <summary>
/// Add the given key-value pair to the status field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_status(Session session, string _tunnel, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.tunnel_add_to_status(session.opaque_ref, _tunnel, _key, _value);
else
session.proxy.tunnel_add_to_status(session.opaque_ref, _tunnel ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the status field of the given tunnel. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_status(Session session, string _tunnel, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.tunnel_remove_from_status(session.opaque_ref, _tunnel, _key);
else
session.proxy.tunnel_remove_from_status(session.opaque_ref, _tunnel ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _tunnel, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.tunnel_set_other_config(session.opaque_ref, _tunnel, _other_config);
else
session.proxy.tunnel_set_other_config(session.opaque_ref, _tunnel ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _tunnel, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.tunnel_add_to_other_config(session.opaque_ref, _tunnel, _key, _value);
else
session.proxy.tunnel_add_to_other_config(session.opaque_ref, _tunnel ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given tunnel. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _tunnel, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.tunnel_remove_from_other_config(session.opaque_ref, _tunnel, _key);
else
session.proxy.tunnel_remove_from_other_config(session.opaque_ref, _tunnel ?? "", _key ?? "").parse();
}
/// <summary>
/// Create a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_transport_pif">PIF which receives the tagged traffic</param>
/// <param name="_network">Network to receive the tunnelled traffic</param>
public static XenRef<Tunnel> create(Session session, string _transport_pif, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_create(session.opaque_ref, _transport_pif, _network);
else
return XenRef<Tunnel>.Create(session.proxy.tunnel_create(session.opaque_ref, _transport_pif ?? "", _network ?? "").parse());
}
/// <summary>
/// Create a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_transport_pif">PIF which receives the tagged traffic</param>
/// <param name="_network">Network to receive the tunnelled traffic</param>
public static XenRef<Task> async_create(Session session, string _transport_pif, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_tunnel_create(session.opaque_ref, _transport_pif, _network);
else
return XenRef<Task>.Create(session.proxy.async_tunnel_create(session.opaque_ref, _transport_pif ?? "", _network ?? "").parse());
}
/// <summary>
/// Destroy a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static void destroy(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.tunnel_destroy(session.opaque_ref, _tunnel);
else
session.proxy.tunnel_destroy(session.opaque_ref, _tunnel ?? "").parse();
}
/// <summary>
/// Destroy a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static XenRef<Task> async_destroy(Session session, string _tunnel)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_tunnel_destroy(session.opaque_ref, _tunnel);
else
return XenRef<Task>.Create(session.proxy.async_tunnel_destroy(session.opaque_ref, _tunnel ?? "").parse());
}
/// <summary>
/// Return a list of all the tunnels known to the system.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Tunnel>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_all(session.opaque_ref);
else
return XenRef<Tunnel>.Create(session.proxy.tunnel_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the tunnel Records at once, in a single XML RPC call
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Tunnel>, Tunnel> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.tunnel_get_all_records(session.opaque_ref);
else
return XenRef<Tunnel>.Create<Proxy_Tunnel>(session.proxy.tunnel_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// The interface through which the tunnel is accessed
/// </summary>
[JsonConverter(typeof(XenRefConverter<PIF>))]
public virtual XenRef<PIF> access_PIF
{
get { return _access_PIF; }
set
{
if (!Helper.AreEqual(value, _access_PIF))
{
_access_PIF = value;
Changed = true;
NotifyPropertyChanged("access_PIF");
}
}
}
private XenRef<PIF> _access_PIF = new XenRef<PIF>(Helper.NullOpaqueRef);
/// <summary>
/// The interface used by the tunnel
/// </summary>
[JsonConverter(typeof(XenRefConverter<PIF>))]
public virtual XenRef<PIF> transport_PIF
{
get { return _transport_PIF; }
set
{
if (!Helper.AreEqual(value, _transport_PIF))
{
_transport_PIF = value;
Changed = true;
NotifyPropertyChanged("transport_PIF");
}
}
}
private XenRef<PIF> _transport_PIF = new XenRef<PIF>(Helper.NullOpaqueRef);
/// <summary>
/// Status information about the tunnel
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> status
{
get { return _status; }
set
{
if (!Helper.AreEqual(value, _status))
{
_status = value;
Changed = true;
NotifyPropertyChanged("status");
}
}
}
private Dictionary<string, string> _status = new Dictionary<string, string>() {{"active", "false"}};
/// <summary>
/// Additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
using System.Collections.Generic;
namespace Pathfinding {
using Pathfinding.Util;
/** Represents a collection of GraphNodes.
* It allows for fast lookups of the closest node to a point.
*
* \see https://en.wikipedia.org/wiki/K-d_tree
*/
public class PointKDTree {
// TODO: Make constant
public const int LeafSize = 10;
public const int LeafArraySize = LeafSize*2 + 1;
Node[] tree = new Node[16];
int numNodes = 0;
readonly List<GraphNode> largeList = new List<GraphNode>();
readonly Stack<GraphNode[]> arrayCache = new Stack<GraphNode[]>();
static readonly IComparer<GraphNode>[] comparers = new IComparer<GraphNode>[] { new CompareX(), new CompareY(), new CompareZ() };
struct Node {
/** Nodes in this leaf node (null if not a leaf node) */
public GraphNode[] data;
/** Split point along the #splitAxis if not a leaf node */
public int split;
/** Number of non-null entries in #data */
public ushort count;
/** Axis to split along if not a leaf node (x=0, y=1, z=2) */
public byte splitAxis;
}
// Pretty ugly with one class for each axis, but it has been verified to make the tree around 5% faster
class CompareX : IComparer<GraphNode> {
public int Compare (GraphNode lhs, GraphNode rhs) { return lhs.position.x.CompareTo(rhs.position.x); }
}
class CompareY : IComparer<GraphNode> {
public int Compare (GraphNode lhs, GraphNode rhs) { return lhs.position.y.CompareTo(rhs.position.y); }
}
class CompareZ : IComparer<GraphNode> {
public int Compare (GraphNode lhs, GraphNode rhs) { return lhs.position.z.CompareTo(rhs.position.z); }
}
public PointKDTree() {
tree[1] = new Node { data = GetOrCreateList() };
}
/** Add the node to the tree */
public void Add (GraphNode node) {
numNodes++;
Add(node, 1);
}
/** Rebuild the tree starting with all nodes in the array between index start (inclusive) and end (exclusive) */
public void Rebuild (GraphNode[] nodes, int start, int end) {
if (start < 0 || end < start || end > nodes.Length)
throw new System.ArgumentException();
for (int i = 0; i < tree.Length; i++) {
var data = tree[i].data;
if (data != null) {
for (int j = 0; j < LeafArraySize; j++) data[j] = null;
arrayCache.Push(data);
tree[i].data = null;
}
}
numNodes = end - start;
Build(1, new List<GraphNode>(nodes), start, end);
}
GraphNode[] GetOrCreateList () {
// Note, the lists will never become larger than this initial capacity, so possibly they should be replaced by arrays
return arrayCache.Count > 0 ? arrayCache.Pop() : new GraphNode[LeafArraySize];
}
int Size (int index) {
return tree[index].data != null ? tree[index].count : Size(2 * index) + Size(2 * index + 1);
}
void CollectAndClear (int index, List<GraphNode> buffer) {
var nodes = tree[index].data;
var count = tree[index].count;
if (nodes != null) {
tree[index] = new Node();
for (int i = 0; i < count; i++) {
buffer.Add(nodes[i]);
nodes[i] = null;
}
arrayCache.Push(nodes);
} else {
CollectAndClear(index*2, buffer);
CollectAndClear(index*2 + 1, buffer);
}
}
static int MaxAllowedSize (int numNodes, int depth) {
// Allow a node to be 2.5 times as full as it should ideally be
// but do not allow it to contain more than 3/4ths of the total number of nodes
// (important to make sure nodes near the top of the tree also get rebalanced).
// A node should ideally contain numNodes/(2^depth) nodes below it (^ is exponentiation, not xor)
return System.Math.Min(((5 * numNodes) / 2) >> depth, (3 * numNodes) / 4);
}
void Rebalance (int index) {
CollectAndClear(index, largeList);
Build(index, largeList, 0, largeList.Count);
largeList.ClearFast();
}
void EnsureSize (int index) {
if (index >= tree.Length) {
var newLeaves = new Node[System.Math.Max(index + 1, tree.Length*2)];
tree.CopyTo(newLeaves, 0);
tree = newLeaves;
}
}
void Build (int index, List<GraphNode> nodes, int start, int end) {
EnsureSize(index);
if (end - start <= LeafSize) {
var leafData = tree[index].data = GetOrCreateList();
tree[index].count = (ushort)(end - start);
for (int i = start; i < end; i++)
leafData[i - start] = nodes[i];
} else {
Int3 mn, mx;
mn = mx = nodes[start].position;
for (int i = start; i < end; i++) {
var p = nodes[i].position;
mn = new Int3(System.Math.Min(mn.x, p.x), System.Math.Min(mn.y, p.y), System.Math.Min(mn.z, p.z));
mx = new Int3(System.Math.Max(mx.x, p.x), System.Math.Max(mx.y, p.y), System.Math.Max(mx.z, p.z));
}
Int3 diff = mx - mn;
var axis = diff.x > diff.y ? (diff.x > diff.z ? 0 : 2) : (diff.y > diff.z ? 1 : 2);
nodes.Sort(start, end - start, comparers[axis]);
int mid = (start+end)/2;
tree[index].split = (nodes[mid-1].position[axis] + nodes[mid].position[axis] + 1)/2;
tree[index].splitAxis = (byte)axis;
Build(index*2 + 0, nodes, start, mid);
Build(index*2 + 1, nodes, mid, end);
}
}
void Add (GraphNode point, int index, int depth = 0) {
// Move down in the tree until the leaf node is found that this point is inside of
while (tree[index].data == null) {
index = 2 * index + (point.position[tree[index].splitAxis] < tree[index].split ? 0 : 1);
depth++;
}
// Add the point to the leaf node
tree[index].data[tree[index].count++] = point;
// Check if the leaf node is large enough that we need to do some rebalancing
if (tree[index].count >= LeafArraySize) {
int levelsUp = 0;
// Search upwards for nodes that are too large and should be rebalanced
// Rebalance the node above the node that had a too large size so that it can
// move children over to the sibling
while (depth - levelsUp > 0 && Size(index >> levelsUp) > MaxAllowedSize(numNodes, depth-levelsUp)) {
levelsUp++;
}
Rebalance(index >> levelsUp);
}
}
/** Closest node to the point which satisfies the constraint */
public GraphNode GetNearest (Int3 point, NNConstraint constraint) {
GraphNode best = null;
long bestSqrDist = long.MaxValue;
GetNearestInternal(1, point, constraint, ref best, ref bestSqrDist);
return best;
}
void GetNearestInternal (int index, Int3 point, NNConstraint constraint, ref GraphNode best, ref long bestSqrDist) {
var data = tree[index].data;
if (data != null) {
for (int i = tree[index].count - 1; i >= 0; i--) {
var dist = (data[i].position - point).sqrMagnitudeLong;
if (dist < bestSqrDist && (constraint == null || constraint.Suitable(data[i]))) {
bestSqrDist = dist;
best = data[i];
}
}
} else {
var dist = (long)(point[tree[index].splitAxis] - tree[index].split);
var childIndex = 2 * index + (dist < 0 ? 0 : 1);
GetNearestInternal(childIndex, point, constraint, ref best, ref bestSqrDist);
// Try the other one if it is possible to find a valid node on the other side
if (dist*dist < bestSqrDist) {
// childIndex ^ 1 will flip the last bit, so if childIndex is odd, then childIndex ^ 1 will be even
GetNearestInternal(childIndex ^ 0x1, point, constraint, ref best, ref bestSqrDist);
}
}
}
/** Add all nodes within a squared distance of the point to the buffer.
* \param point Nodes around this point will be added to the \a buffer.
* \param sqrRadius squared maximum distance in Int3 space. If you are converting from world space you will need to multiply by Int3.Precision:
* \code var sqrRadius = (worldSpaceRadius * Int3.Precision) * (worldSpaceRadius * Int3.Precision); \endcode
* \param buffer All nodes will be added to this list.
*/
public void GetInRange (Int3 point, long sqrRadius, List<GraphNode> buffer) {
GetInRangeInternal(1, point, sqrRadius, buffer);
}
void GetInRangeInternal (int index, Int3 point, long sqrRadius, List<GraphNode> buffer) {
var data = tree[index].data;
if (data != null) {
for (int i = tree[index].count - 1; i >= 0; i--) {
var dist = (data[i].position - point).sqrMagnitudeLong;
if (dist < sqrRadius) {
buffer.Add(data[i]);
}
}
} else {
var dist = (long)(point[tree[index].splitAxis] - tree[index].split);
// Pick the first child to enter based on which side of the splitting line the point is
var childIndex = 2 * index + (dist < 0 ? 0 : 1);
GetInRangeInternal(childIndex, point, sqrRadius, buffer);
// Try the other one if it is possible to find a valid node on the other side
if (dist*dist < sqrRadius) {
// childIndex ^ 1 will flip the last bit, so if childIndex is odd, then childIndex ^ 1 will be even
GetInRangeInternal(childIndex ^ 0x1, point, sqrRadius, buffer);
}
}
}
}
}
| |
using System;
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Migrations.Initial;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Services;
namespace Umbraco.Core.Persistence
{
public class DatabaseSchemaHelper
{
private readonly Database _db;
private readonly ILogger _logger;
private readonly ISqlSyntaxProvider _syntaxProvider;
private readonly BaseDataCreation _baseDataCreation;
public DatabaseSchemaHelper(Database db, ILogger logger, ISqlSyntaxProvider syntaxProvider)
{
_db = db;
_logger = logger;
_syntaxProvider = syntaxProvider;
_baseDataCreation = new BaseDataCreation(db, logger);
}
public bool TableExist(string tableName)
{
return _syntaxProvider.DoesTableExist(_db, tableName);
}
internal void UninstallDatabaseSchema()
{
var creation = new DatabaseSchemaCreation(_db, _logger, _syntaxProvider);
creation.UninstallDatabaseSchema();
}
/// <summary>
/// Creates the Umbraco db schema in the Database of the current Database.
/// Safe method that is only able to create the schema in non-configured
/// umbraco instances.
/// </summary>
public void CreateDatabaseSchema(ApplicationContext applicationContext)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
CreateDatabaseSchema(true, applicationContext);
}
/// <summary>
/// Creates the Umbraco db schema in the Database of the current Database
/// with the option to guard the db from having the schema created
/// multiple times.
/// </summary>
/// <param name="guardConfiguration"></param>
/// <param name="applicationContext"></param>
public void CreateDatabaseSchema(bool guardConfiguration, ApplicationContext applicationContext)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
if (guardConfiguration && applicationContext.IsConfigured)
throw new Exception("Umbraco is already configured!");
CreateDatabaseSchemaDo(applicationContext.Services.MigrationEntryService);
}
internal void CreateDatabaseSchemaDo(bool guardConfiguration, ApplicationContext applicationContext)
{
if (guardConfiguration && applicationContext.IsConfigured)
throw new Exception("Umbraco is already configured!");
CreateDatabaseSchemaDo(applicationContext.Services.MigrationEntryService);
}
internal void CreateDatabaseSchemaDo(IMigrationEntryService migrationEntryService)
{
_logger.Info<Database>("Initializing database schema creation");
var creation = new DatabaseSchemaCreation(_db, _logger, _syntaxProvider);
creation.InitializeDatabaseSchema();
_logger.Info<Database>("Finalized database schema creation");
}
public void CreateTable<T>(bool overwrite)
where T : new()
{
var tableType = typeof(T);
CreateTable(overwrite, tableType);
}
public void CreateTable<T>()
where T : new()
{
var tableType = typeof(T);
CreateTable(false, tableType);
}
public void CreateTable(bool overwrite, Type modelType)
{
var tableDefinition = DefinitionFactory.GetTableDefinition(modelType);
var tableName = tableDefinition.Name;
string createSql = _syntaxProvider.Format(tableDefinition);
string createPrimaryKeySql = _syntaxProvider.FormatPrimaryKey(tableDefinition);
var foreignSql = _syntaxProvider.Format(tableDefinition.ForeignKeys);
var indexSql = _syntaxProvider.Format(tableDefinition.Indexes);
var tableExist = _db.TableExist(tableName);
if (overwrite && tableExist)
{
_db.DropTable(tableName);
tableExist = false;
}
if (tableExist == false)
{
using (var transaction = _db.GetTransaction())
{
//Execute the Create Table sql
int created = _db.Execute(new Sql(createSql));
_logger.Info<Database>(string.Format("Create Table sql {0}:\n {1}", created, createSql));
//If any statements exists for the primary key execute them here
if (!string.IsNullOrEmpty(createPrimaryKeySql))
{
int createdPk = _db.Execute(new Sql(createPrimaryKeySql));
_logger.Info<Database>(string.Format("Primary Key sql {0}:\n {1}", createdPk, createPrimaryKeySql));
}
//Turn on identity insert if db provider is not mysql
if (_syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
_db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", _syntaxProvider.GetQuotedTableName(tableName))));
//Call the NewTable-event to trigger the insert of base/default data
//OnNewTable(tableName, _db, e, _logger);
_baseDataCreation.InitializeBaseData(tableName);
//Turn off identity insert if db provider is not mysql
if (_syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
_db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF;", _syntaxProvider.GetQuotedTableName(tableName))));
//Special case for MySql
if (_syntaxProvider is MySqlSyntaxProvider && tableName.Equals("umbracoUser"))
{
_db.Update<UserDto>("SET id = @IdAfter WHERE id = @IdBefore AND userLogin = @Login", new { IdAfter = 0, IdBefore = 1, Login = "admin" });
}
if (_syntaxProvider is PostgreSyntaxProvider && tableDefinition.Columns.Any(x => x.IsIdentity))
{
var column = tableDefinition.Columns.First(x => x.IsIdentity).Name;
_db.Execute(new Sql(string.Format("select setval(pg_get_serial_sequence({0}, {1}), (select max({3}) + 1 from {2}));",
_syntaxProvider.GetQuotedValue(tableName),
_syntaxProvider.GetQuotedValue(column),
_syntaxProvider.GetQuotedTableName(tableName),
_syntaxProvider.GetQuotedColumnName(column))));
_logger.Info<Database>(string.Format("resequenced {0} ", _syntaxProvider.GetQuotedTableName(tableName)));
}
//Loop through index statements and execute sql
foreach (var sql in indexSql)
{
int createdIndex = _db.Execute(new Sql(sql));
_logger.Info<Database>(string.Format("Create Index sql {0}:\n {1}", createdIndex, sql));
}
//Loop through foreignkey statements and execute sql
foreach (var sql in foreignSql)
{
int createdFk = _db.Execute(new Sql(sql));
_logger.Info<Database>(string.Format("Create Foreign Key sql {0}:\n {1}", createdFk, sql));
}
transaction.Complete();
}
}
_logger.Info<Database>(string.Format("New table '{0}' was created", tableName));
}
public void DropTable<T>()
where T : new()
{
Type type = typeof(T);
var tableNameAttribute = type.FirstAttribute<TableNameAttribute>();
if (tableNameAttribute == null)
throw new Exception(
string.Format(
"The Type '{0}' does not contain a TableNameAttribute, which is used to find the name of the table to drop. The operation could not be completed.",
type.Name));
string tableName = tableNameAttribute.Value;
DropTable(tableName);
}
public void DropTable(string tableName)
{
var sql = new Sql(string.Format(
_syntaxProvider.DropTable,
_syntaxProvider.GetQuotedTableName(tableName)));
_db.Execute(sql);
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
// Some utility functions for compiling and checking errors.
public abstract class CompilingTestBase : CSharpTestBase
{
private const string DefaultTypeName = "C";
private const string DefaultMethodName = "M";
internal static BoundBlock ParseAndBindMethodBody(string program, string typeName = DefaultTypeName, string methodName = DefaultMethodName)
{
var compilation = CreateStandardCompilation(program);
var method = (MethodSymbol)compilation.GlobalNamespace.GetTypeMembers(typeName).Single().GetMembers(methodName).Single();
// Provide an Emit.Module so that the lowering passes will be run
var module = new PEAssemblyBuilder(
(SourceAssemblySymbol)compilation.Assembly,
emitOptions: EmitOptions.Default,
outputKind: OutputKind.ConsoleApplication,
serializationProperties: GetDefaultModulePropertiesForSerialization(),
manifestResources: Enumerable.Empty<ResourceDescription>());
TypeCompilationState compilationState = new TypeCompilationState(method.ContainingType, compilation, module);
var diagnostics = DiagnosticBag.GetInstance();
var block = MethodCompiler.BindMethodBody(method, compilationState, diagnostics);
diagnostics.Free();
return block;
}
public static string DumpDiagnostic(Diagnostic diagnostic)
{
return string.Format("'{0}' {1}",
diagnostic.Location.SourceTree.GetText().ToString(diagnostic.Location.SourceSpan),
DiagnosticFormatter.Instance.Format(diagnostic.WithLocation(Location.None), EnsureEnglishUICulture.PreferredOrNull));
}
[Obsolete("Use VerifyDiagnostics", true)]
public static void TestDiagnostics(IEnumerable<Diagnostic> diagnostics, params string[] diagStrings)
{
AssertEx.SetEqual(diagStrings, diagnostics.Select(DumpDiagnostic));
}
// Do a full compilation and check all the errors.
[Obsolete("Use VerifyDiagnostics", true)]
public void TestAllErrors(string code, params string[] errors)
{
var compilation = CreateStandardCompilation(code);
var diagnostics = compilation.GetDiagnostics();
AssertEx.SetEqual(errors, diagnostics.Select(DumpDiagnostic));
}
// Tests just the errors found while binding method M in class C.
[Obsolete("Use VerifyDiagnostics", true)]
public void TestErrors(string code, params string[] errors)
{
var compilation = CreateStandardCompilation(code);
var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
var factory = compilation.GetBinderFactory(method.SyntaxTree);
var bodyBlock = (BlockSyntax)method.BodySyntax;
var parameterBinderContext = factory.GetBinder(bodyBlock);
var binder = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext);
var diagnostics = new DiagnosticBag();
var block = binder.BindEmbeddedBlock(bodyBlock, diagnostics);
AssertEx.SetEqual(errors, diagnostics.AsEnumerable().Select(DumpDiagnostic));
}
[Obsolete("Use VerifyDiagnostics", true)]
public void TestWarnings(string code, params string[] expectedWarnings)
{
var compilation = CreateStandardCompilation(code);
var method = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
var factory = compilation.GetBinderFactory(method.SyntaxTree);
var bodyBlock = (BlockSyntax)method.BodySyntax;
var parameterBinderContext = factory.GetBinder(bodyBlock);
var binder = new ExecutableCodeBinder(bodyBlock.Parent, method, parameterBinderContext);
var block = binder.BindEmbeddedBlock(bodyBlock, new DiagnosticBag());
var actualWarnings = new DiagnosticBag();
DiagnosticsPass.IssueDiagnostics(compilation, block, actualWarnings, method);
AssertEx.SetEqual(expectedWarnings, actualWarnings.AsEnumerable().Select(DumpDiagnostic));
}
public const string LINQ =
#region the string LINQ defines a complete LINQ API called List1<T> (for instance method) and List2<T> (for extension methods)
@"using System;
using System.Text;
public delegate R Func1<in T1, out R>(T1 arg1);
public delegate R Func1<in T1, in T2, out R>(T1 arg1, T2 arg2);
public class List1<T>
{
internal T[] data;
internal int length;
public List1(params T[] args)
{
this.data = (T[])args.Clone();
this.length = data.Length;
}
public List1()
{
this.data = new T[0];
this.length = 0;
}
public int Length { get { return length; } }
//public T this[int index] { get { return this.data[index]; } }
public T Get(int index) { return this.data[index]; }
public virtual void Add(T t)
{
if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1);
data[length++] = t;
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append('[');
for (int i = 0; i < Length; i++)
{
if (i != 0) builder.Append(',').Append(' ');
builder.Append(data[i]);
}
builder.Append(']');
return builder.ToString();
}
public List1<E> Cast<E>()
{
E[] data = new E[Length];
for (int i = 0; i < Length; i++)
data[i] = (E)(object)this.data[i];
return new List1<E>(data);
}
public List1<T> Where(Func1<T, bool> predicate)
{
List1<T> result = new List1<T>();
for (int i = 0; i < Length; i++)
{
T datum = this.data[i];
if (predicate(datum)) result.Add(datum);
}
return result;
}
public List1<U> Select<U>(Func1<T, U> selector)
{
int length = this.Length;
U[] data = new U[length];
for (int i = 0; i < length; i++) data[i] = selector(this.data[i]);
return new List1<U>(data);
}
public List1<V> SelectMany<U, V>(Func1<T, List1<U>> selector, Func1<T, U, V> resultSelector)
{
List1<V> result = new List1<V>();
int length = this.Length;
for (int i = 0; i < length; i++)
{
T t = this.data[i];
List1<U> selected = selector(t);
int ulength = selected.Length;
for (int j = 0; j < ulength; j++)
{
U u = selected.data[j];
V v = resultSelector(t, u);
result.Add(v);
}
}
return result;
}
public List1<V> Join<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector,
Func1<U, K> innerKeyselector, Func1<T, U, V> resultSelector)
{
List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>();
for (int i = 0; i < Length; i++)
{
T t = this.Get(i);
K k = outerKeyselector(t);
Joined<K, T, U> row = null;
for (int j = 0; j < joined.Length; j++)
{
if (joined.Get(j).k.Equals(k))
{
row = joined.Get(j);
break;
}
}
if (row == null) joined.Add(row = new Joined<K, T, U>(k));
row.t.Add(t);
}
for (int i = 0; i < inner.Length; i++)
{
U u = inner.Get(i);
K k = innerKeyselector(u);
Joined<K, T, U> row = null;
for (int j = 0; j < joined.Length; j++)
{
if (joined.Get(j).k.Equals(k))
{
row = joined.Get(j);
break;
}
}
if (row == null) joined.Add(row = new Joined<K, T, U>(k));
row.u.Add(u);
}
List1<V> result = new List1<V>();
for (int i = 0; i < joined.Length; i++)
{
Joined<K, T, U> row = joined.Get(i);
for (int j = 0; j < row.t.Length; j++)
{
T t = row.t.Get(j);
for (int k = 0; k < row.u.Length; k++)
{
U u = row.u.Get(k);
V v = resultSelector(t, u);
result.Add(v);
}
}
}
return result;
}
class Joined<K, T2, U>
{
public Joined(K k)
{
this.k = k;
this.t = new List1<T2>();
this.u = new List1<U>();
}
public readonly K k;
public readonly List1<T2> t;
public readonly List1<U> u;
}
public List1<V> GroupJoin<U, K, V>(List1<U> inner, Func1<T, K> outerKeyselector,
Func1<U, K> innerKeyselector, Func1<T, List1<U>, V> resultSelector)
{
List1<Joined<K, T, U>> joined = new List1<Joined<K, T, U>>();
for (int i = 0; i < Length; i++)
{
T t = this.Get(i);
K k = outerKeyselector(t);
Joined<K, T, U> row = null;
for (int j = 0; j < joined.Length; j++)
{
if (joined.Get(j).k.Equals(k))
{
row = joined.Get(j);
break;
}
}
if (row == null) joined.Add(row = new Joined<K, T, U>(k));
row.t.Add(t);
}
for (int i = 0; i < inner.Length; i++)
{
U u = inner.Get(i);
K k = innerKeyselector(u);
Joined<K, T, U> row = null;
for (int j = 0; j < joined.Length; j++)
{
if (joined.Get(j).k.Equals(k))
{
row = joined.Get(j);
break;
}
}
if (row == null) joined.Add(row = new Joined<K, T, U>(k));
row.u.Add(u);
}
List1<V> result = new List1<V>();
for (int i = 0; i < joined.Length; i++)
{
Joined<K, T, U> row = joined.Get(i);
for (int j = 0; j < row.t.Length; j++)
{
T t = row.t.Get(j);
V v = resultSelector(t, row.u);
result.Add(v);
}
}
return result;
}
public OrderedList1<T> OrderBy<K>(Func1<T, K> Keyselector)
{
OrderedList1<T> result = new OrderedList1<T>(this);
result.ThenBy(Keyselector);
return result;
}
public OrderedList1<T> OrderByDescending<K>(Func1<T, K> Keyselector)
{
OrderedList1<T> result = new OrderedList1<T>(this);
result.ThenByDescending(Keyselector);
return result;
}
public List1<Group1<K, T>> GroupBy<K>(Func1<T, K> Keyselector)
{
List1<Group1<K, T>> result = new List1<Group1<K, T>>();
for (int i = 0; i < Length; i++)
{
T t = this.Get(i);
K k = Keyselector(t);
Group1<K, T> Group1 = null;
for (int j = 0; j < result.Length; j++)
{
if (result.Get(j).Key.Equals(k))
{
Group1 = result.Get(j);
break;
}
}
if (Group1 == null)
{
result.Add(Group1 = new Group1<K, T>(k));
}
Group1.Add(t);
}
return result;
}
public List1<Group1<K, E>> GroupBy<K, E>(Func1<T, K> Keyselector,
Func1<T, E> elementSelector)
{
List1<Group1<K, E>> result = new List1<Group1<K, E>>();
for (int i = 0; i < Length; i++)
{
T t = this.Get(i);
K k = Keyselector(t);
Group1<K, E> Group1 = null;
for (int j = 0; j < result.Length; j++)
{
if (result.Get(j).Key.Equals(k))
{
Group1 = result.Get(j);
break;
}
}
if (Group1 == null)
{
result.Add(Group1 = new Group1<K, E>(k));
}
Group1.Add(elementSelector(t));
}
return result;
}
}
public class OrderedList1<T> : List1<T>
{
private List1<Keys1> Keys1;
public override void Add(T t)
{
throw new NotSupportedException();
}
internal OrderedList1(List1<T> list)
{
Keys1 = new List1<Keys1>();
for (int i = 0; i < list.Length; i++)
{
base.Add(list.Get(i));
Keys1.Add(new Keys1());
}
}
public OrderedList1<T> ThenBy<K>(Func1<T, K> Keyselector)
{
for (int i = 0; i < Length; i++)
{
object o = Keyselector(this.Get(i)); // work around bug 8405
Keys1.Get(i).Add((IComparable)o);
}
Sort();
return this;
}
class ReverseOrder : IComparable
{
IComparable c;
public ReverseOrder(IComparable c)
{
this.c = c;
}
public int CompareTo(object o)
{
ReverseOrder other = (ReverseOrder)o;
return other.c.CompareTo(this.c);
}
public override string ToString()
{
return String.Empty + '-' + c;
}
}
public OrderedList1<T> ThenByDescending<K>(Func1<T, K> Keyselector)
{
for (int i = 0; i < Length; i++)
{
object o = Keyselector(this.Get(i)); // work around bug 8405
Keys1.Get(i).Add(new ReverseOrder((IComparable)o));
}
Sort();
return this;
}
void Sort()
{
Array.Sort(this.Keys1.data, this.data, 0, Length);
}
}
class Keys1 : List1<IComparable>, IComparable
{
public int CompareTo(object o)
{
Keys1 other = (Keys1)o;
for (int i = 0; i < Length; i++)
{
int c = this.Get(i).CompareTo(other.Get(i));
if (c != 0) return c;
}
return 0;
}
}
public class Group1<K, T> : List1<T>
{
public Group1(K k, params T[] data)
: base(data)
{
this.Key = k;
}
public K Key { get; private set; }
public override string ToString()
{
return Key + String.Empty + ':' + base.ToString();
}
}
//public delegate R Func2<in T1, out R>(T1 arg1);
//public delegate R Func2<in T1, in T2, out R>(T1 arg1, T2 arg2);
//
//public class List2<T>
//{
// internal T[] data;
// internal int length;
//
// public List2(params T[] args)
// {
// this.data = (T[])args.Clone();
// this.length = data.Length;
// }
//
// public List2()
// {
// this.data = new T[0];
// this.length = 0;
// }
//
// public int Length { get { return length; } }
//
// //public T this[int index] { get { return this.data[index]; } }
// public T Get(int index) { return this.data[index]; }
//
// public virtual void Add(T t)
// {
// if (data.Length == length) Array.Resize(ref data, data.Length * 2 + 1);
// data[length++] = t;
// }
//
// public override string ToString()
// {
// StringBuilder builder = new StringBuilder();
// builder.Append('[');
// for (int i = 0; i < Length; i++)
// {
// if (i != 0) builder.Append(',').Append(' ');
// builder.Append(data[i]);
// }
// builder.Append(']');
// return builder.ToString();
// }
//
//}
//
//public class OrderedList2<T> : List2<T>
//{
// internal List2<Keys2> Keys2;
//
// public override void Add(T t)
// {
// throw new NotSupportedException();
// }
//
// internal OrderedList2(List2<T> list)
// {
// Keys2 = new List2<Keys2>();
// for (int i = 0; i < list.Length; i++)
// {
// base.Add(list.Get(i));
// Keys2.Add(new Keys2());
// }
// }
//
// internal void Sort()
// {
// Array.Sort(this.Keys2.data, this.data, 0, Length);
// }
//}
//
//class Keys2 : List2<IComparable>, IComparable
//{
// public int CompareTo(object o)
// {
// Keys2 other = (Keys2)o;
// for (int i = 0; i < Length; i++)
// {
// int c = this.Get(i).CompareTo(other.Get(i));
// if (c != 0) return c;
// }
// return 0;
// }
//}
//
//public class Group2<K, T> : List2<T>
//{
// public Group2(K k, params T[] data)
// : base(data)
// {
// this.Key = k;
// }
//
// public K Key { get; private set; }
//
// public override string ToString()
// {
// return Key + String.Empty + ':' + base.ToString();
// }
//}
//
//public static class Extensions2
//{
//
// public static List2<E> Cast<T, E>(this List2<T> _this)
// {
// E[] data = new E[_this.Length];
// for (int i = 0; i < _this.Length; i++)
// data[i] = (E)(object)_this.data[i];
// return new List2<E>(data);
// }
//
// public static List2<T> Where<T>(this List2<T> _this, Func2<T, bool> predicate)
// {
// List2<T> result = new List2<T>();
// for (int i = 0; i < _this.Length; i++)
// {
// T datum = _this.data[i];
// if (predicate(datum)) result.Add(datum);
// }
// return result;
// }
//
// public static List2<U> Select<T,U>(this List2<T> _this, Func2<T, U> selector)
// {
// int length = _this.Length;
// U[] data = new U[length];
// for (int i = 0; i < length; i++) data[i] = selector(_this.data[i]);
// return new List2<U>(data);
// }
//
// public static List2<V> SelectMany<T, U, V>(this List2<T> _this, Func2<T, List2<U>> selector, Func2<T, U, V> resultSelector)
// {
// List2<V> result = new List2<V>();
// int length = _this.Length;
// for (int i = 0; i < length; i++)
// {
// T t = _this.data[i];
// List2<U> selected = selector(t);
// int ulength = selected.Length;
// for (int j = 0; j < ulength; j++)
// {
// U u = selected.data[j];
// V v = resultSelector(t, u);
// result.Add(v);
// }
// }
//
// return result;
// }
//
// public static List2<V> Join<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector,
// Func2<U, K> innerKeyselector, Func2<T, U, V> resultSelector)
// {
// List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>();
// for (int i = 0; i < _this.Length; i++)
// {
// T t = _this.Get(i);
// K k = outerKeyselector(t);
// Joined<K, T, U> row = null;
// for (int j = 0; j < joined.Length; j++)
// {
// if (joined.Get(j).k.Equals(k))
// {
// row = joined.Get(j);
// break;
// }
// }
// if (row == null) joined.Add(row = new Joined<K, T, U>(k));
// row.t.Add(t);
// }
// for (int i = 0; i < inner.Length; i++)
// {
// U u = inner.Get(i);
// K k = innerKeyselector(u);
// Joined<K, T, U> row = null;
// for (int j = 0; j < joined.Length; j++)
// {
// if (joined.Get(j).k.Equals(k))
// {
// row = joined.Get(j);
// break;
// }
// }
// if (row == null) joined.Add(row = new Joined<K, T, U>(k));
// row.u.Add(u);
// }
// List2<V> result = new List2<V>();
// for (int i = 0; i < joined.Length; i++)
// {
// Joined<K, T, U> row = joined.Get(i);
// for (int j = 0; j < row.t.Length; j++)
// {
// T t = row.t.Get(j);
// for (int k = 0; k < row.u.Length; k++)
// {
// U u = row.u.Get(k);
// V v = resultSelector(t, u);
// result.Add(v);
// }
// }
// }
// return result;
// }
//
// class Joined<K, T2, U>
// {
// public Joined(K k)
// {
// this.k = k;
// this.t = new List2<T2>();
// this.u = new List2<U>();
// }
// public readonly K k;
// public readonly List2<T2> t;
// public readonly List2<U> u;
// }
//
// public static List2<V> GroupJoin<T, U, K, V>(this List2<T> _this, List2<U> inner, Func2<T, K> outerKeyselector,
// Func2<U, K> innerKeyselector, Func2<T, List2<U>, V> resultSelector)
// {
// List2<Joined<K, T, U>> joined = new List2<Joined<K, T, U>>();
// for (int i = 0; i < _this.Length; i++)
// {
// T t = _this.Get(i);
// K k = outerKeyselector(t);
// Joined<K, T, U> row = null;
// for (int j = 0; j < joined.Length; j++)
// {
// if (joined.Get(j).k.Equals(k))
// {
// row = joined.Get(j);
// break;
// }
// }
// if (row == null) joined.Add(row = new Joined<K, T, U>(k));
// row.t.Add(t);
// }
// for (int i = 0; i < inner.Length; i++)
// {
// U u = inner.Get(i);
// K k = innerKeyselector(u);
// Joined<K, T, U> row = null;
// for (int j = 0; j < joined.Length; j++)
// {
// if (joined.Get(j).k.Equals(k))
// {
// row = joined.Get(j);
// break;
// }
// }
// if (row == null) joined.Add(row = new Joined<K, T, U>(k));
// row.u.Add(u);
// }
// List2<V> result = new List2<V>();
// for (int i = 0; i < joined.Length; i++)
// {
// Joined<K, T, U> row = joined.Get(i);
// for (int j = 0; j < row.t.Length; j++)
// {
// T t = row.t.Get(j);
// V v = resultSelector(t, row.u);
// result.Add(v);
// }
// }
// return result;
// }
//
// public static OrderedList2<T> OrderBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector)
// {
// OrderedList2<T> result = new OrderedList2<T>(_this);
// result.ThenBy(Keyselector);
// return result;
// }
//
// public static OrderedList2<T> OrderByDescending<T, K>(this List2<T> _this, Func2<T, K> Keyselector)
// {
// OrderedList2<T> result = new OrderedList2<T>(_this);
// result.ThenByDescending(Keyselector);
// return result;
// }
//
// public static List2<Group2<K, T>> GroupBy<T, K>(this List2<T> _this, Func2<T, K> Keyselector)
// {
// List2<Group2<K, T>> result = new List2<Group2<K, T>>();
// for (int i = 0; i < _this.Length; i++)
// {
// T t = _this.Get(i);
// K k = Keyselector(t);
// Group2<K, T> Group2 = null;
// for (int j = 0; j < result.Length; j++)
// {
// if (result.Get(j).Key.Equals(k))
// {
// Group2 = result.Get(j);
// break;
// }
// }
// if (Group2 == null)
// {
// result.Add(Group2 = new Group2<K, T>(k));
// }
// Group2.Add(t);
// }
// return result;
// }
//
// public static List2<Group2<K, E>> GroupBy<T, K, E>(this List2<T> _this, Func2<T, K> Keyselector,
// Func2<T, E> elementSelector)
// {
// List2<Group2<K, E>> result = new List2<Group2<K, E>>();
// for (int i = 0; i < _this.Length; i++)
// {
// T t = _this.Get(i);
// K k = Keyselector(t);
// Group2<K, E> Group2 = null;
// for (int j = 0; j < result.Length; j++)
// {
// if (result.Get(j).Key.Equals(k))
// {
// Group2 = result.Get(j);
// break;
// }
// }
// if (Group2 == null)
// {
// result.Add(Group2 = new Group2<K, E>(k));
// }
// Group2.Add(elementSelector(t));
// }
// return result;
// }
//
// public static OrderedList2<T> ThenBy<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector)
// {
// for (int i = 0; i < _this.Length; i++)
// {
// object o = Keyselector(_this.Get(i)); // work around bug 8405
// _this.Keys2.Get(i).Add((IComparable)o);
// }
// _this.Sort();
// return _this;
// }
//
// class ReverseOrder : IComparable
// {
// IComparable c;
// public ReverseOrder(IComparable c)
// {
// this.c = c;
// }
// public int CompareTo(object o)
// {
// ReverseOrder other = (ReverseOrder)o;
// return other.c.CompareTo(this.c);
// }
// public override string ToString()
// {
// return String.Empty + '-' + c;
// }
// }
//
// public static OrderedList2<T> ThenByDescending<T, K>(this OrderedList2<T> _this, Func2<T, K> Keyselector)
// {
// for (int i = 0; i < _this.Length; i++)
// {
// object o = Keyselector(_this.Get(i)); // work around bug 8405
// _this.Keys2.Get(i).Add(new ReverseOrder((IComparable)o));
// }
// _this.Sort();
// return _this;
// }
//
//}
"
#endregion the string LINQ
;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
public static class CharTests
{
[Fact]
public static void TestCompareTo()
{
// Int32 Char.CompareTo(Char)
char h = 'h';
Assert.True(h.CompareTo('h') == 0);
Assert.True(h.CompareTo('a') > 0);
Assert.True(h.CompareTo('z') < 0);
}
[Fact]
public static void TestSystemIComparableCompareTo()
{
// Int32 Char.System.IComparable.CompareTo(Object)
IComparable h = 'h';
Assert.True(h.CompareTo('h') == 0);
Assert.True(h.CompareTo('a') > 0);
Assert.True(h.CompareTo('z') < 0);
Assert.True(h.CompareTo(null) > 0);
Assert.Throws<ArgumentException>(() => h.CompareTo("H"));
}
private static void ValidateConvertFromUtf32(int i, string expected)
{
try
{
string s = char.ConvertFromUtf32(i);
Assert.Equal(expected, s);
}
catch (ArgumentOutOfRangeException)
{
Assert.True(expected == null, "Expected an ArgumentOutOfRangeException");
}
}
[Fact]
public static void TestConvertFromUtf32()
{
// String Char.ConvertFromUtf32(Int32)
ValidateConvertFromUtf32(0x10000, "\uD800\uDC00");
ValidateConvertFromUtf32(0x103FF, "\uD800\uDFFF");
ValidateConvertFromUtf32(0xFFFFF, "\uDBBF\uDFFF");
ValidateConvertFromUtf32(0x10FC00, "\uDBFF\uDC00");
ValidateConvertFromUtf32(0x10FFFF, "\uDBFF\uDFFF");
ValidateConvertFromUtf32(0, "\0");
ValidateConvertFromUtf32(0x3FF, "\u03FF");
ValidateConvertFromUtf32(0xE000, "\uE000");
ValidateConvertFromUtf32(0xFFFF, "\uFFFF");
ValidateConvertFromUtf32(0xD800, null);
ValidateConvertFromUtf32(0xDC00, null);
ValidateConvertFromUtf32(0xDFFF, null);
ValidateConvertFromUtf32(0x110000, null);
ValidateConvertFromUtf32(-1, null);
ValidateConvertFromUtf32(Int32.MaxValue, null);
ValidateConvertFromUtf32(Int32.MinValue, null);
}
private static void ValidateconverToUtf32<T>(string s, int i, int expected) where T : Exception
{
try
{
int result = char.ConvertToUtf32(s, i);
Assert.Equal(result, expected);
}
catch (T)
{
Assert.True(expected == Int32.MinValue, "Expected an exception to be thrown");
}
}
[Fact]
public static void TestConvertToUtf32StrInt()
{
// Int32 Char.ConvertToUtf32(String, Int32)
ValidateconverToUtf32<Exception>("\uD800\uDC00", 0, 0x10000);
ValidateconverToUtf32<Exception>("\uD800\uD800\uDFFF", 1, 0x103FF);
ValidateconverToUtf32<Exception>("\uDBBF\uDFFF", 0, 0xFFFFF);
ValidateconverToUtf32<Exception>("\uDBFF\uDC00", 0, 0x10FC00);
ValidateconverToUtf32<Exception>("\uDBFF\uDFFF", 0, 0x10FFFF);
// Not surrogate pairs
ValidateconverToUtf32<Exception>("\u0000\u0001", 0, 0);
ValidateconverToUtf32<Exception>("\u0000\u0001", 1, 1);
ValidateconverToUtf32<Exception>("\u0000", 0, 0);
ValidateconverToUtf32<Exception>("\u0020\uD7FF", 0, 32);
ValidateconverToUtf32<Exception>("\u0020\uD7FF", 1, 0xD7FF);
ValidateconverToUtf32<Exception>("abcde", 4, (int)'e');
ValidateconverToUtf32<Exception>("\uD800\uD7FF", 1, 0xD7FF); // high, non-surrogate
ValidateconverToUtf32<Exception>("\uD800\u0000", 1, 0); // high, non-surrogate
ValidateconverToUtf32<Exception>("\uDF01\u0000", 1, 0); // low, non-surrogate
// Invalid inputs
ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 0, Int32.MinValue); // high, high
ValidateconverToUtf32<ArgumentException>("\uD800\uD7FF", 0, Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uD800\u0000", 0, Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 0, Int32.MinValue); // low, high
ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 0, Int32.MinValue); // low, low
ValidateconverToUtf32<ArgumentException>("\uDF01\u0000", 0, Int32.MinValue); // low, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 1, Int32.MinValue); // high, high
ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 1, Int32.MinValue); // low, high
ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 1, Int32.MinValue); // low, low
ValidateconverToUtf32<ArgumentNullException>(null, 0, Int32.MinValue); // null string
ValidateconverToUtf32<ArgumentOutOfRangeException>("", 0, Int32.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("", -1, Int32.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", -1, Int32.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", 5, Int32.MinValue); // index out of range
}
private static void ValidateconverToUtf32<T>(char c1, char c2, int expected) where T : Exception
{
try
{
int result = char.ConvertToUtf32(c1, c2);
Assert.Equal(result, expected);
}
catch (T)
{
Assert.True(expected == Int32.MinValue, "Expected an exception to be thrown");
}
}
[Fact]
public static void TestConvertToUtf32()
{
// Int32 Char.ConvertToUtf32(Char, Char)
ValidateconverToUtf32<Exception>('\uD800', '\uDC00', 0x10000);
ValidateconverToUtf32<Exception>('\uD800', '\uDFFF', 0x103FF);
ValidateconverToUtf32<Exception>('\uDBBF', '\uDFFF', 0xFFFFF);
ValidateconverToUtf32<Exception>('\uDBFF', '\uDC00', 0x10FC00);
ValidateconverToUtf32<Exception>('\uDBFF', '\uDFFF', 0x10FFFF);
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD800', Int32.MinValue); // high, high
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD7FF', Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\u0000', Int32.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDC01', '\uD940', Int32.MinValue); // low, high
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDD00', '\uDE00', Int32.MinValue); // low, low
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDF01', '\u0000', Int32.MinValue); // low, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0032', '\uD7FF', Int32.MinValue); // both non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0000', '\u0000', Int32.MinValue); // both non-surrogate
}
[Fact]
public static void TestEquals()
{
// Boolean Char.Equals(Char)
char a = 'a';
Assert.True(a.Equals('a'));
Assert.False(a.Equals('b'));
Assert.False(a.Equals('A'));
}
[Fact]
public static void TestEqualsObj()
{
// Boolean Char.Equals(Object)
char a = 'a';
Assert.True(a.Equals((object)'a'));
Assert.False(a.Equals((object)'b'));
Assert.False(a.Equals((object)'A'));
Assert.False(a.Equals(null));
int i = (int)'a';
Assert.False(a.Equals(i));
Assert.False(a.Equals("a"));
}
[Fact]
public static void TestGetHashCode()
{
// Int32 Char.GetHashCode()
char a = 'a';
char b = 'b';
Assert.NotEqual(a.GetHashCode(), b.GetHashCode());
}
[Fact]
public static void TestGetNumericValueStrInt()
{
Assert.Equal(Char.GetNumericValue("\uD800\uDD07", 0), 1);
Assert.Equal(Char.GetNumericValue("9", 0), 9);
Assert.Equal(Char.GetNumericValue("Test 7", 5), 7);
Assert.Equal(Char.GetNumericValue("T", 0), -1);
}
[Fact]
public static void TestGetNumericValue()
{
Assert.Equal(Char.GetNumericValue('9'), 9);
Assert.Equal(Char.GetNumericValue('z'), -1);
}
[Fact]
public static void TestIsControl()
{
// Boolean Char.IsControl(Char)
foreach (var c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c));
}
[Fact]
public static void TestIsControlStrInt()
{
// Boolean Char.IsControl(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsControl(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", 4));
}
[Fact]
public static void TestIsDigit()
{
// Boolean Char.IsDigit(Char)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c));
}
[Fact]
public static void TestIsDigitStrInt()
{
// Boolean Char.IsDigit(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsDigit(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", 4));
}
[Fact]
public static void TestIsLetter()
{
// Boolean Char.IsLetter(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.True(char.IsLetter(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.False(char.IsLetter(c));
}
[Fact]
public static void TestIsLetterStrInt()
{
// Boolean Char.IsLetter(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.True(char.IsLetter(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.False(char.IsLetter(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLetter(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", 4));
}
[Fact]
public static void TestIsLetterOrDigit()
{
// Boolean Char.IsLetterOrDigit(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsLetterOrDigit(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsLetterOrDigit(c));
}
[Fact]
public static void TestIsLetterOrDigitStrInt()
{
// Boolean Char.IsLetterOrDigit(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsLetterOrDigit(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsLetterOrDigit(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLetterOrDigit(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", 4));
}
[Fact]
public static void TestIsLower()
{
// Boolean Char.IsLower(Char)
foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c));
}
[Fact]
public static void TestIsLowerStrInt()
{
// Boolean Char.IsLower(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLower(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", 4));
}
[Fact]
public static void TestIsNumber()
{
// Boolean Char.IsNumber(Char)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.True(char.IsNumber(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.False(char.IsNumber(c));
}
[Fact]
public static void TestIsNumberStrInt()
{
// Boolean Char.IsNumber(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.True(char.IsNumber(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.False(char.IsNumber(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsNumber(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", 4));
}
[Fact]
public static void TestIsPunctuation()
{
// Boolean Char.IsPunctuation(Char)
foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.True(char.IsPunctuation(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.False(char.IsPunctuation(c));
}
[Fact]
public static void TestIsPunctuationStrInt()
{
// Boolean Char.IsPunctuation(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.True(char.IsPunctuation(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.False(char.IsPunctuation(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsPunctuation(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", 4));
}
[Fact]
public static void TestIsSeparator()
{
// Boolean Char.IsSeparator(Char)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsSeparator(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.False(char.IsSeparator(c));
}
[Fact]
public static void TestIsSeparatorStrInt()
{
// Boolean Char.IsSeparator(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsSeparator(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.False(char.IsSeparator(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSeparator(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", 4));
}
[Fact]
public static void TestIsLowSurrogate()
{
// Boolean Char.IsLowSurrogate(Char)
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c));
}
[Fact]
public static void TestIsLowSurrogateStrInt()
{
// Boolean Char.IsLowSurrogate(String, Int32)
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLowSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", 4));
}
[Fact]
public static void TestIsHighSurrogate()
{
// Boolean Char.IsHighSurrogate(Char)
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c));
}
[Fact]
public static void TestIsHighSurrogateStrInt()
{
// Boolean Char.IsHighSurrogate(String, Int32)
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsHighSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", 4));
}
[Fact]
public static void TestIsSurrogate()
{
// Boolean Char.IsSurrogate(Char)
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c));
}
[Fact]
public static void TestIsSurrogateStrInt()
{
// Boolean Char.IsSurrogate(String, Int32)
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", 4));
}
[Fact]
public static void TestIsSurrogatePair()
{
// Boolean Char.IsSurrogatePair(Char, Char)
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(Char.IsSurrogatePair(hs, ls));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(Char.IsSurrogatePair(hs, ls));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(Char.IsSurrogatePair(hs, ls));
}
[Fact]
public static void TestIsSurrogatePairStrInt()
{
// Boolean Char.IsSurrogatePair(String, Int32)
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(Char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0));
}
[Fact]
public static void TestIsSymbol()
{
// Boolean Char.IsSymbol(Char)
foreach (var c in GetTestChars(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.True(char.IsSymbol(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.False(char.IsSymbol(c));
}
[Fact]
public static void TestIsSymbolStrInt()
{
// Boolean Char.IsSymbol(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.True(char.IsSymbol(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.False(char.IsSymbol(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSymbol(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", 4));
}
[Fact]
public static void TestIsUpper()
{
// Boolean Char.IsUpper(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c));
}
[Fact]
public static void TestIsUpperStrInt()
{
// Boolean Char.IsUpper(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsUpper(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", 4));
}
[Fact]
public static void TestIsWhiteSpace()
{
// Boolean Char.IsWhiteSpace(Char)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsWhiteSpace(c));
// Some control chars are also considered whitespace for legacy reasons.
//if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace('\u000b'));
Assert.True(char.IsWhiteSpace('\u0085'));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c));
}
}
[Fact]
public static void TestIsWhiteSpaceStrInt()
{
// Boolean Char.IsWhiteSpace(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsWhiteSpace(c.ToString(), 0));
// Some control chars are also considered whitespace for legacy reasons.
//if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace('\u000b'.ToString(), 0));
Assert.True(char.IsWhiteSpace('\u0085'.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c.ToString(), 0));
}
Assert.Throws<ArgumentNullException>(() => char.IsWhiteSpace(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", 4));
}
[Fact]
public static void TestMaxValue()
{
// Char Char.MaxValue
Assert.Equal(0xffff, char.MaxValue);
}
[Fact]
public static void TestMinValue()
{
// Char Char.MinValue
Assert.Equal(0, char.MinValue);
}
[Fact]
public static void TestToLower()
{
// Char Char.ToLower(Char)
Assert.Equal('a', char.ToLower('A'));
Assert.Equal('a', char.ToLower('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLower(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToLower(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToLowerInvariant()
{
// Char Char.ToLowerInvariant(Char)
Assert.Equal('a', char.ToLowerInvariant('A'));
Assert.Equal('a', char.ToLowerInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLowerInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToLowerInvariant(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToString()
{
// String Char.ToString()
Assert.Equal(new string('a', 1), 'a'.ToString());
Assert.Equal(new string('\uabcd', 1), '\uabcd'.ToString());
}
[Fact]
public static void TestToStringChar()
{
// String Char.ToString(Char)
Assert.Equal(new string('a', 1), char.ToString('a'));
Assert.Equal(new string('\uabcd', 1), char.ToString('\uabcd'));
}
[Fact]
public static void TestToUpper()
{
// Char Char.ToUpper(Char)
Assert.Equal('A', char.ToUpper('A'));
Assert.Equal('A', char.ToUpper('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpper(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToUpper(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToUpperInvariant()
{
// Char Char.ToUpperInvariant(Char)
Assert.Equal('A', char.ToUpperInvariant('A'));
Assert.Equal('A', char.ToUpperInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpperInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToUpperInvariant(c);
Assert.Equal(c, lc);
}
}
private static void ValidateTryParse(string s, char expected, bool shouldSucceed)
{
char result;
Assert.Equal(shouldSucceed, char.TryParse(s, out result));
if (shouldSucceed)
Assert.Equal(expected, result);
}
[Fact]
public static void TestTryParse()
{
// Boolean Char.TryParse(String, Char)
ValidateTryParse("a", 'a', true);
ValidateTryParse("4", '4', true);
ValidateTryParse(" ", ' ', true);
ValidateTryParse("\n", '\n', true);
ValidateTryParse("\0", '\0', true);
ValidateTryParse("\u0135", '\u0135', true);
ValidateTryParse("\u05d9", '\u05d9', true);
ValidateTryParse("\ud801", '\ud801', true); // high surrogate
ValidateTryParse("\udc01", '\udc01', true); // low surrogate
ValidateTryParse("\ue001", '\ue001', true); // private use codepoint
// Fail cases
ValidateTryParse(null, '\0', false);
ValidateTryParse("", '\0', false);
ValidateTryParse("\n\r", '\0', false);
ValidateTryParse("kj", '\0', false);
ValidateTryParse(" a", '\0', false);
ValidateTryParse("a ", '\0', false);
ValidateTryParse("\\u0135", '\0', false);
ValidateTryParse("\u01356", '\0', false);
ValidateTryParse("\ud801\udc01", '\0', false); // surrogate pair
}
private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories)
{
Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length);
for (int i = 0; i < s_latinTestSet.Length; i++)
{
if (Array.Exists(categories, uc => uc == (UnicodeCategory)i))
continue;
char[] latinSet = s_latinTestSet[i];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[i];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories)
{
for (int i = 0; i < categories.Length; i++)
{
char[] latinSet = s_latinTestSet[(int)categories[i]];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[(int)categories[i]];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static char[][] s_latinTestSet = new char[][] {
new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter
new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter
new char[] {}, // UnicodeCategory.TitlecaseLetter
new char[] {}, // UnicodeCategory.ModifierLetter
new char[] {}, // UnicodeCategory.OtherLetter
new char[] {}, // UnicodeCategory.NonSpacingMark
new char[] {}, // UnicodeCategory.SpacingCombiningMark
new char[] {}, // UnicodeCategory.EnclosingMark
new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber
new char[] {}, // UnicodeCategory.LetterNumber
new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber
new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator
new char[] {}, // UnicodeCategory.LineSeparator
new char[] {}, // UnicodeCategory.ParagraphSeparator
new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control
new char[] {}, // UnicodeCategory.Format
new char[] {}, // UnicodeCategory.Surrogate
new char[] {}, // UnicodeCategory.PrivateUse
new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation
new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol
new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol
new char[] {}, // UnicodeCategory.OtherNotAssigned
};
private static char[][] s_unicodeTestSet = new char[][] {
new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter
new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter
new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter
new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter
new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter
new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark
new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u19b9','\u1b44','\ua8b5'}, // UnicodeCategory.SpacingCombiningMark
new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark
new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber
new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber
new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber
new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator
new char[] {'\u2028'}, // UnicodeCategory.LineSeparator
new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator
new char[] {}, // UnicodeCategory.Control
new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format
new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate
new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse
new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation
new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol
new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol
new char[] {'\u09c6','\u0dfa','\u2e5c','\ua9f9','\uabbd'}, // UnicodeCategory.OtherNotAssigned
};
private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // range from '\ud800' to '\udbff'
private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // range from '\udc00' to '\udfff'
private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' };
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.Protobuf.Compatibility;
using System;
using System.Reflection;
namespace Google.Protobuf.Reflection
{
/// <summary>
/// The methods in this class are somewhat evil, and should not be tampered with lightly.
/// Basically they allow the creation of relatively weakly typed delegates from MethodInfos
/// which are more strongly typed. They do this by creating an appropriate strongly typed
/// delegate from the MethodInfo, and then calling that within an anonymous method.
/// Mind-bending stuff (at least to your humble narrator) but the resulting delegates are
/// very fast compared with calling Invoke later on.
/// </summary>
internal static class ReflectionUtil
{
static ReflectionUtil()
{
ForceInitialize<string>(); // Handles all reference types
ForceInitialize<int>();
ForceInitialize<long>();
ForceInitialize<uint>();
ForceInitialize<ulong>();
ForceInitialize<float>();
ForceInitialize<double>();
ForceInitialize<bool>();
ForceInitialize<int?>();
ForceInitialize<long?>();
ForceInitialize<uint?>();
ForceInitialize<ulong?>();
ForceInitialize<float?>();
ForceInitialize<double?>();
ForceInitialize<bool?>();
ForceInitialize<SampleEnum>();
SampleEnumMethod();
}
internal static void ForceInitialize<T>() => new ReflectionHelper<IMessage, T>();
/// <summary>
/// Empty Type[] used when calling GetProperty to force property instead of indexer fetching.
/// </summary>
internal static readonly Type[] EmptyTypes = new Type[0];
/// <summary>
/// Creates a delegate which will cast the argument to the type that declares the method,
/// call the method on it, then convert the result to object.
/// </summary>
/// <param name="method">The method to create a delegate for, which must be declared in an IMessage
/// implementation.</param>
internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) =>
GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageObject(method);
/// <summary>
/// Creates a delegate which will cast the argument to the type that declares the method,
/// call the method on it, then convert the result to the specified type. The method is expected
/// to actually return an enum (because of where we're calling it - for oneof cases). Sometimes that
/// means we need some extra work to perform conversions.
/// </summary>
/// <param name="method">The method to create a delegate for, which must be declared in an IMessage
/// implementation.</param>
internal static Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) =>
GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageInt32(method);
/// <summary>
/// Creates a delegate which will execute the given method after casting the first argument to
/// the type that declares the method, and the second argument to the first parameter type of the method.
/// </summary>
/// <param name="method">The method to create a delegate for, which must be declared in an IMessage
/// implementation.</param>
internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) =>
GetReflectionHelper(method.DeclaringType, method.GetParameters()[0].ParameterType).CreateActionIMessageObject(method);
/// <summary>
/// Creates a delegate which will execute the given method after casting the first argument to
/// type that declares the method.
/// </summary>
/// <param name="method">The method to create a delegate for, which must be declared in an IMessage
/// implementation.</param>
internal static Action<IMessage> CreateActionIMessage(MethodInfo method) =>
GetReflectionHelper(method.DeclaringType, typeof(object)).CreateActionIMessage(method);
internal static Func<IMessage, bool> CreateFuncIMessageBool(MethodInfo method) =>
GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageBool(method);
internal static Func<IMessage, bool> CreateIsInitializedCaller(Type msg) =>
((IExtensionSetReflector)Activator.CreateInstance(typeof(ExtensionSetReflector<>).MakeGenericType(msg))).CreateIsInitializedCaller();
/// <summary>
/// Creates a delegate which will execute the given method after casting the first argument to
/// the type that declares the method, and the second argument to the first parameter type of the method.
/// </summary>
internal static IExtensionReflectionHelper CreateExtensionHelper(Extension extension) =>
(IExtensionReflectionHelper)Activator.CreateInstance(typeof(ExtensionReflectionHelper<,>).MakeGenericType(extension.TargetType, extension.GetType().GenericTypeArguments[1]), extension);
/// <summary>
/// Creates a reflection helper for the given type arguments. Currently these are created on demand
/// rather than cached; this will be "busy" when initially loading a message's descriptor, but after that
/// they can be garbage collected. We could cache them by type if that proves to be important, but creating
/// an object is pretty cheap.
/// </summary>
private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) =>
(IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2));
// Non-generic interface allowing us to use an instance of ReflectionHelper<T1, T2> without statically
// knowing the types involved.
private interface IReflectionHelper
{
Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method);
Action<IMessage> CreateActionIMessage(MethodInfo method);
Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method);
Action<IMessage, object> CreateActionIMessageObject(MethodInfo method);
Func<IMessage, bool> CreateFuncIMessageBool(MethodInfo method);
}
internal interface IExtensionReflectionHelper
{
object GetExtension(IMessage message);
void SetExtension(IMessage message, object value);
bool HasExtension(IMessage message);
void ClearExtension(IMessage message);
}
private interface IExtensionSetReflector
{
Func<IMessage, bool> CreateIsInitializedCaller();
}
private class ReflectionHelper<T1, T2> : IReflectionHelper
{
public Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method)
{
// On pleasant runtimes, we can create a Func<int> from a method returning
// an enum based on an int. That's the fast path.
if (CanConvertEnumFuncToInt32Func)
{
var del = (Func<T1, int>) method.CreateDelegate(typeof(Func<T1, int>));
return message => del((T1) message);
}
else
{
// On some runtimes (e.g. old Mono) the return type has to be exactly correct,
// so we go via boxing. Reflection is already fairly inefficient, and this is
// only used for one-of case checking, fortunately.
var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
return message => (int) (object) del((T1) message);
}
}
public Action<IMessage> CreateActionIMessage(MethodInfo method)
{
var del = (Action<T1>) method.CreateDelegate(typeof(Action<T1>));
return message => del((T1) message);
}
public Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method)
{
var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
return message => del((T1) message);
}
public Action<IMessage, object> CreateActionIMessageObject(MethodInfo method)
{
var del = (Action<T1, T2>) method.CreateDelegate(typeof(Action<T1, T2>));
return (message, arg) => del((T1) message, (T2) arg);
}
public Func<IMessage, bool> CreateFuncIMessageBool(MethodInfo method)
{
var del = (Func<T1, bool>)method.CreateDelegate(typeof(Func<T1, bool>));
return message => del((T1)message);
}
}
private class ExtensionReflectionHelper<T1, T3> : IExtensionReflectionHelper
where T1 : IExtendableMessage<T1>
{
private readonly Extension extension;
public ExtensionReflectionHelper(Extension extension)
{
this.extension = extension;
}
public object GetExtension(IMessage message)
{
if (!(message is T1))
{
throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
}
T1 extensionMessage = (T1)message;
if (extension is Extension<T1, T3>)
{
return extensionMessage.GetExtension(extension as Extension<T1, T3>);
}
else if (extension is RepeatedExtension<T1, T3>)
{
return extensionMessage.GetOrInitializeExtension(extension as RepeatedExtension<T1, T3>);
}
else
{
throw new InvalidCastException("The provided extension is not a valid extension identifier type");
}
}
public bool HasExtension(IMessage message)
{
if (!(message is T1))
{
throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
}
T1 extensionMessage = (T1)message;
if (extension is Extension<T1, T3>)
{
return extensionMessage.HasExtension(extension as Extension<T1, T3>);
}
else if (extension is RepeatedExtension<T1, T3>)
{
throw new InvalidOperationException("HasValue is not implemented for repeated extensions");
}
else
{
throw new InvalidCastException("The provided extension is not a valid extension identifier type");
}
}
public void SetExtension(IMessage message, object value)
{
if (!(message is T1))
{
throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
}
T1 extensionMessage = (T1)message;
if (extension is Extension<T1, T3>)
{
extensionMessage.SetExtension(extension as Extension<T1, T3>, (T3)value);
}
else if (extension is RepeatedExtension<T1, T3>)
{
throw new InvalidOperationException("SetValue is not implemented for repeated extensions");
}
else
{
throw new InvalidCastException("The provided extension is not a valid extension identifier type");
}
}
public void ClearExtension(IMessage message)
{
if (!(message is T1))
{
throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
}
T1 extensionMessage = (T1)message;
if (extension is Extension<T1, T3>)
{
extensionMessage.ClearExtension(extension as Extension<T1, T3>);
}
else if (extension is RepeatedExtension<T1, T3>)
{
extensionMessage.GetExtension(extension as RepeatedExtension<T1, T3>).Clear();
}
else
{
throw new InvalidCastException("The provided extension is not a valid extension identifier type");
}
}
}
private class ExtensionSetReflector<T1> : IExtensionSetReflector where T1 : IExtendableMessage<T1>
{
public Func<IMessage, bool> CreateIsInitializedCaller()
{
var prop = typeof(T1).GetTypeInfo().GetDeclaredProperty("_Extensions");
#if NET35
var getFunc = (Func<T1, ExtensionSet<T1>>)prop.GetGetMethod(true).CreateDelegate(typeof(Func<T1, ExtensionSet<T1>>));
#else
var getFunc = (Func<T1, ExtensionSet<T1>>)prop.GetMethod.CreateDelegate(typeof(Func<T1, ExtensionSet<T1>>));
#endif
var initializedFunc = (Func<ExtensionSet<T1>, bool>)
typeof(ExtensionSet<T1>)
.GetTypeInfo()
.GetDeclaredMethod("IsInitialized")
.CreateDelegate(typeof(Func<ExtensionSet<T1>, bool>));
return (m) => {
var set = getFunc((T1)m);
return set == null || initializedFunc(set);
};
}
}
// Runtime compatibility checking code - see ReflectionHelper<T1, T2>.CreateFuncIMessageInt32 for
// details about why we're doing this.
// Deliberately not inside the generic type. We only want to check this once.
private static bool CanConvertEnumFuncToInt32Func { get; } = CheckCanConvertEnumFuncToInt32Func();
private static bool CheckCanConvertEnumFuncToInt32Func()
{
try
{
// Try to do the conversion using reflection, so we can see whether it's supported.
MethodInfo method = typeof(ReflectionUtil).GetMethod(nameof(SampleEnumMethod));
// If this passes, we're in a reasonable runtime.
method.CreateDelegate(typeof(Func<int>));
return true;
}
catch (ArgumentException)
{
return false;
}
}
public enum SampleEnum
{
X
}
// Public to make the reflection simpler.
public static SampleEnum SampleEnumMethod() => SampleEnum.X;
}
}
| |
//
// ExceptionTest.cs - NUnit Test Cases for the System.Exception class
//
// Authors:
// Linus Upson ([email protected])
// Duncan Mak ([email protected])
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
using System;
using System.Runtime.Serialization;
using NUnit.Framework;
namespace MonoTests.System
{
public class ExceptionTest : TestCase
{
public ExceptionTest() {}
// This test makes sure that exceptions thrown on block boundaries are
// handled in the correct block. The meaning of the 'caught' variable is
// a little confusing since there are two catchers: the method being
// tested the the method calling the test. There is probably a better
// name, but I can't think of it right now.
[Test]
public void TestThrowOnBlockBoundaries()
{
bool caught;
try {
caught = false;
ThrowBeforeTry();
} catch {
caught = true;
}
Assert("Exceptions thrown before try blocks should not be caught", caught);
try {
caught = false;
ThrowAtBeginOfTry();
} catch {
caught = true;
}
Assert("Exceptions thrown at begin of try blocks should be caught", !caught);
try {
caught = false;
ThrowAtEndOfTry();
} catch {
caught = true;
}
Assert("Exceptions thrown at end of try blocks should be caught", !caught);
try {
caught = false;
ThrowAtBeginOfCatch();
} catch {
caught = true;
}
Assert("Exceptions thrown at begin of catch blocks should not be caught", caught);
try {
caught = false;
ThrowAtEndOfCatch();
} catch {
caught = true;
}
Assert("Exceptions thrown at end of catch blocks should not be caught", caught);
try {
caught = false;
ThrowAtBeginOfFinally();
} catch {
caught = true;
}
Assert("Exceptions thrown at begin of finally blocks should not be caught", caught);
try {
caught = false;
ThrowAtEndOfFinally();
} catch {
caught = true;
}
Assert("Exceptions thrown at end of finally blocks should not be caught", caught);
try {
caught = false;
ThrowAfterFinally();
} catch {
caught = true;
}
Assert("Exceptions thrown after finally blocks should not be caught", caught);
}
private static void DoNothing()
{
}
private static void ThrowException()
{
throw new Exception();
}
private static void ThrowBeforeTry()
{
ThrowException();
try {
DoNothing();
} catch (Exception) {
DoNothing();
}
}
private static void ThrowAtBeginOfTry()
{
DoNothing();
try {
ThrowException();
DoNothing();
} catch (Exception) {
DoNothing();
}
}
private static void ThrowAtEndOfTry()
{
DoNothing();
try {
DoNothing();
ThrowException();
} catch (Exception) {
DoNothing();
}
}
private static void ThrowAtBeginOfCatch()
{
DoNothing();
try {
DoNothing();
ThrowException();
} catch (Exception) {
throw;
}
}
private static void ThrowAtEndOfCatch()
{
DoNothing();
try {
DoNothing();
ThrowException();
} catch (Exception) {
DoNothing();
throw;
}
}
private static void ThrowAtBeginOfFinally()
{
DoNothing();
try {
DoNothing();
ThrowException();
} catch (Exception) {
DoNothing();
} finally {
ThrowException();
DoNothing();
}
}
private static void ThrowAtEndOfFinally()
{
DoNothing();
try {
DoNothing();
ThrowException();
} catch (Exception) {
DoNothing();
} finally {
DoNothing();
ThrowException();
}
}
private static void ThrowAfterFinally()
{
DoNothing();
try {
DoNothing();
ThrowException();
} catch (Exception) {
DoNothing();
} finally {
DoNothing();
}
ThrowException();
}
[Test]
public void InnerExceptionSource ()
{
Exception a = new Exception ("a", new ArgumentException ("b"));
a.Source = "foo";
AssertEquals (null, a.InnerException.Source);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetObjectData_Null ()
{
Exception e = new Exception ();
e.GetObjectData (null, new StreamingContext (StreamingContextStates.All));
}
}
}
| |
// Variables needed by detail options!
$max_screenerror = 25;
$min_TSScreenError = 2;
$max_TSScreenError = 20;
$min_TSDetailAdjust = 0.6;
$max_TSDetailAdjust = 1.0;
//------------------------------------------
function optionsDlg::setPane(%this, %pane)
{
OptAudioPane.setVisible(false);
OptGraphicsPane.setVisible(false);
OptNetworkPane.setVisible(false);
OptControlsPane.setVisible(false);
OptDetailPane.setVisible(false);
("Opt" @ %pane @ "Pane").setVisible(true);
OptRemapList.fillList();
}
function saveSettings(%this)
{
%flushTextures = false;
// Vsync
if ( $SwapIntervalSupported && OP_VSyncTgl.getValue() != $pref::Video::disableVerticalSync )
{
$pref::Video::disableVerticalSync = OP_VSyncTgl.getValue();
setVerticalSync( !$pref::Video::disableVerticalSync );
}
// Detail Stuff
$pref::Terrain::screenError = $max_screenerror - mFloor( OP_TerrainSlider.getValue() );
$pref::TS::screenError = $max_TSScreenError - mFloor( OP_ShapeSlider.getValue() * ( $max_TSScreenError - $min_TSScreenError ) );
$pref::TS::detailAdjust = $min_TSDetailAdjust + OP_ShapeSlider.getValue() * ( $max_TSDetailAdjust - $min_TSDetailAdjust );
$pref::Shadows = OP_ShadowSlider.getValue();
setShadowDetailLevel( $pref::Shadows );
$pref::VisibleDistanceMod = OP_VisibleDistanceSlider.getValue();
// Sky
%tmp = OP_SkyDetailMenu.getSelected();
if ( %tmp == 5 )
$pref::SkyOn = false; // No sky for us as #5 is "No Sky"
else
{
$pref::SkyOn = true;
$pref::numCloudLayers = ( 4 - %tmp ); // 4 max clouds, menu options are 0..4
}
%temp = OP_PlayerRenderMenu.getSelected();
$pref::Player::renderMyPlayer = %temp & 1;
$pref::Player::renderMyItems = %temp & 2;
// Vertex Lighting
if ( $pref::Interior::VertexLighting != OP_VertexLightTgl.getValue() )
{
$pref::Interior::VertexLighting = OP_VertexLightTgl.getValue();
// Crashes if textured flushed after setting this
// %flushTextures = true;
}
// Texture Detail Sliders need to be saved
$pref::Terrain::texDetail = 6 - mFloor( OP_TerrainTexSlider.getValue() );
%temp = 5 - mFloor( OP_ShapeTexSlider.getValue() );
if ( $pref::OpenGL::mipReduction != %temp )
{
$pref::OpenGL::mipReduction = %temp;
setOpenGLMipReduction( $pref::OpenGL::mipReduction );
%flushTextures = true;
}
%temp = 5 - mFloor( OP_BuildingTexSlider.getValue() );
if ( $pref::OpenGL::interiorMipReduction != %temp )
{
$pref::OpenGL::interiorMipReduction = %temp;
setOpenGLInteriorMipReduction( $pref::OpenGL::interiorMipReduction );
%flushTextures = true;
}
%temp = 5 - mFloor( OP_SkyTexSlider.getValue() );
if ( $pref::OpenGL::skyMipReduction != %temp )
{
$pref::OpenGL::skyMipReduction = %temp;
setOpenGLSkyMipReduction( $pref::OpenGL::skyMipReduction );
%flushTextures = true;
}
// Anisotropy Rendering
if ( $AnisotropySupported )
{
%temp = OP_AnisotropySlider.getValue();
if ( $pref::OpenGL::anisotropy != %temp )
{
$pref::OpenGL::anisotropy = %temp;
setOpenGLAnisotropy( $pref::OpenGL::anisotropy );
%flushTextures = true;
}
}
if (%flushTextures)
OptionsDlg.schedule( 0, doTextureFlush );
}
function OptionsDlg::doTextureFlush(%this)
{
Canvas.repaint();
flushTextureCache();
}
function OptionsDlg::onWake(%this)
{
%this.setPane(Graphics);
%buffer = getDisplayDeviceList();
%count = getFieldCount( %buffer );
OptGraphicsDriverMenu.clear();
for(%i = 0; %i < %count; %i++)
OptGraphicsDriverMenu.add(getField(%buffer, %i), %i);
%selId = OptGraphicsDriverMenu.findText( $pref::Video::displayDevice );
if ( %selId == -1 )
%selId = 0; // How did THAT happen?
OptGraphicsDriverMenu.setSelected( %selId );
OptGraphicsDriverMenu.onSelect( %selId, "" );
OP_GammaSlider.setValue( $pref::OpenGL::gammaCorrection ); // Gamma Correction
// Audio
OptAudioUpdate();
OptAudioVolumeMaster.setValue( $pref::Audio::masterVolume);
OptAudioVolumeShell.setValue( $pref::Audio::channelVolume[$GuiAudioType]);
OptAudioVolumeSim.setValue( $pref::Audio::channelVolume[$SimAudioType]);
OptAudioDriverList.clear();
OptAudioDriverList.add("OpenAL", 1);
OptAudioDriverList.add("none", 2);
%selId = OptAudioDriverList.findText($pref::Audio::driver);
if ( %selId == -1 )
%selId = 0; // How did THAT happen?
OptAudioDriverList.setSelected( %selId );
OptAudioDriverList.onSelect( %selId, "" );
// Detail Controls
OP_TerrainSlider.setValue( $max_screenerror - $pref::Terrain::screenError );
OP_ShapeSlider.setValue( ( $max_TSScreenError - $pref::TS::screenError ) / ( $max_TSScreenError - $min_TSScreenError ) );
OP_ShadowSlider.setValue( $pref::Shadows );
// Sky
OP_SkyDetailMenu.init();
if ( !$pref::SkyOn )
%selId = 5;
else if ( $pref::numCloudLayers >= 0 && $pref::numCloudLayers < 4 )
%selId = 4 - $pref::numCloudLayers;
else
%selId = 1;
OP_SkyDetailMenu.setSelected( %selId );
OP_SkyDetailMenu.setText(OP_SkyDetailMenu.getTextById( %selId ));
OP_VertexLightTgl.setValue( $pref::Interior::VertexLighting );
OP_PlayerRenderMenu.init();
%selId = $pref::Player::renderMyPlayer | ( $pref::Player::renderMyItems << 1 );
OP_PlayerRenderMenu.setSelected( %selId );
OP_VisibleDistanceSlider.setValue( $pref::VisibleDistanceMod );
// Init Texture Menu
OP_DetailSelect.init();
%selId = 1;
OP_DetailSelect.setSelected( %selId );
OP_DetailSelect.setText(OP_DetailSelect.getTextById( %selId ));
// And also init the texture sliders
OP_ShapeTexSlider.setValue( 5 - $pref::OpenGL::mipReduction );
OP_TerrainTexSlider.setValue( 6 - $pref::Terrain::texDetail );
OP_BuildingTexSlider.setValue( 5 - $pref::OpenGL::interiorMipReduction );
OP_SkyTexSlider.setValue( 5 - $pref::OpenGL::skyMipReduction );
// Anisotropy Rendering
OP_AnisotropySlider.setValue( $pref::OpenGL::anisotropy );
OP_AnisotropySlider.setActive( $AnisotropySupported );
// Vsync
if ( $SwapIntervalSupported )
{
OP_VSyncTgl.setValue( $pref::Video::disableVerticalSync );
OP_VSyncTgl.setActive( true );
}
else
{
OP_VSyncTgl.setValue( false );
OP_VSyncTgl.setActive( false );
}
}
function OptionsDlg::onSleep(%this)
{
// write out the control config into the fps/config.cs file
moveMap.save( "~/client/config.cs" );
}
function OP_DetailSelect::init(%this)
{
%this.clear();
%this.add("Terrain", 1);
%this.add("Shape", 2);
%this.add("Building", 3);
%this.add("Sky", 4);
}
function OP_DetailSelect::onSelect( %this, %id, %text )
{
// Hide All Sliders
OP_TerrainTexSlider.visible = false;
OP_ShapeTexSlider.visible = false;
OP_BuildingTexSlider.visible = false;
OP_SkyTexSlider.visible = false;
// Now Show the correct slider
switch ( %id )
{
case 1:OP_TerrainTexSlider.visible = true;
case 2:OP_ShapeTexSlider.visible = true;
case 3:OP_BuildingTexSlider.visible = true;
case 4:OP_SkyTexSlider.visible = true;
}
}
function OP_SkyDetailMenu::init(%this)
{
%this.clear();
%this.add("Full Sky", 1);
%this.add("Two Cloud Layers", 2);
%this.add("One Cloud Layer", 3);
%this.add("Sky Box Only", 4);
%this.add("No Sky", 5);
}
function OptGraphicsDriverMenu::onSelect( %this, %id, %text )
{
// Attempt to keep the same res and bpp settings:
if ( OptGraphicsResolutionMenu.size() > 0 )
%prevRes = OptGraphicsResolutionMenu.getText();
else
%prevRes = getWords( $pref::Video::resolution, 0, 1 );
// Check if this device is full-screen only:
if ( isDeviceFullScreenOnly( %this.getText() ) )
{
OptGraphicsFullscreenToggle.setValue( true );
OptGraphicsFullscreenToggle.setActive( false );
OptGraphicsFullscreenToggle.onAction();
}
else
OptGraphicsFullscreenToggle.setActive( true );
if ( OptGraphicsFullscreenToggle.getValue() )
{
if ( OptGraphicsBPPMenu.size() > 0 )
%prevBPP = OptGraphicsBPPMenu.getText();
else
%prevBPP = getWord( $pref::Video::resolution, 2 );
}
// Fill the resolution and bit depth lists:
OptGraphicsResolutionMenu.init( %this.getText(), OptGraphicsFullscreenToggle.getValue() );
OptGraphicsBPPMenu.init( %this.getText() );
// Try to select the previous settings:
%selId = OptGraphicsResolutionMenu.findText( %prevRes );
if ( %selId == -1 )
%selId = 0;
OptGraphicsResolutionMenu.setSelected( %selId );
if ( OptGraphicsFullscreenToggle.getValue() )
{
%selId = OptGraphicsBPPMenu.findText( %prevBPP );
if ( %selId == -1 )
%selId = 0;
OptGraphicsBPPMenu.setSelected( %selId );
OptGraphicsBPPMenu.setText( OptGraphicsBPPMenu.getTextById( %selId ) );
}
else
OptGraphicsBPPMenu.setText( "Default" );
}
function OptGraphicsResolutionMenu::init( %this, %device, %fullScreen )
{
%this.clear();
%resList = getResolutionList( %device );
%resCount = getFieldCount( %resList );
%deskRes = getDesktopResolution();
%count = 0;
for ( %i = 0; %i < %resCount; %i++ )
{
%res = getWords( getField( %resList, %i ), 0, 1 );
if ( !%fullScreen )
{
if ( firstWord( %res ) >= firstWord( %deskRes ) )
continue;
if ( getWord( %res, 1 ) >= getWord( %deskRes, 1 ) )
continue;
}
// Only add to list if it isn't there already:
if ( %this.findText( %res ) == -1 )
{
%this.add( %res, %count );
%count++;
}
}
}
function OptGraphicsFullscreenToggle::onAction(%this)
{
Parent::onAction();
%prevRes = OptGraphicsResolutionMenu.getText();
// Update the resolution menu with the new options
OptGraphicsResolutionMenu.init( OptGraphicsDriverMenu.getText(), %this.getValue() );
// Set it back to the previous resolution if the new mode supports it.
%selId = OptGraphicsResolutionMenu.findText( %prevRes );
if ( %selId == -1 )
%selId = 0;
OptGraphicsResolutionMenu.setSelected( %selId );
}
function OptGraphicsBPPMenu::init( %this, %device )
{
%this.clear();
if ( %device $= "Voodoo2" )
%this.add( "16", 0 );
else
{
%resList = getResolutionList( %device );
%resCount = getFieldCount( %resList );
%count = 0;
for ( %i = 0; %i < %resCount; %i++ )
{
%bpp = getWord( getField( %resList, %i ), 2 );
// Only add to list if it isn't there already:
if ( %this.findText( %bpp ) == -1 )
{
%this.add( %bpp, %count );
%count++;
}
}
}
}
function optionsDlg::applyGraphics( %this )
{
%newDriver = OptGraphicsDriverMenu.getText();
%newRes = OptGraphicsResolutionMenu.getText();
%newBpp = OptGraphicsBPPMenu.getText();
%newFullScreen = OptGraphicsFullscreenToggle.getValue();
if ( %newDriver !$= $pref::Video::displayDevice )
{
setDisplayDevice( %newDriver, firstWord( %newRes ), getWord( %newRes, 1 ), %newBpp, %newFullScreen );
//OptionsDlg::deviceDependent( %this );
}
else
setScreenMode( firstWord( %newRes ), getWord( %newRes, 1 ), %newBpp, %newFullScreen );
}
$RemapCount = 0;
$RemapName[$RemapCount] = "Forward";
$RemapCmd[$RemapCount] = "moveforward";
$RemapCount++;
$RemapName[$RemapCount] = "Backward";
$RemapCmd[$RemapCount] = "movebackward";
$RemapCount++;
$RemapName[$RemapCount] = "Strafe Left";
$RemapCmd[$RemapCount] = "moveleft";
$RemapCount++;
$RemapName[$RemapCount] = "Strafe Right";
$RemapCmd[$RemapCount] = "moveright";
$RemapCount++;
$RemapName[$RemapCount] = "Turn Left";
$RemapCmd[$RemapCount] = "turnLeft";
$RemapCount++;
$RemapName[$RemapCount] = "Turn Right";
$RemapCmd[$RemapCount] = "turnRight";
$RemapCount++;
$RemapName[$RemapCount] = "Look Up";
$RemapCmd[$RemapCount] = "panUp";
$RemapCount++;
$RemapName[$RemapCount] = "Look Down";
$RemapCmd[$RemapCount] = "panDown";
$RemapCount++;
$RemapName[$RemapCount] = "Jump";
$RemapCmd[$RemapCount] = "jump";
$RemapCount++;
$RemapName[$RemapCount] = "Fire Weapon";
$RemapCmd[$RemapCount] = "mouseFire";
$RemapCount++;
$RemapName[$RemapCount] = "Adjust Zoom";
$RemapCmd[$RemapCount] = "setZoomFov";
$RemapCount++;
$RemapName[$RemapCount] = "Toggle Zoom";
$RemapCmd[$RemapCount] = "toggleZoom";
$RemapCount++;
$RemapName[$RemapCount] = "Free Look";
$RemapCmd[$RemapCount] = "toggleFreeLook";
$RemapCount++;
$RemapName[$RemapCount] = "Switch 1st/3rd";
$RemapCmd[$RemapCount] = "toggleFirstPerson";
$RemapCount++;
$RemapName[$RemapCount] = "Toggle Message Hud";
$RemapCmd[$RemapCount] = "toggleMessageHud";
$RemapCount++;
$RemapName[$RemapCount] = "Message Hud PageUp";
$RemapCmd[$RemapCount] = "pageMessageHudUp";
$RemapCount++;
$RemapName[$RemapCount] = "Message Hud PageDown";
$RemapCmd[$RemapCount] = "pageMessageHudDown";
$RemapCount++;
$RemapName[$RemapCount] = "Resize Message Hud";
$RemapCmd[$RemapCount] = "resizeMessageHud";
$RemapCount++;
$RemapName[$RemapCount] = "Toggle Camera";
$RemapCmd[$RemapCount] = "toggleCamera";
$RemapCount++;
$RemapName[$RemapCount] = "Drop Camera at Player";
$RemapCmd[$RemapCount] = "dropCameraAtPlayer";
$RemapCount++;
$RemapName[$RemapCount] = "Drop Player at Camera";
$RemapCmd[$RemapCount] = "dropPlayerAtCamera";
$RemapCount++;
function restoreDefaultMappings()
{
moveMap.delete();
exec( "~/client/scripts/default.bind.cs" );
OptRemapList.fillList();
}
function getMapDisplayName( %device, %action )
{
if ( %device $= "keyboard" )
return( %action );
else if ( strstr( %device, "mouse" ) != -1 )
{
// Substitute "mouse" for "button" in the action string:
%pos = strstr( %action, "button" );
if ( %pos != -1 )
{
%mods = getSubStr( %action, 0, %pos );
%object = getSubStr( %action, %pos, 1000 );
%instance = getSubStr( %object, strlen( "button" ), 1000 );
return( %mods @ "mouse" @ ( %instance + 1 ) );
}
else
error( "Mouse input object other than button passed to getDisplayMapName!" );
}
else if ( strstr( %device, "joystick" ) != -1 )
{
// Substitute "joystick" for "button" in the action string:
%pos = strstr( %action, "button" );
if ( %pos != -1 )
{
%mods = getSubStr( %action, 0, %pos );
%object = getSubStr( %action, %pos, 1000 );
%instance = getSubStr( %object, strlen( "button" ), 1000 );
return( %mods @ "joystick" @ ( %instance + 1 ) );
}
else
{
%pos = strstr( %action, "pov" );
if ( %pos != -1 )
{
%wordCount = getWordCount( %action );
%mods = %wordCount > 1 ? getWords( %action, 0, %wordCount - 2 ) @ " " : "";
%object = getWord( %action, %wordCount - 1 );
switch$ ( %object )
{
case "upov": %object = "POV1 up";
case "dpov": %object = "POV1 down";
case "lpov": %object = "POV1 left";
case "rpov": %object = "POV1 right";
case "upov2": %object = "POV2 up";
case "dpov2": %object = "POV2 down";
case "lpov2": %object = "POV2 left";
case "rpov2": %object = "POV2 right";
default: %object = "??";
}
return( %mods @ %object );
}
else
error( "Unsupported Joystick input object passed to getDisplayMapName!" );
}
}
return( "??" );
}
function buildFullMapString( %index )
{
%name = $RemapName[%index];
%cmd = $RemapCmd[%index];
%temp = moveMap.getBinding( %cmd );
%device = getField( %temp, 0 );
%object = getField( %temp, 1 );
if ( %device !$= "" && %object !$= "" )
%mapString = getMapDisplayName( %device, %object );
else
%mapString = "";
return( %name TAB %mapString );
}
function OptRemapList::fillList( %this )
{
%this.clear();
for ( %i = 0; %i < $RemapCount; %i++ )
%this.addRow( %i, buildFullMapString( %i ) );
}
//------------------------------------------------------------------------------
function OptRemapList::doRemap( %this )
{
%selId = %this.getSelectedId();
%name = $RemapName[%selId];
OptRemapText.setValue( "REMAP \"" @ %name @ "\"" );
OptRemapInputCtrl.index = %selId;
Canvas.pushDialog( RemapDlg );
}
//------------------------------------------------------------------------------
function redoMapping( %device, %action, %cmd, %oldIndex, %newIndex )
{
//%actionMap.bind( %device, %action, $RemapCmd[%newIndex] );
moveMap.bind( %device, %action, %cmd );
OptRemapList.setRowById( %oldIndex, buildFullMapString( %oldIndex ) );
OptRemapList.setRowById( %newIndex, buildFullMapString( %newIndex ) );
}
//------------------------------------------------------------------------------
function findRemapCmdIndex( %command )
{
for ( %i = 0; %i < $RemapCount; %i++ )
{
if ( %command $= $RemapCmd[%i] )
return( %i );
}
return( -1 );
}
function OptRemapInputCtrl::onInputEvent( %this, %device, %action )
{
//error( "** onInputEvent called - device = " @ %device @ ", action = " @ %action @ " **" );
Canvas.popDialog( RemapDlg );
// Test for the reserved keystrokes:
if ( %device $= "keyboard" )
{
// Cancel...
if ( %action $= "escape" )
{
// Do nothing...
return;
}
}
%cmd = $RemapCmd[%this.index];
%name = $RemapName[%this.index];
// First check to see if the given action is already mapped:
%prevMap = moveMap.getCommand( %device, %action );
if ( %prevMap !$= %cmd )
{
if ( %prevMap $= "" )
{
moveMap.bind( %device, %action, %cmd );
OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) );
}
else
{
%mapName = getMapDisplayName( %device, %action );
%prevMapIndex = findRemapCmdIndex( %prevMap );
if ( %prevMapIndex == -1 )
MessageBoxOK( "REMAP FAILED", "\"" @ %mapName @ "\" is already bound to a non-remappable command!" );
else
{
%prevCmdName = $RemapName[%prevMapIndex];
MessageBoxYesNo( "WARNING",
"\"" @ %mapName @ "\" is already bound to \""
@ %prevCmdName @ "\"!\nDo you want to undo this mapping?",
"redoMapping(" @ %device @ ", \"" @ %action @ "\", \"" @ %cmd @ "\", " @ %prevMapIndex @ ", " @ %this.index @ ");", "" );
}
return;
}
}
}
// Audio
function OptAudioUpdate()
{
// set the driver text
%text = "Vendor: " @ alGetString("AL_VENDOR") @
"\nVersion: " @ alGetString("AL_VERSION") @
"\nRenderer: " @ alGetString("AL_RENDERER") @
"\nExtensions: " @ alGetString("AL_EXTENSIONS");
OptAudioInfo.setText(%text);
}
// Channel 0 is unused in-game, but is used here to test master volume.
new AudioDescription(AudioChannel0)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 0;
};
new AudioDescription(AudioChannel1)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 1;
};
new AudioDescription(AudioChannel2)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 2;
};
new AudioDescription(AudioChannel3)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 3;
};
new AudioDescription(AudioChannel4)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 4;
};
new AudioDescription(AudioChannel5)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 5;
};
new AudioDescription(AudioChannel6)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 6;
};
new AudioDescription(AudioChannel7)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 7;
};
new AudioDescription(AudioChannel8)
{
volume = 1.0;
isLooping= false;
is3D = false;
type = 8;
};
$AudioTestHandle = 0;
function OptAudioUpdateMasterVolume(%volume)
{
if (%volume == $pref::Audio::masterVolume)
return;
alxListenerf(AL_GAIN_LINEAR, %volume);
$pref::Audio::masterVolume = %volume;
if (!alxIsPlaying($AudioTestHandle))
{
$AudioTestHandle = alxCreateSource("AudioChannel0", expandFilename("~/data/sound/testing.wav"));
alxPlay($AudioTestHandle);
}
}
function OptAudioUpdateChannelVolume(%channel, %volume)
{
if (%channel < 1 || %channel > 8)
return;
if (%volume == $pref::Audio::channelVolume[%channel])
return;
alxSetChannelVolume(%channel, %volume);
$pref::Audio::channelVolume[%channel] = %volume;
if (!alxIsPlaying($AudioTestHandle))
{
$AudioTestHandle = alxCreateSource("AudioChannel"@%channel, expandFilename("~/data/sound/testing.wav"));
alxPlay($AudioTestHandle);
}
}
function OptAudioDriverList::onSelect( %this, %id, %text )
{
if (%text $= "")
return;
if ($pref::Audio::driver $= %text)
return;
$pref::Audio::driver = %text;
OpenALInit();
}
//------------------------------------------
// Graphic Stuff
function updateGammaCorrection()
{
$pref::OpenGL::gammaCorrection = OP_GammaSlider.getValue();
videoSetGammaCorrection( $pref::OpenGL::gammaCorrection );
}
// Terrain Stuff
function updateTerrainDetail()
{
$pref::Terrain::screenError = $max_screenerror - mFloor( OP_TerrainSlider.getValue());
if ( OP_TerrainSlider.getValue() != $max_screenerror - $pref::Terrain::screenError )
OP_TerrainSlider.setValue( $max_screenerror - $pref::Terrain::screenError );
}
// Player Render Options
function OP_PlayerRenderMenu::init( %this )
{
%this.clear();
%this.add( "Player and Items", 3 );
%this.add( "Player only", 1 );
%this.add( "Items only", 2 );
%this.add( "Neither Player nor Items", 0 );
}
//------------------------------------------
| |
// /* ------------------
//
// (c) whydoidoit.com 2012
// by Mike Talbot
// ------------------- */
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
using Serialization;
/// <summary>
/// Used to store material and shader information
/// </summary>
[AddComponentMenu("Storage/Store Materials")]
[ExecuteInEditMode]
[DontStore]
public partial class StoreMaterials : MonoBehaviour {
/// <summary>
/// Contains all shaders and properties that are used with all instances of this script in the entire project.
/// The initialization happens in the constructor which is created using code generation.
/// </summary>
public static Index<string, List<MaterialProperty>> ShaderDatabase = new Index<string, List<MaterialProperty>>();
/// <summary>
/// Caches shaders we already searched for
/// </summary>
static Index<string, List<MaterialProperty>> cache = new Index<string, List<MaterialProperty>>();
/// <summary>
/// Stores whether all shaders are in the shader database
/// </summary>
public static bool Dirty {
get;
set;
}
/// <summary>
/// The amount of shaders in the database
/// </summary>
public static int ShaderCount {
get {
return ShaderDatabase.Count;
}
}
/// <summary>
/// The amount of properties of all shaders in the database
/// </summary>
public static int PropertyCount {
get {
int count = 0;
foreach (List<MaterialProperty> list in ShaderDatabase.Values) {
count += list.Count;
}
return count;
}
}
/// <summary>
/// Contains a copy of the ShaderPropertyType enum from the ShaderUtil class, because it's not available in player builds
/// </summary>
[Serializable]
public class MaterialProperty {
[Serializable]
public enum PropertyType {
Color = 0,
Vector = 1,
Float = 2,
Range = 3,
TexEnv = 4,
}
public string name;
public string description;
public PropertyType type;
}
/// <summary>
/// Container for the stored information
/// </summary>
public class StoredValue {
public MaterialProperty property;
public object[] value;
}
static StoreMaterials() {
DelegateSupport.RegisterFunctionType<Texture2D, int>();
DelegateSupport.RegisterFunctionType<StoreMaterials, List<MaterialProperty>>();
DelegateSupport.RegisterFunctionType<MaterialProperty, MaterialProperty.PropertyType>();
DelegateSupport.RegisterFunctionType<MaterialProperty, string>();
DelegateSupport.RegisterFunctionType<StoredValue, MaterialProperty>();
DelegateSupport.RegisterFunctionType<StoredValue, object>();
}
private void Awake() {
OnEnable();
}
private void OnEnable() {
cache.Clear();
#if UNITY_EDITOR
if (!StoreMaterials.Dirty) {
Renderer renderer = GetComponent<Renderer>();
foreach (Material mat in renderer.sharedMaterials) {
if (!ShaderDatabase.ContainsKey(mat.shader.name)) {
Dirty = true;
break;
}
}
}
#endif
}
private void OnDisable() {
cache.Clear();
}
/// <summary>
/// Gets the values given a material
/// </summary>
/// <param name="m">The material</param>
/// <returns>A StoredValue containing value and type information</returns>
public List<StoredValue> GetValues(Material m) {
var list = GetShaderProperties(m);
var output = new List<StoredValue>();
foreach (var p in list) {
var o = new StoredValue {
property = p
};
output.Add(o);
switch (p.type) {
case MaterialProperty.PropertyType.Color:
o.value = new object[1];
o.value[0] = m.GetColor(p.name);
break;
case MaterialProperty.PropertyType.Float:
o.value = new object[1];
o.value[0] = m.GetFloat(p.name);
break;
case MaterialProperty.PropertyType.Range:
o.value = new object[1];
o.value[0] = m.GetFloat(p.name);
break;
case MaterialProperty.PropertyType.TexEnv:
o.value = new object[3];
o.value[0] = m.GetTexture(p.name);
o.value[1] = m.GetTextureOffset(p.name);
o.value[2] = m.GetTextureScale(p.name);
break;
case MaterialProperty.PropertyType.Vector:
o.value = new object[1];
o.value[0] = m.GetVector(p.name);
break;
default:
Debug.LogError("Unsupported type: " + p.type.ToString());
break;
}
}
return output;
}
/// <summary>
/// Restores the material values
/// </summary>
/// <param name="m">Material</param>
/// <param name="values">Set of values</param>
public void SetValues(Material m, IEnumerable<StoredValue> values) {
foreach (var v in values) {
switch (v.property.type) {
case MaterialProperty.PropertyType.Color:
m.SetColor(v.property.name, (Color)v.value[0]);
break;
case MaterialProperty.PropertyType.Float:
m.SetFloat(v.property.name, (float)v.value[0]);
break;
case MaterialProperty.PropertyType.Range:
m.SetFloat(v.property.name, (float)v.value[0]);
break;
case MaterialProperty.PropertyType.TexEnv:
m.SetTexture(v.property.name, (Texture)v.value[0]);
m.SetTextureOffset(v.property.name, (Vector2)v.value[1]);
m.SetTextureScale(v.property.name, (Vector2)v.value[2]);
break;
case MaterialProperty.PropertyType.Vector:
m.SetVector(v.property.name, (Vector4)v.value[0]);
break;
default:
Debug.LogError("Unsupported type: " + v.property.type.ToString());
break;
}
}
}
/// <summary>
/// Finds the shader's properties in the shader database and caches them
/// </summary>
/// <param name="material">Material</param>
/// <returns>List of properties</returns>
public List<MaterialProperty> GetShaderProperties(Material material) {
if (cache.ContainsKey(material.shader.name)) {
return cache[material.shader.name];
}
var list = new List<MaterialProperty>();
List<MaterialProperty> material_list = ShaderDatabase[material.shader.name];
foreach (MaterialProperty prop in material_list) {
if (material.HasProperty(prop.name)) {
list.Add(prop);
}
}
cache[material.shader.name] = list;
return list;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal
{
public static ICertificatePal FromHandle(IntPtr handle)
{
return FromHandle(handle, true);
}
internal static ICertificatePal FromHandle(IntPtr handle, bool throwOnFail)
{
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));
SafeSecCertificateHandle certHandle;
SafeSecIdentityHandle identityHandle;
if (Interop.AppleCrypto.X509DemuxAndRetainHandle(handle, out certHandle, out identityHandle))
{
Debug.Assert(
certHandle.IsInvalid != identityHandle.IsInvalid,
$"certHandle.IsInvalid ({certHandle.IsInvalid}) should differ from identityHandle.IsInvalid ({identityHandle.IsInvalid})");
if (certHandle.IsInvalid)
{
certHandle.Dispose();
return new AppleCertificatePal(identityHandle);
}
identityHandle.Dispose();
return new AppleCertificatePal(certHandle);
}
certHandle.Dispose();
identityHandle.Dispose();
if (throwOnFail)
{
throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));
}
return null;
}
public static ICertificatePal FromOtherCert(X509Certificate cert)
{
Debug.Assert(cert.Pal != null);
ICertificatePal pal = FromHandle(cert.Handle);
GC.KeepAlive(cert); // ensure cert's safe handle isn't finalized while raw handle is in use
return pal;
}
public static ICertificatePal FromBlob(
byte[] rawData,
SafePasswordHandle password,
X509KeyStorageFlags keyStorageFlags)
{
Debug.Assert(password != null);
X509ContentType contentType = X509Certificate2.GetCertContentType(rawData);
if (contentType == X509ContentType.Pkcs7)
{
// In single mode for a PKCS#7 signed or signed-and-enveloped file we're supposed to return
// the certificate which signed the PKCS#7 file.
//
// X509Certificate2Collection::Export(X509ContentType.Pkcs7) claims to be a signed PKCS#7,
// but doesn't emit a signature block. So this is hard to test.
//
// TODO(2910): Figure out how to extract the signing certificate, when it's present.
throw new CryptographicException(SR.Cryptography_X509_PKCS7_NoSigner);
}
bool exportable = true;
SafeKeychainHandle keychain;
if (contentType == X509ContentType.Pkcs12)
{
if ((keyStorageFlags & X509KeyStorageFlags.EphemeralKeySet) == X509KeyStorageFlags.EphemeralKeySet)
{
throw new PlatformNotSupportedException(SR.Cryptography_X509_NoEphemeralPfx);
}
exportable = (keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable;
bool persist =
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet;
keychain = persist
? Interop.AppleCrypto.SecKeychainCopyDefault()
: Interop.AppleCrypto.CreateTemporaryKeychain();
}
else
{
keychain = SafeTemporaryKeychainHandle.InvalidHandle;
password = SafePasswordHandle.InvalidHandle;
}
using (keychain)
{
SafeSecIdentityHandle identityHandle;
SafeSecCertificateHandle certHandle = Interop.AppleCrypto.X509ImportCertificate(
rawData,
contentType,
password,
keychain,
exportable,
out identityHandle);
if (identityHandle.IsInvalid)
{
identityHandle.Dispose();
return new AppleCertificatePal(certHandle);
}
if (contentType != X509ContentType.Pkcs12)
{
Debug.Fail("Non-PKCS12 import produced an identity handle");
identityHandle.Dispose();
certHandle.Dispose();
throw new CryptographicException();
}
Debug.Assert(certHandle.IsInvalid);
certHandle.Dispose();
return new AppleCertificatePal(identityHandle);
}
}
public static ICertificatePal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
Debug.Assert(password != null);
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
return FromBlob(fileBytes, password, keyStorageFlags);
}
}
internal sealed class AppleCertificatePal : ICertificatePal
{
private SafeSecIdentityHandle _identityHandle;
private SafeSecCertificateHandle _certHandle;
private CertificateData _certData;
private bool _readCertData;
internal AppleCertificatePal(SafeSecCertificateHandle certHandle)
{
Debug.Assert(!certHandle.IsInvalid);
_certHandle = certHandle;
}
internal AppleCertificatePal(SafeSecIdentityHandle identityHandle)
{
Debug.Assert(!identityHandle.IsInvalid);
_identityHandle = identityHandle;
_certHandle = Interop.AppleCrypto.X509GetCertFromIdentity(identityHandle);
}
public void Dispose()
{
_certHandle?.Dispose();
_identityHandle?.Dispose();
_certHandle = null;
_identityHandle = null;
}
internal SafeSecCertificateHandle CertificateHandle => _certHandle;
internal SafeSecIdentityHandle IdentityHandle => _identityHandle;
public bool HasPrivateKey => !(_identityHandle?.IsInvalid ?? true);
public IntPtr Handle
{
get
{
if (HasPrivateKey)
{
return _identityHandle.DangerousGetHandle();
}
return _certHandle?.DangerousGetHandle() ?? IntPtr.Zero;
}
}
public string Issuer => IssuerName.Name;
public string Subject => SubjectName.Name;
public string KeyAlgorithm
{
get
{
EnsureCertData();
return _certData.PublicKeyAlgorithm.AlgorithmId;
}
}
public byte[] KeyAlgorithmParameters
{
get
{
EnsureCertData();
return _certData.PublicKeyAlgorithm.Parameters;
}
}
public byte[] PublicKeyValue
{
get
{
EnsureCertData();
return _certData.PublicKey;
}
}
public byte[] SerialNumber
{
get
{
EnsureCertData();
byte[] serial = _certData.SerialNumber;
Array.Reverse(serial);
return serial;
}
}
public string SignatureAlgorithm
{
get
{
EnsureCertData();
return _certData.SignatureAlgorithm.AlgorithmId;
}
}
public string FriendlyName
{
get { return ""; }
set
{
throw new PlatformNotSupportedException(
SR.Format(SR.Cryptography_Unix_X509_PropertyNotSettable, nameof(FriendlyName)));
}
}
public int Version
{
get
{
EnsureCertData();
return _certData.Version + 1;
}
}
public X500DistinguishedName SubjectName
{
get
{
EnsureCertData();
return _certData.Subject;
}
}
public X500DistinguishedName IssuerName
{
get
{
EnsureCertData();
return _certData.Issuer;
}
}
public IEnumerable<X509Extension> Extensions {
get
{
EnsureCertData();
return _certData.Extensions;
}
}
public byte[] RawData
{
get
{
EnsureCertData();
return _certData.RawData;
}
}
public DateTime NotAfter
{
get
{
EnsureCertData();
return _certData.NotAfter.ToLocalTime();
}
}
public DateTime NotBefore
{
get
{
EnsureCertData();
return _certData.NotBefore.ToLocalTime();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350",
Justification = "SHA1 is required for Compat")]
public byte[] Thumbprint
{
get
{
EnsureCertData();
using (SHA1 hash = SHA1.Create())
{
return hash.ComputeHash(_certData.RawData);
}
}
}
public bool Archived
{
get { return false; }
set
{
throw new PlatformNotSupportedException(
SR.Format(SR.Cryptography_Unix_X509_PropertyNotSettable, nameof(Archived)));
}
}
public byte[] SubjectPublicKeyInfo
{
get
{
EnsureCertData();
return _certData.SubjectPublicKeyInfo;
}
}
public RSA GetRSAPrivateKey()
{
if (_identityHandle == null)
return null;
Debug.Assert(!_identityHandle.IsInvalid);
SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.X509GetPublicKey(_certHandle);
SafeSecKeyRefHandle privateKey = Interop.AppleCrypto.X509GetPrivateKeyFromIdentity(_identityHandle);
return new RSAImplementation.RSASecurityTransforms(publicKey, privateKey);
}
public DSA GetDSAPrivateKey()
{
if (_identityHandle == null)
return null;
Debug.Assert(!_identityHandle.IsInvalid);
SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.X509GetPublicKey(_certHandle);
SafeSecKeyRefHandle privateKey = Interop.AppleCrypto.X509GetPrivateKeyFromIdentity(_identityHandle);
return new DSAImplementation.DSASecurityTransforms(publicKey, privateKey);
}
public ECDsa GetECDsaPrivateKey()
{
if (_identityHandle == null)
return null;
Debug.Assert(!_identityHandle.IsInvalid);
SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.X509GetPublicKey(_certHandle);
SafeSecKeyRefHandle privateKey = Interop.AppleCrypto.X509GetPrivateKeyFromIdentity(_identityHandle);
return new ECDsaImplementation.ECDsaSecurityTransforms(publicKey, privateKey);
}
public ICertificatePal CopyWithPrivateKey(DSA privateKey)
{
var typedKey = privateKey as DSAImplementation.DSASecurityTransforms;
if (typedKey != null)
{
return CopyWithPrivateKey(typedKey.GetKeys());
}
DSAParameters dsaParameters = privateKey.ExportParameters(true);
using (PinAndClear.Track(dsaParameters.X))
using (typedKey = new DSAImplementation.DSASecurityTransforms())
{
typedKey.ImportParameters(dsaParameters);
return CopyWithPrivateKey(typedKey.GetKeys());
}
}
public ICertificatePal CopyWithPrivateKey(ECDsa privateKey)
{
var typedKey = privateKey as ECDsaImplementation.ECDsaSecurityTransforms;
if (typedKey != null)
{
return CopyWithPrivateKey(typedKey.GetKeys());
}
ECParameters ecParameters = privateKey.ExportParameters(true);
using (PinAndClear.Track(ecParameters.D))
using (typedKey = new ECDsaImplementation.ECDsaSecurityTransforms())
{
typedKey.ImportParameters(ecParameters);
return CopyWithPrivateKey(typedKey.GetKeys());
}
}
public ICertificatePal CopyWithPrivateKey(RSA privateKey)
{
var typedKey = privateKey as RSAImplementation.RSASecurityTransforms;
if (typedKey != null)
{
return CopyWithPrivateKey(typedKey.GetKeys());
}
RSAParameters rsaParameters = privateKey.ExportParameters(true);
using (PinAndClear.Track(rsaParameters.D))
using (PinAndClear.Track(rsaParameters.P))
using (PinAndClear.Track(rsaParameters.Q))
using (PinAndClear.Track(rsaParameters.DP))
using (PinAndClear.Track(rsaParameters.DQ))
using (PinAndClear.Track(rsaParameters.InverseQ))
using (typedKey = new RSAImplementation.RSASecurityTransforms())
{
typedKey.ImportParameters(rsaParameters);
return CopyWithPrivateKey(typedKey.GetKeys());
}
}
private ICertificatePal CopyWithPrivateKey(SecKeyPair keyPair)
{
if (keyPair.PrivateKey == null)
{
// Both Windows and Linux/OpenSSL are unaware if they bound a public or private key.
// Here, we do know. So throw if we can't do what they asked.
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keyPair.PrivateKey);
// If we're using a key already in a keychain don't add the certificate to that keychain here,
// do it in the temporary add/remove in the shim.
SafeKeychainHandle cloneKeychain = SafeTemporaryKeychainHandle.InvalidHandle;
if (keychain.IsInvalid)
{
keychain = Interop.AppleCrypto.CreateTemporaryKeychain();
cloneKeychain = keychain;
}
// Because SecIdentityRef only has private constructors we need to have the cert and the key
// in the same keychain. That almost certainly means we're going to need to add this cert to a
// keychain, and when a cert that isn't part of a keychain gets added to a keychain then the
// interior pointer of "what keychain did I come from?" used by SecKeychainItemCopyKeychain gets
// set. That makes this function have side effects, which is not desired.
//
// It also makes reference tracking on temporary keychains broken, since the cert can
// DangerousRelease a handle it didn't DangerousAddRef on. And so CopyWithPrivateKey makes
// a temporary keychain, then deletes it before anyone has a chance to (e.g.) export the
// new identity as a PKCS#12 blob.
//
// Solution: Clone the cert, like we do in Windows.
SafeSecCertificateHandle tempHandle;
{
byte[] export = RawData;
const bool exportable = false;
SafeSecIdentityHandle identityHandle;
tempHandle = Interop.AppleCrypto.X509ImportCertificate(
export,
X509ContentType.Cert,
SafePasswordHandle.InvalidHandle,
cloneKeychain,
exportable,
out identityHandle);
Debug.Assert(identityHandle.IsInvalid, "identityHandle should be IsInvalid");
identityHandle.Dispose();
Debug.Assert(!tempHandle.IsInvalid, "tempHandle should not be IsInvalid");
}
using (keychain)
using (tempHandle)
{
SafeSecIdentityHandle identityHandle = Interop.AppleCrypto.X509CopyWithPrivateKey(
tempHandle,
keyPair.PrivateKey,
keychain);
AppleCertificatePal newPal = new AppleCertificatePal(identityHandle);
return newPal;
}
}
public string GetNameInfo(X509NameType nameType, bool forIssuer)
{
// Algorithm behaviors (pseudocode). When forIssuer is true, replace "Subject" with "Issuer" and
// SAN (Subject Alternative Names) with IAN (Issuer Alternative Names).
//
// SimpleName: Subject[CN] ?? Subject[OU] ?? Subject[O] ?? Subject[E] ?? Subject.Rdns.FirstOrDefault() ??
// SAN.Entries.FirstOrDefault(type == GEN_EMAIL);
// EmailName: SAN.Entries.FirstOrDefault(type == GEN_EMAIL) ?? Subject[E];
// UpnName: SAN.Entries.FirsOrDefaultt(type == GEN_OTHER && entry.AsOther().OID == szOidUpn).AsOther().Value;
// DnsName: SAN.Entries.FirstOrDefault(type == GEN_DNS) ?? Subject[CN];
// DnsFromAlternativeName: SAN.Entries.FirstOrDefault(type == GEN_DNS);
// UrlName: SAN.Entries.FirstOrDefault(type == GEN_URI);
EnsureCertData();
if (nameType == X509NameType.SimpleName)
{
X500DistinguishedName name = forIssuer ? _certData.Issuer : _certData.Subject;
string candidate = GetSimpleNameInfo(name);
if (candidate != null)
{
return candidate;
}
}
// Check the Subject Alternative Name (or Issuer Alternative Name) for the right value;
{
string extensionId = forIssuer ? Oids.IssuerAltName : Oids.SubjectAltName;
GeneralNameType? matchType = null;
string otherOid = null;
// Currently all X509NameType types have a path where they look at the SAN/IAN,
// but we need to figure out which kind they want.
switch (nameType)
{
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
matchType = GeneralNameType.DnsName;
break;
case X509NameType.SimpleName:
case X509NameType.EmailName:
matchType = GeneralNameType.Email;
break;
case X509NameType.UpnName:
matchType = GeneralNameType.OtherName;
otherOid = Oids.UserPrincipalName;
break;
case X509NameType.UrlName:
matchType = GeneralNameType.UniformResourceIdentifier;
break;
}
if (matchType.HasValue)
{
foreach (X509Extension extension in _certData.Extensions)
{
if (extension.Oid.Value == extensionId)
{
string candidate = FindAltNameMatch(extension.RawData, matchType.Value, otherOid);
if (candidate != null)
{
return candidate;
}
}
}
}
else
{
Debug.Fail($"Unresolved matchType for X509NameType.{nameType}");
}
}
// Subject-based fallback
{
string expectedKey = null;
switch (nameType)
{
case X509NameType.EmailName:
expectedKey = Oids.EmailAddress;
break;
case X509NameType.DnsName:
// Note: This does not include DnsFromAlternativeName, since
// the subject (or issuer) is not the Alternative Name.
expectedKey = Oids.CommonName;
break;
}
if (expectedKey != null)
{
X500DistinguishedName name = forIssuer ? _certData.Issuer : _certData.Subject;
foreach (var kvp in ReadReverseRdns(name))
{
if (kvp.Key == expectedKey)
{
return kvp.Value;
}
}
}
}
return "";
}
private static string GetSimpleNameInfo(X500DistinguishedName name)
{
string ou = null;
string o = null;
string e = null;
string firstRdn = null;
foreach (var kvp in ReadReverseRdns(name))
{
string oid = kvp.Key;
string value = kvp.Value;
// TODO: Check this (and the OpenSSL-using version) if OU/etc are specified more than once.
// (Compare against Windows)
switch (oid)
{
case Oids.CommonName:
return value;
case Oids.OrganizationalUnit:
ou = value;
break;
case Oids.Organization:
o = value;
break;
case Oids.EmailAddress:
e = value;
break;
default:
if (firstRdn == null)
{
firstRdn = value;
}
break;
}
}
return ou ?? o ?? e ?? firstRdn;
}
private static string FindAltNameMatch(byte[] extensionBytes, GeneralNameType matchType, string otherOid)
{
// If Other, have OID, else, no OID.
Debug.Assert(
(otherOid == null) == (matchType != GeneralNameType.OtherName),
$"otherOid has incorrect nullarity for matchType {matchType}");
Debug.Assert(
matchType == GeneralNameType.UniformResourceIdentifier ||
matchType == GeneralNameType.DnsName ||
matchType == GeneralNameType.Email ||
matchType == GeneralNameType.OtherName,
$"matchType ({matchType}) is not currently supported");
Debug.Assert(
otherOid == null || otherOid == Oids.UserPrincipalName,
$"otherOid ({otherOid}) is not supported");
// SubjectAltName ::= GeneralNames
//
// IssuerAltName ::= GeneralNames
//
// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
//
// GeneralName ::= CHOICE {
// otherName [0] OtherName,
// rfc822Name [1] IA5String,
// dNSName [2] IA5String,
// x400Address [3] ORAddress,
// directoryName [4] Name,
// ediPartyName [5] EDIPartyName,
// uniformResourceIdentifier [6] IA5String,
// iPAddress [7] OCTET STRING,
// registeredID [8] OBJECT IDENTIFIER }
//
// OtherName::= SEQUENCE {
// type - id OBJECT IDENTIFIER,
// value[0] EXPLICIT ANY DEFINED BY type - id }
byte expectedTag = (byte)(DerSequenceReader.ContextSpecificTagFlag | (byte)matchType);
if (matchType == GeneralNameType.OtherName)
{
expectedTag |= DerSequenceReader.ConstructedFlag;
}
DerSequenceReader altNameReader = new DerSequenceReader(extensionBytes);
while (altNameReader.HasData)
{
if (altNameReader.PeekTag() != expectedTag)
{
altNameReader.SkipValue();
continue;
}
switch (matchType)
{
case GeneralNameType.OtherName:
{
DerSequenceReader otherNameReader = altNameReader.ReadSequence();
string oid = otherNameReader.ReadOidAsString();
if (oid == otherOid)
{
// Payload is value[0] EXPLICIT, meaning
// a) it'll be tagged as ContextSpecific0
// b) that's interpretable as a Sequence (EXPLICIT)
// c) the payload will then be retagged as the correct type (EXPLICIT)
if (otherNameReader.PeekTag() != DerSequenceReader.ContextSpecificConstructedTag0)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
otherNameReader = otherNameReader.ReadSequence();
// Currently only UPN is supported, which is a UTF8 string per
// https://msdn.microsoft.com/en-us/library/ff842518.aspx
return otherNameReader.ReadUtf8String();
}
// If the OtherName OID didn't match, move to the next entry.
continue;
}
case GeneralNameType.Rfc822Name:
case GeneralNameType.DnsName:
case GeneralNameType.UniformResourceIdentifier:
return altNameReader.ReadIA5String();
default:
altNameReader.SkipValue();
continue;
}
}
return null;
}
public void AppendPrivateKeyInfo(StringBuilder sb)
{
if (!HasPrivateKey)
{
return;
}
// There's nothing really to say about the key, just acknowledge there is one.
sb.AppendLine();
sb.AppendLine();
sb.AppendLine("[Private Key]");
}
private void EnsureCertData()
{
if (_readCertData)
return;
Debug.Assert(!_certHandle.IsInvalid);
_certData = new CertificateData(Interop.AppleCrypto.X509GetRawData(_certHandle));
_readCertData = true;
}
private static IEnumerable<KeyValuePair<string, string>> ReadReverseRdns(X500DistinguishedName name)
{
DerSequenceReader x500NameReader = new DerSequenceReader(name.RawData);
var rdnReaders = new Stack<DerSequenceReader>();
while (x500NameReader.HasData)
{
rdnReaders.Push(x500NameReader.ReadSet());
}
while (rdnReaders.Count > 0)
{
DerSequenceReader rdnReader = rdnReaders.Pop();
while (rdnReader.HasData)
{
DerSequenceReader tavReader = rdnReader.ReadSequence();
string oid = tavReader.ReadOidAsString();
var tag = (DerSequenceReader.DerTag)tavReader.PeekTag();
string value = null;
switch (tag)
{
case DerSequenceReader.DerTag.BMPString:
value = tavReader.ReadBMPString();
break;
case DerSequenceReader.DerTag.IA5String:
value = tavReader.ReadIA5String();
break;
case DerSequenceReader.DerTag.PrintableString:
value = tavReader.ReadPrintableString();
break;
case DerSequenceReader.DerTag.UTF8String:
value = tavReader.ReadUtf8String();
break;
// Ignore anything we don't know how to read.
}
if (value != null)
{
yield return new KeyValuePair<string, string>(oid, value);
}
}
}
}
}
internal enum GeneralNameType
{
OtherName = 0,
Rfc822Name = 1,
// RFC 822: Standard for the format of ARPA Internet Text Messages.
// That means "email", and an RFC 822 Name: "Email address"
Email = Rfc822Name,
DnsName = 2,
X400Address = 3,
DirectoryName = 4,
EdiPartyName = 5,
UniformResourceIdentifier = 6,
IPAddress = 7,
RegisteredId = 8,
}
internal struct CertificateData
{
internal struct AlgorithmIdentifier
{
internal string AlgorithmId;
internal byte[] Parameters;
}
internal byte[] RawData;
internal byte[] SubjectPublicKeyInfo;
internal int Version;
internal byte[] SerialNumber;
internal AlgorithmIdentifier TbsSignature;
internal X500DistinguishedName Issuer;
internal DateTime NotBefore;
internal DateTime NotAfter;
internal X500DistinguishedName Subject;
internal AlgorithmIdentifier PublicKeyAlgorithm;
internal byte[] PublicKey;
internal byte[] IssuerUniqueId;
internal byte[] SubjectUniqueId;
internal List<X509Extension> Extensions;
internal AlgorithmIdentifier SignatureAlgorithm;
internal byte[] SignatureValue;
internal CertificateData(byte[] rawData)
{
#if DEBUG
try
{
#endif
DerSequenceReader reader = new DerSequenceReader(rawData);
DerSequenceReader tbsCertificate = reader.ReadSequence();
if (tbsCertificate.PeekTag() == DerSequenceReader.ContextSpecificConstructedTag0)
{
DerSequenceReader version = tbsCertificate.ReadSequence();
Version = version.ReadInteger();
}
else if (tbsCertificate.PeekTag() != (byte)DerSequenceReader.DerTag.Integer)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
else
{
Version = 0;
}
if (Version < 0 || Version > 2)
throw new CryptographicException();
SerialNumber = tbsCertificate.ReadIntegerBytes();
DerSequenceReader tbsSignature = tbsCertificate.ReadSequence();
TbsSignature.AlgorithmId = tbsSignature.ReadOidAsString();
TbsSignature.Parameters = tbsSignature.HasData ? tbsSignature.ReadNextEncodedValue() : Array.Empty<byte>();
if (tbsSignature.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
Issuer = new X500DistinguishedName(tbsCertificate.ReadNextEncodedValue());
DerSequenceReader validity = tbsCertificate.ReadSequence();
NotBefore = validity.ReadX509Date();
NotAfter = validity.ReadX509Date();
if (validity.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
Subject = new X500DistinguishedName(tbsCertificate.ReadNextEncodedValue());
SubjectPublicKeyInfo = tbsCertificate.ReadNextEncodedValue();
DerSequenceReader subjectPublicKeyInfo = new DerSequenceReader(SubjectPublicKeyInfo);
DerSequenceReader subjectKeyAlgorithm = subjectPublicKeyInfo.ReadSequence();
PublicKeyAlgorithm.AlgorithmId = subjectKeyAlgorithm.ReadOidAsString();
PublicKeyAlgorithm.Parameters = subjectKeyAlgorithm.HasData ? subjectKeyAlgorithm.ReadNextEncodedValue() : Array.Empty<byte>();
if (subjectKeyAlgorithm.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
PublicKey = subjectPublicKeyInfo.ReadBitString();
if (subjectPublicKeyInfo.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
if (Version > 0 &&
tbsCertificate.HasData &&
tbsCertificate.PeekTag() == DerSequenceReader.ContextSpecificConstructedTag1)
{
IssuerUniqueId = tbsCertificate.ReadBitString();
}
else
{
IssuerUniqueId = null;
}
if (Version > 0 &&
tbsCertificate.HasData &&
tbsCertificate.PeekTag() == DerSequenceReader.ContextSpecificConstructedTag2)
{
SubjectUniqueId = tbsCertificate.ReadBitString();
}
else
{
SubjectUniqueId = null;
}
Extensions = new List<X509Extension>();
if (Version > 1 &&
tbsCertificate.HasData &&
tbsCertificate.PeekTag() == DerSequenceReader.ContextSpecificConstructedTag3)
{
DerSequenceReader extensions = tbsCertificate.ReadSequence();
extensions = extensions.ReadSequence();
while (extensions.HasData)
{
DerSequenceReader extensionReader = extensions.ReadSequence();
string oid = extensionReader.ReadOidAsString();
bool critical = false;
if (extensionReader.PeekTag() == (byte)DerSequenceReader.DerTag.Boolean)
{
critical = extensionReader.ReadBoolean();
}
byte[] extensionData = extensionReader.ReadOctetString();
Extensions.Add(new X509Extension(oid, extensionData, critical));
if (extensionReader.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
}
if (tbsCertificate.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
DerSequenceReader signatureAlgorithm = reader.ReadSequence();
SignatureAlgorithm.AlgorithmId = signatureAlgorithm.ReadOidAsString();
SignatureAlgorithm.Parameters = signatureAlgorithm.HasData ? signatureAlgorithm.ReadNextEncodedValue() : Array.Empty<byte>();
if (signatureAlgorithm.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
SignatureValue = reader.ReadBitString();
if (reader.HasData)
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
RawData = rawData;
#if DEBUG
}
catch (Exception e)
{
throw new CryptographicException(
$"Error in reading certificate:{Environment.NewLine}{PemPrintCert(rawData)}",
e);
}
#endif
}
#if DEBUG
private static string PemPrintCert(byte[] rawData)
{
const string PemHeader = "-----BEGIN CERTIFICATE-----";
const string PemFooter = "-----END CERTIFICATE-----";
StringBuilder builder = new StringBuilder(PemHeader.Length + PemFooter.Length + rawData.Length * 2);
builder.Append(PemHeader);
builder.AppendLine();
builder.Append(Convert.ToBase64String(rawData, Base64FormattingOptions.InsertLineBreaks));
builder.AppendLine();
builder.Append(PemFooter);
builder.AppendLine();
return builder.ToString();
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Internal;
using System.Text.Unicode;
namespace System.Text.Encodings.Web.Tests
{
internal unsafe abstract class UnicodeEncoderBase
{
// A bitmap of characters which are allowed to be returned unescaped.
private AllowedCharactersBitmap _allowedCharacters;
// The worst-case number of output chars generated for any input char.
private readonly int _maxOutputCharsPerInputChar;
/// <summary>
/// Instantiates an encoder using a custom allow list of characters.
/// </summary>
protected UnicodeEncoderBase(TextEncoderSettings filter, int maxOutputCharsPerInputChar)
{
_maxOutputCharsPerInputChar = maxOutputCharsPerInputChar;
_allowedCharacters = filter.GetAllowedCharacters();
// Forbid characters that are special in HTML.
// Even though this is a common encoder used by everybody (including URL
// and JavaScript strings), it's unfortunately common for developers to
// forget to HTML-encode a string once it has been URL-encoded or
// JavaScript string-escaped, so this offers extra protection.
ForbidCharacter('<');
ForbidCharacter('>');
ForbidCharacter('&');
ForbidCharacter('\''); // can be used to escape attributes
ForbidCharacter('\"'); // can be used to escape attributes
ForbidCharacter('+'); // technically not HTML-specific, but can be used to perform UTF7-based attacks
// Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed
// (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp)
_allowedCharacters.ForbidUndefinedCharacters();
}
// Marks a character as forbidden (must be returned encoded)
protected void ForbidCharacter(char c)
{
_allowedCharacters.ForbidCharacter(c);
}
/// <summary>
/// Entry point to the encoder.
/// </summary>
public void Encode(char[] value, int startIndex, int characterCount, TextWriter output)
{
// Input checking
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
ValidateInputs(startIndex, characterCount, actualInputLength: value.Length);
if (characterCount != 0)
{
fixed (char* pChars = value)
{
int indexOfFirstCharWhichRequiresEncoding = GetIndexOfFirstCharWhichRequiresEncoding(&pChars[startIndex], characterCount);
if (indexOfFirstCharWhichRequiresEncoding < 0)
{
// All chars are valid - just copy the buffer as-is.
output.Write(value, startIndex, characterCount);
}
else
{
// Flush all chars which are known to be valid, then encode the remainder individually
if (indexOfFirstCharWhichRequiresEncoding > 0)
{
output.Write(value, startIndex, indexOfFirstCharWhichRequiresEncoding);
}
EncodeCore(&pChars[startIndex + indexOfFirstCharWhichRequiresEncoding], (uint)(characterCount - indexOfFirstCharWhichRequiresEncoding), output);
}
}
}
}
/// <summary>
/// Entry point to the encoder.
/// </summary>
public string Encode(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
// Quick check: does the string need to be encoded at all?
// If not, just return the input string as-is.
for (int i = 0; i < value.Length; i++)
{
if (!IsCharacterAllowed(value[i]))
{
return EncodeCore(value, idxOfFirstCharWhichRequiresEncoding: i);
}
}
return value;
}
/// <summary>
/// Entry point to the encoder.
/// </summary>
public void Encode(string value, int startIndex, int characterCount, TextWriter output)
{
// Input checking
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
ValidateInputs(startIndex, characterCount, actualInputLength: value.Length);
if (characterCount != 0)
{
fixed (char* pChars = value)
{
if (characterCount == value.Length)
{
// Optimize for the common case: we're being asked to encode the entire input string
// (not just a subset). If all characters are safe, we can just spit it out as-is.
int indexOfFirstCharWhichRequiresEncoding = GetIndexOfFirstCharWhichRequiresEncoding(pChars, characterCount);
if (indexOfFirstCharWhichRequiresEncoding < 0)
{
output.Write(value);
}
else
{
// Flush all chars which are known to be valid, then encode the remainder individually
for (int i = 0; i < indexOfFirstCharWhichRequiresEncoding; i++)
{
output.Write(pChars[i]);
}
EncodeCore(&pChars[indexOfFirstCharWhichRequiresEncoding], (uint)(characterCount - indexOfFirstCharWhichRequiresEncoding), output);
}
}
else
{
// We're being asked to encode a subset, so we need to go through the slow path of appending
// each character individually.
EncodeCore(&pChars[startIndex], (uint)characterCount, output);
}
}
}
}
private string EncodeCore(string input, int idxOfFirstCharWhichRequiresEncoding)
{
Debug.Assert(idxOfFirstCharWhichRequiresEncoding >= 0);
Debug.Assert(idxOfFirstCharWhichRequiresEncoding < input.Length);
int numCharsWhichMayRequireEncoding = input.Length - idxOfFirstCharWhichRequiresEncoding;
int sbCapacity = checked(idxOfFirstCharWhichRequiresEncoding + EncoderCommon.GetCapacityOfOutputStringBuilder(numCharsWhichMayRequireEncoding, _maxOutputCharsPerInputChar));
Debug.Assert(sbCapacity >= input.Length);
// Allocate the StringBuilder with the first (known to not require encoding) part of the input string,
// then begin encoding from the last (potentially requiring encoding) part of the input string.
StringBuilder builder = new StringBuilder(input, 0, idxOfFirstCharWhichRequiresEncoding, sbCapacity);
Writer writer = new Writer(builder);
fixed (char* pInput = input)
{
EncodeCore(ref writer, &pInput[idxOfFirstCharWhichRequiresEncoding], (uint)numCharsWhichMayRequireEncoding);
}
return builder.ToString();
}
private void EncodeCore(char* input, uint charsRemaining, TextWriter output)
{
Writer writer = new Writer(output);
EncodeCore(ref writer, input, charsRemaining);
}
private void EncodeCore(ref Writer writer, char* input, uint charsRemaining)
{
while (charsRemaining != 0)
{
int nextScalar = UnicodeHelpers.GetScalarValueFromUtf16(input, endOfString: (charsRemaining == 1));
if (UnicodeHelpers.IsSupplementaryCodePoint(nextScalar))
{
// Supplementary characters should always be encoded numerically.
WriteEncodedScalar(ref writer, (uint)nextScalar);
// We consume two UTF-16 characters for a single supplementary character.
input += 2;
charsRemaining -= 2;
}
else
{
// Otherwise, this was a BMP character.
input++;
charsRemaining--;
char c = (char)nextScalar;
if (IsCharacterAllowed(c))
{
writer.Write(c);
}
else
{
WriteEncodedScalar(ref writer, (uint)nextScalar);
}
}
}
}
private int GetIndexOfFirstCharWhichRequiresEncoding(char* input, int inputLength)
{
for (int i = 0; i < inputLength; i++)
{
if (!IsCharacterAllowed(input[i]))
{
return i;
}
}
return -1; // no characters require encoding
}
// Determines whether the given character can be returned unencoded.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool IsCharacterAllowed(char c)
{
return _allowedCharacters.IsCharacterAllowed(c);
}
private static void ValidateInputs(int startIndex, int characterCount, int actualInputLength)
{
if (startIndex < 0 || startIndex > actualInputLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (characterCount < 0 || characterCount > (actualInputLength - startIndex))
{
throw new ArgumentOutOfRangeException(nameof(characterCount));
}
}
protected abstract void WriteEncodedScalar(ref Writer writer, uint value);
/// <summary>
/// Provides an abstraction over both StringBuilder and TextWriter.
/// Declared as a struct so we can allocate on the stack and pass by
/// reference. Eliminates chatty virtual dispatches on hot paths.
/// </summary>
protected struct Writer
{
private readonly StringBuilder _innerBuilder;
private readonly TextWriter _innerWriter;
public Writer(StringBuilder innerBuilder)
{
_innerBuilder = innerBuilder;
_innerWriter = null;
}
public Writer(TextWriter innerWriter)
{
_innerBuilder = null;
_innerWriter = innerWriter;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(char value)
{
if (_innerBuilder != null)
{
_innerBuilder.Append(value);
}
else
{
_innerWriter.Write(value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write(string value)
{
if (_innerBuilder != null)
{
_innerBuilder.Append(value);
}
else
{
_innerWriter.Write(value);
}
}
}
}
}
| |
namespace android.location
{
[global::MonoJavaBridge.JavaClass()]
public partial class LocationManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected LocationManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::android.location.LocationProvider getProvider(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.location.LocationManager.staticClass, "getProvider", "(Ljava/lang/String;)Landroid/location/LocationProvider;", ref global::android.location.LocationManager._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.location.LocationProvider;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::java.util.List getProviders(bool arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.location.LocationManager.staticClass, "getProviders", "(Z)Ljava/util/List;", ref global::android.location.LocationManager._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual global::java.util.List getProviders(android.location.Criteria arg0, bool arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.location.LocationManager.staticClass, "getProviders", "(Landroid/location/Criteria;Z)Ljava/util/List;", ref global::android.location.LocationManager._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.util.List;
}
public new global::java.util.List AllProviders
{
get
{
return getAllProviders();
}
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual global::java.util.List getAllProviders()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.location.LocationManager.staticClass, "getAllProviders", "()Ljava/util/List;", ref global::android.location.LocationManager._m3) as java.util.List;
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::java.lang.String getBestProvider(android.location.Criteria arg0, bool arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.location.LocationManager.staticClass, "getBestProvider", "(Landroid/location/Criteria;Z)Ljava/lang/String;", ref global::android.location.LocationManager._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual void requestLocationUpdates(java.lang.String arg0, long arg1, float arg2, android.location.LocationListener arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "requestLocationUpdates", "(Ljava/lang/String;JFLandroid/location/LocationListener;)V", ref global::android.location.LocationManager._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void requestLocationUpdates(java.lang.String arg0, long arg1, float arg2, android.location.LocationListener arg3, android.os.Looper arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "requestLocationUpdates", "(Ljava/lang/String;JFLandroid/location/LocationListener;Landroid/os/Looper;)V", ref global::android.location.LocationManager._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void requestLocationUpdates(java.lang.String arg0, long arg1, float arg2, android.app.PendingIntent arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "requestLocationUpdates", "(Ljava/lang/String;JFLandroid/app/PendingIntent;)V", ref global::android.location.LocationManager._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void removeUpdates(android.location.LocationListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "removeUpdates", "(Landroid/location/LocationListener;)V", ref global::android.location.LocationManager._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void removeUpdates(android.app.PendingIntent arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "removeUpdates", "(Landroid/app/PendingIntent;)V", ref global::android.location.LocationManager._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual void addProximityAlert(double arg0, double arg1, float arg2, long arg3, android.app.PendingIntent arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "addProximityAlert", "(DDFJLandroid/app/PendingIntent;)V", ref global::android.location.LocationManager._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual void removeProximityAlert(android.app.PendingIntent arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "removeProximityAlert", "(Landroid/app/PendingIntent;)V", ref global::android.location.LocationManager._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual bool isProviderEnabled(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.LocationManager.staticClass, "isProviderEnabled", "(Ljava/lang/String;)Z", ref global::android.location.LocationManager._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual global::android.location.Location getLastKnownLocation(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.location.LocationManager.staticClass, "getLastKnownLocation", "(Ljava/lang/String;)Landroid/location/Location;", ref global::android.location.LocationManager._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.location.Location;
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void addTestProvider(java.lang.String arg0, bool arg1, bool arg2, bool arg3, bool arg4, bool arg5, bool arg6, bool arg7, int arg8, int arg9)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "addTestProvider", "(Ljava/lang/String;ZZZZZZZII)V", ref global::android.location.LocationManager._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9));
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void removeTestProvider(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "removeTestProvider", "(Ljava/lang/String;)V", ref global::android.location.LocationManager._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setTestProviderLocation(java.lang.String arg0, android.location.Location arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "setTestProviderLocation", "(Ljava/lang/String;Landroid/location/Location;)V", ref global::android.location.LocationManager._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void clearTestProviderLocation(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "clearTestProviderLocation", "(Ljava/lang/String;)V", ref global::android.location.LocationManager._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setTestProviderEnabled(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "setTestProviderEnabled", "(Ljava/lang/String;Z)V", ref global::android.location.LocationManager._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void clearTestProviderEnabled(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "clearTestProviderEnabled", "(Ljava/lang/String;)V", ref global::android.location.LocationManager._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setTestProviderStatus(java.lang.String arg0, int arg1, android.os.Bundle arg2, long arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "setTestProviderStatus", "(Ljava/lang/String;ILandroid/os/Bundle;J)V", ref global::android.location.LocationManager._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void clearTestProviderStatus(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "clearTestProviderStatus", "(Ljava/lang/String;)V", ref global::android.location.LocationManager._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual bool addGpsStatusListener(android.location.GpsStatus.Listener arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.LocationManager.staticClass, "addGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)Z", ref global::android.location.LocationManager._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public bool addGpsStatusListener(global::android.location.GpsStatus.ListenerDelegate arg0)
{
return addGpsStatusListener((global::android.location.GpsStatus.ListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void removeGpsStatusListener(android.location.GpsStatus.Listener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "removeGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)V", ref global::android.location.LocationManager._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void removeGpsStatusListener(global::android.location.GpsStatus.ListenerDelegate arg0)
{
removeGpsStatusListener((global::android.location.GpsStatus.ListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual bool addNmeaListener(android.location.GpsStatus.NmeaListener arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.LocationManager.staticClass, "addNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)Z", ref global::android.location.LocationManager._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public bool addNmeaListener(global::android.location.GpsStatus.NmeaListenerDelegate arg0)
{
return addNmeaListener((global::android.location.GpsStatus.NmeaListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual void removeNmeaListener(android.location.GpsStatus.NmeaListener arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.LocationManager.staticClass, "removeNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)V", ref global::android.location.LocationManager._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void removeNmeaListener(global::android.location.GpsStatus.NmeaListenerDelegate arg0)
{
removeNmeaListener((global::android.location.GpsStatus.NmeaListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual global::android.location.GpsStatus getGpsStatus(android.location.GpsStatus arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.location.GpsStatus>(this, global::android.location.LocationManager.staticClass, "getGpsStatus", "(Landroid/location/GpsStatus;)Landroid/location/GpsStatus;", ref global::android.location.LocationManager._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.location.GpsStatus;
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual bool sendExtraCommand(java.lang.String arg0, java.lang.String arg1, android.os.Bundle arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.LocationManager.staticClass, "sendExtraCommand", "(Ljava/lang/String;Ljava/lang/String;Landroid/os/Bundle;)Z", ref global::android.location.LocationManager._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public static global::java.lang.String NETWORK_PROVIDER
{
get
{
return "network";
}
}
public static global::java.lang.String GPS_PROVIDER
{
get
{
return "gps";
}
}
public static global::java.lang.String PASSIVE_PROVIDER
{
get
{
return "passive";
}
}
public static global::java.lang.String KEY_PROXIMITY_ENTERING
{
get
{
return "entering";
}
}
public static global::java.lang.String KEY_STATUS_CHANGED
{
get
{
return "status";
}
}
public static global::java.lang.String KEY_PROVIDER_ENABLED
{
get
{
return "providerEnabled";
}
}
public static global::java.lang.String KEY_LOCATION_CHANGED
{
get
{
return "location";
}
}
static LocationManager()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.location.LocationManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/LocationManager"));
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.IO.Tests
{
public class Directory_CreateDirectory : FileSystemTest
{
public static TheoryData ReservedDeviceNames = IOInputs.GetReservedDeviceNames().ToTheoryData();
#region Utilities
public virtual DirectoryInfo Create(string path)
{
return Directory.CreateDirectory(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => Create(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => Create(string.Empty));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void PathWithInvalidCharactersAsPath_Desktop(string invalidPath)
{
Assert.Throws<ArgumentException>(() => Create(invalidPath));
}
[ActiveIssue(27269)]
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void PathWithInvalidCharactersAsPath_Core(string invalidPath)
{
if (invalidPath.Contains('\0'))
Assert.Throws<ArgumentException>("path", () => Create(invalidPath));
else
Assert.Throws<IOException>(() => Create(invalidPath));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.Throws<IOException>(() => Create(path));
Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
DirectoryInfo testDir = Create(GetTestFilePath());
FileAttributes original = testDir.Attributes;
try
{
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName);
}
finally
{
testDir.Attributes = original;
}
}
[Fact]
public void RootPath()
{
string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory());
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFilePath();
DirectoryInfo result = Create(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName);
result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName);
}
[Fact]
public void CreateCurrentDirectory()
{
DirectoryInfo result = Create(Directory.GetCurrentDirectory());
Assert.Equal(Directory.GetCurrentDirectory(), result.FullName);
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Theory, MemberData(nameof(ValidPathComponentNames))]
public void ValidPathWithTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
}
[ConditionalTheory(nameof(UsingNewNormalization)),
MemberData(nameof(ValidPathComponentNames))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // trailing slash
public void ValidExtendedPathWithTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
}
[Theory,
MemberData(nameof(ValidPathComponentNames))]
public void ValidPathWithoutTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = testDir.FullName + Path.DirectorySeparatorChar + component;
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce()
{
DirectoryInfo testDir = Create(GetTestFilePath());
string path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory);
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Theory,
MemberData(nameof(PathsWithComponentLongerThanMaxComponent))]
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsException(string path)
{
// While paths themselves can be up to 260 characters including trailing null, file systems
// limit each components of the path to a total of 255 characters on Desktop.
if (PlatformDetection.IsFullFramework)
{
Assert.Throws<PathTooLongException>(() => Create(path));
}
else
{
AssertExtensions.ThrowsAny<IOException, DirectoryNotFoundException, PathTooLongException>(() => Create(path));
}
}
#endregion
#region PlatformSpecific
[Theory, MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void PathWithInvalidColons_ThrowsNotSupportedException_Desktop(string invalidPath)
{
if (PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Throws<ArgumentException>(() => Create(invalidPath));
}
else
{
Assert.Throws<NotSupportedException>(() => Create(invalidPath));
}
}
[ActiveIssue(27269)]
[Theory, MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void PathsWithInvalidColons_ThrowIOException_Core(string invalidPath)
{
// You can't actually create a directory with a colon in it. It was a preemptive
// check, now we let the OS give us failures on usage.
Assert.ThrowsAny<IOException>(() => Create(invalidPath));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds
public void DirectoryLongerThanMaxPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath());
Assert.All(paths, (path) =>
{
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path throws PathTooLongException
public void DirectoryLongerThanMaxLongPath_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath());
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)]
public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsException()
{
var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true);
// Long directory path with extended syntax throws PathTooLongException on Desktop.
// Everywhere else, it may be either PathTooLongException or DirectoryNotFoundException
if (PlatformDetection.IsFullFramework)
{
Assert.All(paths, path => { Assert.Throws<PathTooLongException>(() => Create(path)); });
}
else
{
Assert.All(paths,
path =>
{
AssertExtensions
.ThrowsAny<PathTooLongException, DirectoryNotFoundException>(
() => Create(path));
});
}
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path with extended syntax succeeds
public void ExtendedDirectoryLongerThanLegacyMaxPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath(), useExtendedSyntax: true);
Assert.All(paths, (path) =>
{
Assert.True(Create(path).Exists);
});
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds
public void DirectoryLongerThanMaxDirectoryAsPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath());
Assert.All(paths, (path) =>
{
var result = Create(path);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // long directory path allowed
public void UnixPathLongerThan256_Allowed()
{
DirectoryInfo testDir = Create(GetTestFilePath());
string path = IOServices.GetPath(testDir.FullName, 257);
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // deeply nested directories allowed
public void UnixPathWithDeeplyNestedDirectories()
{
DirectoryInfo parent = Create(GetTestFilePath());
for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories
{
parent = Create(Path.Combine(parent.FullName, "dir" + i));
Assert.True(Directory.Exists(parent.FullName));
}
}
[Theory,
MemberData(nameof(SimpleWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
public void WindowsSimpleWhiteSpaceAsPath_ThrowsArgumentException(string path)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsControlWhiteSpaceAsPath_ThrowsArgumentException_Desktop(string path)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
[ActiveIssue(27269)]
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsWhiteSpaceAsPath_ThrowsIOException_Core(string path)
{
Assert.Throws<IOException>(() => Create(path));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // whitespace as path allowed
public void UnixWhiteSpaceAsPath_Allowed(string path)
{
Create(Path.Combine(TestDirectory, path));
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
}
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] // e.g. NetFX only
public void TrailingWhiteSpace_Trimmed(string component)
{
// On desktop, we trim a number of whitespace characters
DirectoryInfo testDir = Create(GetTestFilePath());
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
[Theory,
MemberData(nameof(NonControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Not NetFX
public void TrailingWhiteSpace_NotTrimmed(string component)
{
// In CoreFX we don't trim anything other than space (' ')
DirectoryInfo testDir = Create(GetTestFilePath() + component);
string path = IOServices.RemoveTrailingSlash(testDir.FullName);
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
[Theory,
MemberData(nameof(SimpleWhiteSpace))] //*Just Spaces*
[PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Not NetFX
public void TrailingSpace_NotTrimmed(string component)
{
DirectoryInfo testDir = Create(GetTestFilePath());
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
[ConditionalTheory(nameof(UsingNewNormalization)),
MemberData(nameof(SimpleWhiteSpace))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // extended syntax with whitespace
public void WindowsExtendedSyntaxWhiteSpace(string path)
{
string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + TestDirectory, path);
Directory.CreateDirectory(extendedPath);
Assert.True(Directory.Exists(extendedPath), extendedPath);
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // trailing whitespace in path treated as significant on Unix
public void UnixNonSignificantTrailingWhiteSpace(string component)
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Create(GetTestFilePath());
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
[Theory,
MemberData(nameof(PathsWithColons))]
[PlatformSpecific(TestPlatforms.Windows)] // alternate data streams
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void PathWithColons_ThrowsNotSupportedException_Desktop(string path)
{
Assert.Throws<NotSupportedException>(() => Create(path));
}
[ActiveIssue(27269)]
[Theory,
MemberData(nameof(PathsWithColons))]
[PlatformSpecific(TestPlatforms.Windows)] // alternate data streams
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void PathWithColons_ThrowsIOException_Core(string path)
{
Assert.ThrowsAny<IOException>(() => Create(Path.Combine(TestDirectory, path)));
}
[Theory,
MemberData(nameof(PathsWithReservedDeviceNames))]
[PlatformSpecific(TestPlatforms.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException(string path)
{
// Throws DirectoryNotFoundException, when the behavior really should be an invalid path
Assert.Throws<DirectoryNotFoundException>(() => Create(path));
}
[ConditionalTheory(nameof(UsingNewNormalization)),
MemberData(nameof(ReservedDeviceNames))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsExtendedPath(string path)
{
Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, path)).Exists, path);
}
[Theory,
MemberData(nameof(UncPathsWithoutShareName))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void UncPathWithoutShareNameAsPath_ThrowsArgumentException_Desktop(string path)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
[ActiveIssue(27269)]
[Theory,
MemberData(nameof(UncPathsWithoutShareName))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void UncPathWithoutShareNameAsPath_ThrowsIOException_Core(string path)
{
Assert.ThrowsAny<IOException>(() => Create(path));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void UNCPathWithOnlySlashes_Desktop()
{
Assert.Throws<ArgumentException>(() => Create("//"));
}
[ActiveIssue(27269)]
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void UNCPathWithOnlySlashes_Core()
{
Assert.ThrowsAny<IOException>(() => Create("//"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
public void CDriveCase()
{
DirectoryInfo dir = Create("c:\\");
DirectoryInfo dir2 = Create("C:\\");
Assert.NotEqual(dir.FullName, dir2.FullName);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // drive letters
public void DriveLetter_Windows()
{
// On Windows, DirectoryInfo will replace "<DriveLetter>:" with "."
var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":");
var current = Create(".");
Assert.Equal(current.Name, driveLetter.Name);
Assert.Equal(current.FullName, driveLetter.FullName);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // drive letters casing
public void DriveLetter_Unix()
{
// On Unix, there's no special casing for drive letters. These may or may not be valid names, depending
// on the file system underlying the current directory. Unix file systems typically allow these, but,
// for example, these names are not allowed if running on a file system mounted from a Windows machine.
DirectoryInfo driveLetter;
try
{
driveLetter = Create("C:");
}
catch (IOException)
{
return;
}
var current = Create(".");
Assert.Equal("C:", driveLetter.Name);
Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName);
try
{
// If this test is inherited then it's possible this call will fail due to the "C:" directory
// being deleted in that other test before this call. What we care about testing (proper path
// handling) is unaffected by this race condition.
Directory.Delete("C:");
}
catch (DirectoryNotFoundException) { }
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(IOServices.GetNonExistentDrive());
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory"));
});
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException()
{ // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(drive);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // testing drive labels
[ActiveIssue(1221)]
public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
// 'Device is not ready'
Assert.Throws<IOException>(() =>
{
Create(Path.Combine(drive, "Subdirectory"));
});
}
#if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL
/*
[Fact]
public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
using (CurrentDirectoryContext context = new CurrentDirectoryContext(root))
{
DirectoryInfo result = Create("..");
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(root, result.FullName);
}
}
*/
#endif
#endregion
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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.Runtime.InteropServices;
using System.ComponentModel;
using System.Xml.Serialization;
namespace Urho
{
/// <summary>
/// Represents a Quaternion.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion : IEquatable<Quaternion>
{
#region Fields
float w;
Vector3 xyz;
#endregion
#region Constructors
/// <summary>
/// Construct a new Quaternion from vector and w components
/// </summary>
/// <param name="v">The vector part</param>
/// <param name="w">The w part</param>
public Quaternion(Vector3 v, float w)
{
this.xyz = v;
this.w = w;
}
/// <summary>
/// Construct a new Quaternion
/// </summary>
/// <param name="x">The x component</param>
/// <param name="y">The y component</param>
/// <param name="z">The z component</param>
/// <param name="w">The w component</param>
public Quaternion(float x, float y, float z, float w)
: this(new Vector3(x, y, z), w)
{ }
// From Euler angles
public Quaternion (float x, float y, float z)
{
const float M_DEGTORAD_2 = (float)Math.PI / 360.0f;
x *= M_DEGTORAD_2;
y *= M_DEGTORAD_2;
z *= M_DEGTORAD_2;
float sinX = (float)Math.Sin(x);
float cosX = (float)Math.Cos(x);
float sinY = (float)Math.Sin(y);
float cosY = (float)Math.Cos(y);
float sinZ = (float)Math.Sin(z);
float cosZ = (float)Math.Cos(z);
xyz = new Vector3(cosY * sinX * cosZ + sinY * cosX * sinZ,
sinY * cosX * cosZ - cosY * sinX * sinZ,
cosY * cosX * sinZ - sinY * sinX * cosZ);
w = cosY * cosX * cosZ + sinY * sinX * sinZ;
}
public Quaternion (ref Matrix3 matrix)
{
double scale = System.Math.Pow(matrix.Determinant, 1.0d / 3.0d);
float x, y, z;
w = (float) (System.Math.Sqrt(System.Math.Max(0, scale + matrix[0, 0] + matrix[1, 1] + matrix[2, 2])) / 2);
x = (float) (System.Math.Sqrt(System.Math.Max(0, scale + matrix[0, 0] - matrix[1, 1] - matrix[2, 2])) / 2);
y = (float) (System.Math.Sqrt(System.Math.Max(0, scale - matrix[0, 0] + matrix[1, 1] - matrix[2, 2])) / 2);
z = (float) (System.Math.Sqrt(System.Math.Max(0, scale - matrix[0, 0] - matrix[1, 1] + matrix[2, 2])) / 2);
xyz = new Vector3 (x, y, z);
if (matrix[2, 1] - matrix[1, 2] < 0) X = -X;
if (matrix[0, 2] - matrix[2, 0] < 0) Y = -Y;
if (matrix[1, 0] - matrix[0, 1] < 0) Z = -Z;
}
#endregion
#region Public Members
#region Properties
/// <summary>
/// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance.
/// </summary>
[Obsolete("Use Xyz property instead.")]
[CLSCompliant(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[XmlIgnore]
public Vector3 XYZ { get { return Xyz; } set { Xyz = value; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance.
/// </summary>
public Vector3 Xyz { get { return xyz; } set { xyz = value; } }
/// <summary>
/// Gets or sets the X component of this instance.
/// </summary>
[XmlIgnore]
public float X { get { return xyz.X; } set { xyz.X = value; } }
/// <summary>
/// Gets or sets the Y component of this instance.
/// </summary>
[XmlIgnore]
public float Y { get { return xyz.Y; } set { xyz.Y = value; } }
/// <summary>
/// Gets or sets the Z component of this instance.
/// </summary>
[XmlIgnore]
public float Z { get { return xyz.Z; } set { xyz.Z = value; } }
/// <summary>
/// Gets or sets the W component of this instance.
/// </summary>
public float W { get { return w; } set { w = value; } }
#endregion
#region Instance
#region ToAxisAngle
/// <summary>
/// Convert the current quaternion to axis angle representation
/// </summary>
/// <param name="axis">The resultant axis</param>
/// <param name="angle">The resultant angle</param>
public void ToAxisAngle(out Vector3 axis, out float angle)
{
Vector4 result = ToAxisAngle();
axis = result.Xyz;
angle = result.W;
}
/// <summary>
/// Convert this instance to an axis-angle representation.
/// </summary>
/// <returns>A Vector4 that is the axis-angle representation of this quaternion.</returns>
public Vector4 ToAxisAngle()
{
Quaternion q = this;
if (q.W > 1.0f)
q.Normalize();
Vector4 result = new Vector4();
result.W = 2.0f * (float)System.Math.Acos(q.W); // angle
float den = (float)System.Math.Sqrt(1.0 - q.W * q.W);
if (den > 0.0001f)
{
result.Xyz = q.Xyz / den;
}
else
{
// This occurs when the angle is zero.
// Not a problem: just set an arbitrary normalized axis.
result.Xyz = Vector3.UnitX;
}
return result;
}
#endregion
#region public float Length
/// <summary>
/// Gets the length (magnitude) of the quaternion.
/// </summary>
/// <seealso cref="LengthSquared"/>
public float Length
{
get
{
return (float)System.Math.Sqrt(W * W + Xyz.LengthSquared);
}
}
#endregion
#region public float LengthSquared
/// <summary>
/// Gets the square of the quaternion length (magnitude).
/// </summary>
public float LengthSquared
{
get
{
return W * W + Xyz.LengthSquared;
}
}
#endregion
#region public void Normalize()
/// <summary>
/// Scales the Quaternion to unit length.
/// </summary>
public void Normalize()
{
float scale = 1.0f / this.Length;
Xyz *= scale;
W *= scale;
}
#endregion
#region EulerAngles
public Vector3 ToEulerAngles()
{
// Derivation from http://www.geometrictools.com/Documentation/EulerAngles.pdf
// Order of rotations: Z first, then X, then Y
float check = 2.0f*(-Y*Z + W*X);
const float radToDeg = 180f/(float) Math.PI;
if (check < -0.995f)
{
return new Vector3(-90f, 0f, -(float)Math.Atan2(2.0f * (X * Z - W * Y), 1.0f - 2.0f * (Y * Y + Z * Z)) * radToDeg);
}
else if (check > 0.995f)
{
return new Vector3(90f, 0f, (float)Math.Atan2(2.0f * (X * Z - W * Y), 1.0f - 2.0f * (Y * Y + Z * Z)) * radToDeg);
}
else
{
return new Vector3(
(float)Math.Asin(check) * radToDeg,
(float)Math.Atan2(2.0f * (X * Z - W * Y), 1.0f - 2.0f * (X * X + Y * Y)) * radToDeg,
(float)Math.Atan2(2.0f * (X * Y - W * Z), 1.0f - 2.0f * (X * X + Z * Z)) * radToDeg);
}
}
public float YawAngle => ToEulerAngles().Y;
public float PitchAngle => ToEulerAngles().X;
public float RollAngle => ToEulerAngles().Z;
#endregion
#region public void Conjugate()
/// <summary>
/// Convert this quaternion to its conjugate
/// </summary>
public void Conjugate()
{
Xyz = -Xyz;
}
#endregion
#endregion
#region Static
#region Fields
/// <summary>
/// Defines the identity quaternion.
/// </summary>
public static Quaternion Identity = new Quaternion(0, 0, 0, 1);
#endregion
#region Add
/// <summary>
/// Add two quaternions
/// </summary>
/// <param name="left">The first operand</param>
/// <param name="right">The second operand</param>
/// <returns>The result of the addition</returns>
public static Quaternion Add(Quaternion left, Quaternion right)
{
return new Quaternion(
left.Xyz + right.Xyz,
left.W + right.W);
}
/// <summary>
/// Add two quaternions
/// </summary>
/// <param name="left">The first operand</param>
/// <param name="right">The second operand</param>
/// <param name="result">The result of the addition</param>
public static void Add(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
left.Xyz + right.Xyz,
left.W + right.W);
}
#endregion
#region Sub
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The left instance.</param>
/// <param name="right">The right instance.</param>
/// <returns>The result of the operation.</returns>
public static Quaternion Sub(Quaternion left, Quaternion right)
{
return new Quaternion(
left.Xyz - right.Xyz,
left.W - right.W);
}
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The left instance.</param>
/// <param name="right">The right instance.</param>
/// <param name="result">The result of the operation.</param>
public static void Sub(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
left.Xyz - right.Xyz,
left.W - right.W);
}
#endregion
#region Mult
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
[Obsolete("Use Multiply instead.")]
public static Quaternion Mult(Quaternion left, Quaternion right)
{
return new Quaternion(
right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz),
left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz));
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <param name="result">A new instance containing the result of the calculation.</param>
[Obsolete("Use Multiply instead.")]
public static void Mult(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz),
left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz));
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion Multiply(Quaternion left, Quaternion right)
{
Quaternion result;
Multiply(ref left, ref right, out result);
return result;
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <param name="result">A new instance containing the result of the calculation.</param>
public static void Multiply(ref Quaternion left, ref Quaternion right, out Quaternion result)
{
result = new Quaternion(
right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz),
left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz));
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <param name="result">A new instance containing the result of the calculation.</param>
public static void Multiply(ref Quaternion quaternion, float scale, out Quaternion result)
{
result = new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale);
}
[Obsolete ("Use the overload without the ref float scale")]
public static void Multiply(ref Quaternion quaternion, ref float scale, out Quaternion result)
{
result = new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale);
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion Multiply(Quaternion quaternion, float scale)
{
return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale);
}
#endregion
#region Conjugate
/// <summary>
/// Get the conjugate of the given quaternion
/// </summary>
/// <param name="q">The quaternion</param>
/// <returns>The conjugate of the given quaternion</returns>
public static Quaternion Conjugate(Quaternion q)
{
return new Quaternion(-q.Xyz, q.W);
}
/// <summary>
/// Get the conjugate of the given quaternion
/// </summary>
/// <param name="q">The quaternion</param>
/// <param name="result">The conjugate of the given quaternion</param>
public static void Conjugate(ref Quaternion q, out Quaternion result)
{
result = new Quaternion(-q.Xyz, q.W);
}
#endregion
#region Invert
/// <summary>
/// Get the inverse of the given quaternion
/// </summary>
/// <param name="q">The quaternion to invert</param>
/// <returns>The inverse of the given quaternion</returns>
public static Quaternion Invert(Quaternion q)
{
Quaternion result;
Invert(ref q, out result);
return result;
}
/// <summary>
/// Get the inverse of the given quaternion
/// </summary>
/// <param name="q">The quaternion to invert</param>
/// <param name="result">The inverse of the given quaternion</param>
public static void Invert(ref Quaternion q, out Quaternion result)
{
float lengthSq = q.LengthSquared;
if (lengthSq != 0.0)
{
float i = 1.0f / lengthSq;
result = new Quaternion(q.Xyz * -i, q.W * i);
}
else
{
result = q;
}
}
#endregion
#region Normalize
/// <summary>
/// Scale the given quaternion to unit length
/// </summary>
/// <param name="q">The quaternion to normalize</param>
/// <returns>The normalized quaternion</returns>
public static Quaternion Normalize(Quaternion q)
{
Quaternion result;
Normalize(ref q, out result);
return result;
}
/// <summary>
/// Scale the given quaternion to unit length
/// </summary>
/// <param name="q">The quaternion to normalize</param>
/// <param name="result">The normalized quaternion</param>
public static void Normalize(ref Quaternion q, out Quaternion result)
{
float scale = 1.0f / q.Length;
result = new Quaternion(q.Xyz * scale, q.W * scale);
}
#endregion
#region FromAxisAngle
/// <summary>
/// Build a quaternion from the given axis and angle
/// </summary>
/// <param name="axis">The axis to rotate about</param>
/// <param name="angle">The rotation angle in degrees</param>
/// <returns></returns>
public static Quaternion FromAxisAngle(Vector3 axis, float angle)
{
axis.Normalize();
angle *= (float)Math.PI /360f;
var sinAngle = (float)Math.Sin(angle);
var cosAngle = (float)Math.Cos(angle);
return new Quaternion(axis.X * sinAngle, axis.Y * sinAngle, axis.Z * sinAngle, cosAngle);
}
#endregion
#region FromRotationTo
public static Quaternion FromRotationTo(Vector3 start, Vector3 end)
{
Quaternion result = new Quaternion();
start.Normalize();
end.Normalize();
const float epsilon = 0.000001f;
float d = Vector3.Dot(start, end);
if (d > -1.0f + epsilon)
{
Vector3 c = Vector3.Cross(start, end);
float s = (float)Math.Sqrt((1.0f + d) * 2.0f);
float invS = 1.0f / s;
result.X = c.X * invS;
result.Y = c.Y * invS;
result.Z = c.Z * invS;
result.W = 0.5f * s;
}
else
{
Vector3 axis = Vector3.Cross(Vector3.UnitX, start);
if (axis.Length < epsilon)
axis = Vector3.Cross(Vector3.UnitY, start);
return FromAxisAngle(axis, 180.0f);
}
return result;
}
#endregion
#region Slerp
/// <summary>
/// Do Spherical linear interpolation between two quaternions
/// </summary>
/// <param name="q1">The first quaternion</param>
/// <param name="q2">The second quaternion</param>
/// <param name="blend">The blend factor</param>
/// <returns>A smooth blend between the given quaternions</returns>
public static Quaternion Slerp(Quaternion q1, Quaternion q2, float blend)
{
// if either input is zero, return the other.
if (q1.LengthSquared == 0.0f)
{
if (q2.LengthSquared == 0.0f)
{
return Identity;
}
return q2;
}
else if (q2.LengthSquared == 0.0f)
{
return q1;
}
float cosHalfAngle = q1.W * q2.W + Vector3.Dot(q1.Xyz, q2.Xyz);
if (cosHalfAngle >= 1.0f || cosHalfAngle <= -1.0f)
{
// angle = 0.0f, so just return one input.
return q1;
}
else if (cosHalfAngle < 0.0f)
{
q2.Xyz = -q2.Xyz;
q2.W = -q2.W;
cosHalfAngle = -cosHalfAngle;
}
float blendA;
float blendB;
if (cosHalfAngle < 0.99f)
{
// do proper slerp for big angles
float halfAngle = (float)System.Math.Acos(cosHalfAngle);
float sinHalfAngle = (float)System.Math.Sin(halfAngle);
float oneOverSinHalfAngle = 1.0f / sinHalfAngle;
blendA = (float)System.Math.Sin(halfAngle * (1.0f - blend)) * oneOverSinHalfAngle;
blendB = (float)System.Math.Sin(halfAngle * blend) * oneOverSinHalfAngle;
}
else
{
// do lerp if angle is really small.
blendA = 1.0f - blend;
blendB = blend;
}
Quaternion result = new Quaternion(blendA * q1.Xyz + blendB * q2.Xyz, blendA * q1.W + blendB * q2.W);
if (result.LengthSquared > 0.0f)
return Normalize(result);
else
return Identity;
}
#endregion
#endregion
#region Operators
/// <summary>
/// Adds two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Quaternion operator +(Quaternion left, Quaternion right)
{
left.Xyz += right.Xyz;
left.W += right.W;
return left;
}
/// <summary>
/// Subtracts two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Quaternion operator -(Quaternion left, Quaternion right)
{
left.Xyz -= right.Xyz;
left.W -= right.W;
return left;
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>The result of the calculation.</returns>
public static Quaternion operator *(Quaternion left, Quaternion right)
{
Multiply(ref left, ref right, out left);
return left;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion operator *(Quaternion quaternion, float scale)
{
Multiply(ref quaternion, scale, out quaternion);
return quaternion;
}
/// <summary>
/// Multiplies an instance by a scalar.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="scale">The scalar.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Quaternion operator *(float scale, Quaternion quaternion)
{
return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale);
}
/// <summary>
/// Multiplies an instance by a vector3.
/// </summary>
/// <param name="quaternion">The instance.</param>
/// <param name="vector">The vector.</param>
/// <returns>A new instance containing the result of the calculation.</returns>
public static Vector3 operator *(Quaternion quaternion, Vector3 vector)
{
var qVec = new Vector3(quaternion.X, quaternion.Y, quaternion.Z);
var cross1 = Vector3.Cross(qVec, vector);
var cross2 = Vector3.Cross(qVec, cross1);
return vector + 2.0f * (cross1 * quaternion.W + cross2);
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Quaternion left, Quaternion right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equal right; false otherwise.</returns>
public static bool operator !=(Quaternion left, Quaternion right)
{
return !left.Equals(right);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Quaternion.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("V: {0}, W: {1}", Xyz, W);
}
#endregion
#region public override bool Equals (object o)
/// <summary>
/// Compares this object instance to another object for equality.
/// </summary>
/// <param name="other">The other object to be used in the comparison.</param>
/// <returns>True if both objects are Quaternions of equal value. Otherwise it returns false.</returns>
public override bool Equals(object other)
{
if (other is Quaternion == false) return false;
return this == (Quaternion)other;
}
#endregion
#region public override int GetHashCode ()
/// <summary>
/// Provides the hash code for this object.
/// </summary>
/// <returns>A hash code formed from the bitwise XOR of this objects members.</returns>
public override int GetHashCode()
{
return Xyz.GetHashCode() ^ W.GetHashCode();
}
#endregion
#endregion
#endregion
#region IEquatable<Quaternion> Members
/// <summary>
/// Compares this Quaternion instance to another Quaternion for equality.
/// </summary>
/// <param name="other">The other Quaternion to be used in the comparison.</param>
/// <returns>True if both instances are equal; false otherwise.</returns>
public bool Equals(Quaternion other)
{
return Xyz == other.Xyz && W == other.W;
}
#endregion
}
}
| |
using System;
using System.Net.Mail;
namespace S22.Imap {
/// <summary>
/// Allows applications to communicate with a mail server by using the
/// Internet Message Access Protocol (IMAP).
/// </summary>
public interface IImapClient : IDisposable {
/// <summary>
/// The default mailbox to operate on, when no specific mailbox name was indicated
/// to methods operating on mailboxes. This property is initially set to "INBOX".
/// </summary>
/// <exception cref="ArgumentNullException">The value specified for a set operation is
/// null.</exception>
/// <exception cref="ArgumentException">The value specified for a set operation is equal
/// to String.Empty ("").</exception>
/// <remarks>This property is initialized to "INBOX"</remarks>
string DefaultMailbox { get; set; }
/// <summary>
/// Indicates whether the client is authenticated with the server
/// </summary>
bool Authed { get; }
/// <summary>
/// This event is raised when a new mail message is received by the server.
/// </summary>
/// <remarks>To probe a server for IMAP IDLE support, the <see cref="Supports"/>
/// method can be used, specifying "IDLE" for the capability parameter.
///
/// Notice that the event handler will be executed on a threadpool thread.
/// </remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="NewMessage"]/*'/>
event EventHandler<IdleMessageEventArgs> NewMessage;
/// <summary>
/// This event is raised when a message is deleted on the server.
/// </summary>
/// <remarks>To probe a server for IMAP IDLE support, the <see cref="Supports"/>
/// method can be used, specifying "IDLE" for the capability parameter.
///
/// Notice that the event handler will be executed on a threadpool thread.
/// </remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="MessageDeleted"]/*'/>
event EventHandler<IdleMessageEventArgs> MessageDeleted;
/// <summary>
/// Attempts to establish an authenticated session with the server using the specified
/// credentials.
/// </summary>
/// <param name="username">The username with which to login in to the IMAP server.</param>
/// <param name="password">The password with which to log in to the IMAP server.</param>
/// <param name="method">The requested method of authentication. Can be one of the values
/// of the AuthMethod enumeration.</param>
/// <exception cref="InvalidCredentialsException">Thrown if authentication using the
/// supplied credentials failed.</exception>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="Login"]/*'/>
void Login(string username, string password, AuthMethod method);
/// <summary>
/// Logs an authenticated client out of the server. After the logout sequence has
/// been completed, the server closes the connection with the client.
/// </summary>
/// <exception cref="BadServerResponseException">Thrown if an unexpected response is
/// received from the server during the logout sequence</exception>
/// <remarks>Calling Logout in a non-authenticated state has no effect</remarks>
void Logout();
/// <summary>
/// Returns a listing of capabilities that the IMAP server supports. All strings
/// in the returned array are guaranteed to be upper-case.
/// </summary>
/// <exception cref="BadServerResponseException">Thrown if an unexpected response is received
/// from the server during the request. The message property of the exception contains the
/// error message returned by the server.</exception>
/// <returns>A listing of supported capabilities as an array of strings</returns>
/// <remarks>This is one of the few methods which can be called in a non-authenticated
/// state.</remarks>
string[] Capabilities();
/// <summary>
/// Returns whether the specified capability is supported by the server.
/// </summary>
/// <param name="capability">The capability to probe for (for example "IDLE")</param>
/// <exception cref="BadServerResponseException">Thrown if an unexpected response is received
/// from the server during the request. The message property of the exception contains
/// the error message returned by the server.</exception>
/// <returns>Returns true if the specified capability is supported by the server,
/// otherwise false is returned.</returns>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="ctor-2"]/*'/>
bool Supports(string capability);
/// <summary>
/// Changes the name of a mailbox.
/// </summary>
/// <param name="mailbox">The mailbox to rename.</param>
/// <param name="newName">The new name the mailbox will be renamed to.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mailbox could
/// not be renamed. The message property of the exception contains the error message
/// returned by the server.</exception>
void RenameMailbox(string mailbox, string newName);
/// <summary>
/// Permanently removes a mailbox.
/// </summary>
/// <param name="mailbox">Name of the mailbox to remove.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mailbox could
/// not be removed. The message property of the exception contains the error message
/// returned by the server.</exception>
void DeleteMailbox(string mailbox);
/// <summary>
/// Creates a new mailbox with the given name.
/// </summary>
/// <param name="mailbox">Name of the mailbox to create.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mailbox could
/// not be created. The message property of the exception contains the error message
/// returned by the server.</exception>
void CreateMailbox(string mailbox);
/// <summary>
/// Retrieves a list of all available and selectable mailboxes on the server.
/// </summary>
/// <returns>A list of all available and selectable mailboxes</returns>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if a list of mailboxes
/// could not be retrieved. The message property of the exception contains the
/// error message returned by the server.</exception>
/// <remarks>The mailbox INBOX is a special name reserved to mean "the
/// primary mailbox for this user on this server"</remarks>
string[] ListMailboxes();
/// <summary>
/// Permanently removes all messages that have the \Deleted flag set from the
/// specified mailbox.
/// </summary>
/// <param name="mailbox">The mailbox to remove all messages from that have the
/// \Deleted flag set. If this parameter is omitted, the value of the DefaultMailbox
/// property is used to determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the expunge operation could
/// not be completed. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <seealso cref="DeleteMessage"/>
void Expunge(string mailbox = null);
/// <summary>
/// Retrieves status information (total number of messages, various attributes
/// as well as quota information) for the specified mailbox.</summary>
/// <param name="mailbox">The mailbox to retrieve status information for. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <returns>A MailboxInfo object containing status information for the
/// mailbox.</returns>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the operation could
/// not be completed. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <remarks>Not all IMAP servers support the retrieval of quota information. If
/// it is not possible to retrieve this information, the UsedStorage and FreeStorage
/// properties of the returned MailboxStatus instance are set to 0.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMailboxInfo"]/*'/>
MailboxInfo GetMailboxInfo(string mailbox = null);
/// <summary>
/// Searches the specified mailbox for messages that match the given
/// searching criteria.
/// </summary>
/// <param name="criteria">A search criteria expression. Only messages
/// that match this expression will be included in the result set returned
/// by this method.</param>
/// <param name="mailbox">The mailbox that will be searched. If this parameter is
/// omitted, the value of the DefaultMailbox property is used to determine the mailbox
/// to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the search could
/// not be completed. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <exception cref="NotSupportedException">Thrown if the search values
/// contain characters beyond the ASCII range and the server does not support
/// handling such strings.</exception>
/// <returns>An array of unique identifier (UID) message attributes which
/// can be used with the GetMessage family of methods to download mail
/// messages.</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="Search"]/*'/>
uint[] Search(SearchCondition criteria, string mailbox = null);
/// <summary>
/// Retrieves a mail message by its unique identifier message attribute.
/// </summary>
/// <param name="uid">The unique identifier of the mail message to retrieve</param>
/// <param name="seen">Set this to true to set the \Seen flag for this message
/// on the server.</param>
/// <param name="mailbox">The mailbox the message will be retrieved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message could
/// not be fetched. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>An initialized instance of the MailMessage class representing the
/// fetched mail message</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessage-1"]/*'/>
MailMessage GetMessage(uint uid, bool seen = true, string mailbox = null);
/// <summary>
/// Retrieves a mail message by its unique identifier message attribute with the
/// specified fetch option.
/// </summary>
/// <param name="uid">The unique identifier of the mail message to retrieve</param>
/// <param name="options">A value from the FetchOptions enumeration which allows
/// for fetching selective parts of a mail message.</param>
/// <param name="seen">Set this to true to set the \Seen flag for this message
/// on the server.</param>
/// <param name="mailbox">The mailbox the message will be retrieved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message could
/// not be fetched. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>An initialized instance of the MailMessage class representing the
/// fetched mail message</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.
/// <para>If you need more fine-grained control over which parts of a mail
/// message to fetch, consider using one of the overloaded GetMessage methods.
/// </para>
/// </remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessage-2"]/*'/>
MailMessage GetMessage(uint uid, FetchOptions options,
bool seen = true, string mailbox = null);
/// <summary>
/// Retrieves a mail message by its unique identifier message attribute providing
/// fine-grained control over which message parts to retrieve.
/// </summary>
/// <param name="uid">The unique identifier of the mail message to retrieve</param>
/// <param name="callback">A delegate which will be invoked for every MIME body
/// part of the mail message to determine whether it should be fetched from the
/// server or skipped.</param>
/// <param name="seen">Set this to true to set the \Seen flag for this message
/// on the server.</param>
/// <param name="mailbox">The mailbox the message will be retrieved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message could
/// not be fetched. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>An initialized instance of the MailMessage class representing the
/// fetched mail message</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessage-3"]/*'/>
MailMessage GetMessage(uint uid, ExaminePartDelegate callback,
bool seen = true, string mailbox = null);
/// <summary>
/// Retrieves a set of mail messages by their unique identifier message attributes.
/// </summary>
/// <param name="uids">An array of unique identifiers of the mail messages to
/// retrieve</param>
/// <param name="seen">Set this to true to set the \Seen flag for the fetched
/// messages on the server.</param>
/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail messages could
/// not be fetched. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>An array of initialized instances of the MailMessage class representing
/// the fetched mail messages</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-1"]/*'/>
MailMessage[] GetMessages(uint[] uids, bool seen = true, string mailbox = null);
/// <summary>
/// Retrieves a set of mail messages by their unique identifier message attributes
/// providing fine-grained control over which message parts to retrieve of each
/// respective message.
/// </summary>
/// <param name="uids">An array of unique identifiers of the mail messages to
/// retrieve</param>
/// <param name="callback">A delegate which will be invoked for every MIME body
/// part of a mail message to determine whether it should be fetched from the
/// server or skipped.</param>
/// <param name="seen">Set this to true to set the \Seen flag for the fetched
/// messages on the server.</param>
/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail messages could
/// not be fetched. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>An array of initialized instances of the MailMessage class representing
/// the fetched mail messages</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-3"]/*'/>
MailMessage[] GetMessages(uint[] uids, ExaminePartDelegate callback,
bool seen = true, string mailbox = null);
/// <summary>
/// Retrieves a set of mail messages by their unique identifier message attributes
/// with the specified fetch option.
/// </summary>
/// <param name="uids">An array of unique identifiers of the mail messages to
/// retrieve</param>
/// <param name="options">A value from the FetchOptions enumeration which allows
/// for fetching selective parts of a mail message.</param>
/// <param name="seen">Set this to true to set the \Seen flag for the fetched
/// messages on the server.</param>
/// <param name="mailbox">The mailbox the messages will be retrieved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail messages could
/// not be fetched. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>An array of initialized instances of the MailMessage class representing
/// the fetched mail messages</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="GetMessages-2"]/*'/>
MailMessage[] GetMessages(uint[] uids, FetchOptions options,
bool seen = true, string mailbox = null);
/// <summary>
/// Stores the specified mail message on the IMAP server.
/// </summary>
/// <param name="message">The mail message to store on the server.</param>
/// <param name="seen">Set this to true to set the \Seen flag for the message
/// on the server.</param>
/// <param name="mailbox">The mailbox the message will be stored in. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to store the message in.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message could
/// not be stored. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>The unique identifier (UID) of the stored message.</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <seealso cref="StoreMessages"/>
/// <include file='Examples.xml' path='S22/Imap/ImapClient[@name="StoreMessage"]/*'/>
uint StoreMessage(MailMessage message, bool seen = false, string mailbox = null);
/// <summary>
/// Stores the specified mail messages on the IMAP server.
/// </summary>
/// <param name="messages">An array of mail messages to store on the server.</param>
/// <param name="seen">Set this to true to set the \Seen flag for each message
/// on the server.</param>
/// <param name="mailbox">The mailbox the messages will be stored in. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to store the messages in.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail messages could
/// not be stored. The message property of the exception contains the error message
/// returned by the server.</exception>
/// <returns>An array containing the unique identifiers (UID) of the stored
/// messages.</returns>
/// <remarks>A unique identifier (UID) is a 32-bit value assigned to each
/// message which uniquely identifies the message within a mailbox. No two
/// messages in a mailbox share the the same UID.</remarks>
/// <seealso cref="StoreMessage"/>
uint[] StoreMessages(MailMessage[] messages, bool seen = false,
string mailbox = null);
/// <summary>
/// Copies a mail message with the specified UID to the specified destination
/// mailbox.
/// </summary>
/// <param name="uid">The UID of the mail message that is to be copied.</param>
/// <param name="destination">The name of the mailbox to copy the message
/// into.</param>
/// <param name="mailbox">The mailbox the message will be copied from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message could
/// not be copied to the specified destination. The message property of the
/// exception contains the error message returned by the server.</exception>
/// <seealso cref="MoveMessage"/>
void CopyMessage(uint uid, string destination, string mailbox = null);
/// <summary>
/// Moves a mail message with the specified UID to the specified destination
/// mailbox.
/// </summary>
/// <param name="uid">The UID of the mail message that is to be moved.</param>
/// <param name="destination">The name of the mailbox to move the message
/// into.</param>
/// <param name="mailbox">The mailbox the message will be moved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message could
/// not be moved into the specified destination. The message property of the
/// exception contains the error message returned by the server.</exception>
/// <seealso cref="CopyMessage"/>
/// <seealso cref="DeleteMessage"/>
void MoveMessage(uint uid, string destination, string mailbox = null);
/// <summary>
/// Deletes the mail message with the specified UID.
/// </summary>
/// <param name="uid">The UID of the mail message that is to be deleted.</param>
/// <param name="mailbox">The mailbox the message will be deleted from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message could
/// not be deleted. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <seealso cref="MoveMessage"/>
void DeleteMessage(uint uid, string mailbox = null);
/// <summary>
/// Retrieves the IMAP message flag attributes for a mail message.
/// </summary>
/// <param name="uid">The UID of the mail message to retrieve the flag
/// attributes for.</param>
/// <param name="mailbox">The mailbox the message will be retrieved from. If this
/// parameter is omitted, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message flags
/// could not be retrieved. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <returns>A list of IMAP flags set for the message with the matching UID.</returns>
/// <seealso cref="SetMessageFlags"/>
/// <seealso cref="AddMessageFlags"/>
/// <seealso cref="RemoveMessageFlags"/>
MessageFlag[] GetMessageFlags(uint uid, string mailbox = null);
/// <summary>
/// Sets the IMAP message flag attributes for a mail message.
/// </summary>
/// <param name="uid">The UID of the mail message to set the flag
/// attributes for.</param>
/// <param name="mailbox">The mailbox that contains the mail message. If this
/// parameter is null, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <param name="flags">One or multiple message flags from the MessageFlag
/// enumeration.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message flags
/// could not be set. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <remarks>This method replaces the current flag attributes of the message
/// with the specified new flags. If you wish to retain the old attributes, use
/// the <see cref="AddMessageFlags"/> method instead.</remarks>
/// <seealso cref="GetMessageFlags"/>
/// <seealso cref="AddMessageFlags"/>
/// <seealso cref="RemoveMessageFlags"/>
void SetMessageFlags(uint uid, string mailbox, params MessageFlag[] flags);
/// <summary>
/// Adds the specified set of IMAP message flags to the existing flag attributes
/// of a mail message.
/// </summary>
/// <param name="uid">The UID of the mail message to add the flag
/// attributes to.</param>
/// <param name="mailbox">The mailbox that contains the mail message. If this
/// parameter is null, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <param name="flags">One or multiple message flags from the MessageFlag
/// enumeration.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message flags
/// could not be added. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <remarks>This method adds the specified set of flags to the existing set of
/// flag attributes of the message. If you wish to replace the old attributes, use
/// the <see cref="SetMessageFlags"/> method instead.</remarks>
/// <seealso cref="GetMessageFlags"/>
/// <seealso cref="SetMessageFlags"/>
/// <seealso cref="RemoveMessageFlags"/>
void AddMessageFlags(uint uid, string mailbox, params MessageFlag[] flags);
/// <summary>
/// Removes the specified set of IMAP message flags from the existing flag
/// attributes of a mail message.
/// </summary>
/// <param name="uid">The UID of the mail message to remove the flag
/// attributes to.</param>
/// <param name="mailbox">The mailbox that contains the mail message. If this
/// parameter is null, the value of the DefaultMailbox property is used to
/// determine the mailbox to operate on.</param>
/// <param name="flags">One or multiple message flags from the MessageFlag
/// enumeration.</param>
/// <exception cref="NotAuthenticatedException">Thrown if the method was called
/// in a non-authenticated state, i.e. before logging into the server with
/// valid credentials.</exception>
/// <exception cref="BadServerResponseException">Thrown if the mail message flags
/// could not be removed. The message property of the exception contains the error
/// message returned by the server.</exception>
/// <remarks>This method removes the specified set of flags from the existing set of
/// flag attributes of the message. If you wish to replace the old attributes, use
/// the <see cref="SetMessageFlags"/> method instead.</remarks>
/// <seealso cref="GetMessageFlags"/>
/// <seealso cref="SetMessageFlags"/>
/// <seealso cref="AddMessageFlags"/>
void RemoveMessageFlags(uint uid, string mailbox, params MessageFlag[] flags);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace WinDHCP.Library
{
internal class DhcpData
{
private IPEndPoint m_Source;
private Byte[] m_MessageBuffer;
private Int32 m_BufferSize;
private IAsyncResult m_Result;
public IPEndPoint Source
{
get { return this.m_Source; }
set { this.m_Source = value; }
}
public Byte[] MessageBuffer
{
get { return this.m_MessageBuffer; }
// set { this.m_MessageBuffer = value; }
}
public Int32 BufferSize
{
get
{
return this.m_BufferSize;
}
set
{
this.m_BufferSize = value;
Byte[] oldBuffer = this.m_MessageBuffer;
this.m_MessageBuffer = new Byte[this.m_BufferSize];
Int32 copyLen = Math.Min(oldBuffer.Length, this.m_BufferSize);
Array.Copy(oldBuffer, this.m_MessageBuffer, copyLen);
}
}
public IAsyncResult Result
{
get { return this.m_Result; }
set { this.m_Result = value; }
}
public DhcpData(Byte[] messageBuffer)
{
this.m_MessageBuffer = messageBuffer;
this.m_BufferSize = messageBuffer.Length;
}
public DhcpData(IPEndPoint source, Byte[] messageBuffer)
{
this.m_Source = source;
this.m_MessageBuffer = messageBuffer;
this.m_BufferSize = messageBuffer.Length;
}
}
public enum DhcpOperation : byte
{
BootRequest = 0x01,
BootReply
}
public enum HardwareType : byte
{
Ethernet = 0x01,
ExperimentalEthernet,
AmateurRadio,
ProteonTokenRing,
Chaos,
IEEE802Networks,
ArcNet,
Hyperchnnel,
Lanstar
}
public enum DhcpMessageType
{
Discover = 0x01,
Offer,
Request,
Decline,
Ack,
Nak,
Release,
Inform,
ForceRenew,
LeaseQuery,
LeaseUnassigned,
LeaseUnknown,
LeaseActive
}
public enum DhcpOption : byte
{
Pad = 0x00,
SubnetMask = 0x01,
TimeOffset = 0x02,
Router = 0x03,
TimeServer = 0x04,
NameServer = 0x05,
DomainNameServer = 0x06,
Hostname = 0x0C,
DomainNameSuffix = 0x0F,
AddressRequest = 0x32,
AddressTime = 0x33,
DhcpMessageType = 0x35,
DhcpAddress = 0x36,
ParameterList = 0x37,
DhcpMessage = 0x38,
DhcpMaxMessageSize = 0x39,
ClassId = 0x3C,
ClientId = 0x3D,
AutoConfig = 0x74,
End = 0xFF
}
public class DhcpMessage
{
private const UInt32 DhcpOptionsMagicNumber = 1669485411;
private const UInt32 WinDhcpOptionsMagicNumber = 1666417251;
private const Int32 DhcpMinimumMessageSize = 236;
private DhcpOperation m_Operation = DhcpOperation.BootRequest;
private HardwareType m_Hardware = HardwareType.Ethernet;
private Byte m_HardwareAddressLength;
private Byte m_Hops;
private Int32 m_SessionId;
private UInt16 m_SecondsElapsed;
private UInt16 m_Flags;
private Byte[] m_ClientAddress = new Byte[4];
private Byte[] m_AssignedAddress = new Byte[4];
private Byte[] m_NextServerAddress = new Byte[4];
private Byte[] m_RelayAgentAddress = new Byte[4];
private Byte[] m_ClientHardwareAddress = new Byte[16];
private Byte[] m_OptionOrdering = new Byte[] {};
private Int32 m_OptionDataSize = 0;
private Dictionary<DhcpOption, Byte[]> m_Options = new Dictionary<DhcpOption, Byte[]>();
public DhcpMessage()
{
}
internal DhcpMessage(DhcpData data)
: this(data.MessageBuffer)
{
}
public DhcpMessage(Byte[] data)
{
Int32 offset = 0;
this.m_Operation = (DhcpOperation)data[offset++];
this.m_Hardware = (HardwareType)data[offset++];
this.m_HardwareAddressLength = data[offset++];
this.m_Hops = data[offset++];
this.m_SessionId = BitConverter.ToInt32(data, offset);
offset += 4;
Byte[] secondsElapsed = new Byte[2];
Array.Copy(data, offset, secondsElapsed, 0, 2);
this.m_SecondsElapsed = BitConverter.ToUInt16(ReverseByteOrder(secondsElapsed), 0);
offset += 2;
this.m_Flags = BitConverter.ToUInt16(data, offset);
offset += 2;
Array.Copy(data, offset, this.m_ClientAddress, 0, 4);
offset += 4;
Array.Copy(data, offset, this.m_AssignedAddress, 0, 4);
offset += 4;
Array.Copy(data, offset, this.m_NextServerAddress, 0, 4);
offset += 4;
Array.Copy(data, offset, this.m_RelayAgentAddress, 0, 4);
offset += 4;
Array.Copy(data, offset, this.m_ClientHardwareAddress, 0, 16);
offset += 16;
offset += 192; // Skip server host name and boot file
if (offset + 4 < data.Length &&
(BitConverter.ToUInt32(data, offset) == DhcpOptionsMagicNumber || BitConverter.ToUInt32(data, offset) == WinDhcpOptionsMagicNumber))
{
offset += 4;
Boolean end = false;
while (!end && offset < data.Length)
{
DhcpOption option = (DhcpOption)data[offset];
offset++;
Int32 optionLen;
switch (option)
{
case DhcpOption.Pad:
continue;
case DhcpOption.End:
end = true;
continue;
default:
optionLen = (Int32)data[offset];
offset++;
break;
}
Byte[] optionData = new Byte[optionLen];
Array.Copy(data, offset, optionData, 0, optionLen);
offset += optionLen;
this.m_Options.Add(option, optionData);
this.m_OptionDataSize += optionLen;
}
}
}
public DhcpOperation Operation
{
get { return this.m_Operation; }
set { this.m_Operation = value; }
}
public HardwareType Hardware
{
get { return this.m_Hardware; }
set { this.m_Hardware = value; }
}
public Byte HardwareAddressLength
{
get { return this.m_HardwareAddressLength; }
set { this.m_HardwareAddressLength = value; }
}
public Byte Hops
{
get { return this.m_Hops; }
set { this.m_Hops = value; }
}
public Int32 SessionId
{
get { return this.m_SessionId; }
set { this.m_SessionId = value; }
}
public UInt16 SecondsElapsed
{
get { return this.m_SecondsElapsed; }
set { this.m_SecondsElapsed = value; }
}
public UInt16 Flags
{
get { return this.m_Flags; }
set { this.m_Flags = value; }
}
public Byte[] ClientAddress
{
get { return this.m_ClientAddress; }
set { CopyData(value, this.m_ClientAddress); }
}
public Byte[] AssignedAddress
{
get { return this.m_AssignedAddress; }
set { CopyData(value, this.m_AssignedAddress); }
}
public Byte[] NextServerAddress
{
get { return this.m_NextServerAddress; }
set { CopyData(value, this.m_NextServerAddress); }
}
public Byte[] RelayAgentAddress
{
get { return this.m_RelayAgentAddress; }
set { CopyData(value, this.m_RelayAgentAddress); }
}
public Byte[] ClientHardwareAddress
{
get
{
Byte[] hardwareAddress = new Byte[this.m_HardwareAddressLength];
Array.Copy(this.m_ClientHardwareAddress, hardwareAddress, this.m_HardwareAddressLength);
return hardwareAddress;
}
set
{
CopyData(value, this.m_ClientHardwareAddress);
this.m_HardwareAddressLength = (Byte)value.Length;
for (Int32 i = value.Length; i < 16; i++)
{
this.m_ClientHardwareAddress[i] = 0;
}
}
}
public Byte[] OptionOrdering
{
get { return this.m_OptionOrdering; }
set { this.m_OptionOrdering = value; }
}
public Byte[] GetOptionData(DhcpOption option)
{
if (this.m_Options.ContainsKey(option))
{
return this.m_Options[option];
}
else
{
return null;
}
}
public void AddOption(DhcpOption option, params Byte[] data)
{
if (option == DhcpOption.Pad || option == DhcpOption.End)
{
throw new ArgumentException("The Pad and End DhcpOptions cannot be added explicitly.", "option");
}
this.m_Options.Add(option, data);
this.m_OptionDataSize += data.Length;
}
public Boolean RemoveOption(DhcpOption option)
{
if (this.m_Options.ContainsKey(option))
{
this.m_OptionDataSize -= this.m_Options[option].Length;
}
return this.m_Options.Remove(option);
}
public void ClearOptions()
{
this.m_OptionDataSize = 0;
this.m_Options.Clear();
}
public Byte[] ToArray()
{
Byte[] data = new Byte[DhcpMinimumMessageSize + (this.m_Options.Count > 0 ? 4 + this.m_Options.Count * 2 + this.m_OptionDataSize + 1 : 0)];
Int32 offset = 0;
data[offset++] = (Byte)this.m_Operation;
data[offset++] = (Byte)this.m_Hardware;
data[offset++] = this.m_HardwareAddressLength;
data[offset++] = this.m_Hops;
BitConverter.GetBytes(this.m_SessionId).CopyTo(data, offset);
offset += 4;
ReverseByteOrder(BitConverter.GetBytes(this.m_SecondsElapsed)).CopyTo(data, offset);
offset += 2;
BitConverter.GetBytes(this.m_Flags).CopyTo(data, offset);
offset += 2;
this.m_ClientAddress.CopyTo(data, offset);
offset += 4;
this.m_AssignedAddress.CopyTo(data, offset);
offset += 4;
this.m_NextServerAddress.CopyTo(data, offset);
offset += 4;
this.m_RelayAgentAddress.CopyTo(data, offset);
offset += 4;
this.m_ClientHardwareAddress.CopyTo(data, offset);
offset += 16;
offset += 192;
if (this.m_Options.Count > 0)
{
BitConverter.GetBytes(WinDhcpOptionsMagicNumber).CopyTo(data, offset);
offset += 4;
foreach (Byte optionId in this.m_OptionOrdering)
{
DhcpOption option = (DhcpOption)optionId;
if (this.m_Options.ContainsKey(option))
{
data[offset++] = optionId;
if (this.m_Options[option] != null && this.m_Options[option].Length > 0)
{
data[offset++] = (Byte)this.m_Options[option].Length;
Array.Copy(this.m_Options[option], 0, data, offset, this.m_Options[option].Length);
offset += this.m_Options[option].Length;
}
}
}
foreach (DhcpOption option in this.m_Options.Keys)
{
if (Array.IndexOf(this.m_OptionOrdering, (Byte)option) == -1)
{
data[offset++] = (Byte)option;
if (this.m_Options[option] != null && this.m_Options[option].Length > 0)
{
data[offset++] = (Byte)this.m_Options[option].Length;
Array.Copy(this.m_Options[option], 0, data, offset, this.m_Options[option].Length);
offset += this.m_Options[option].Length;
}
}
}
data[offset] = (Byte)DhcpOption.End;
}
return data;
}
private void CopyData(Byte[] source, Byte[] dest)
{
if (source.Length > dest.Length)
{
throw new ArgumentException(String.Format("Values must be no more than {0} bytes.", dest.Length), "value");
}
source.CopyTo(dest, 0);
}
public static Byte[] ReverseByteOrder(Byte[] source)
{
Byte[] reverse = new Byte[source.Length];
Int32 j = 0;
for (Int32 i = source.Length - 1; i >= 0; i--)
{
reverse[j++] = source[i];
}
return reverse;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories.Models
{
/// <summary>
/// A data slice run is unit of processing for a data slice.
/// </summary>
public partial class DataSliceRun
{
private IDictionary<string, string> _activityInputProperties;
/// <summary>
/// Optional. Container for all the input properties for the Activity
/// </summary>
public IDictionary<string, string> ActivityInputProperties
{
get { return this._activityInputProperties; }
set { this._activityInputProperties = value; }
}
private string _activityName;
/// <summary>
/// Optional. Run activity name.
/// </summary>
public string ActivityName
{
get { return this._activityName; }
set { this._activityName = value; }
}
private DateTime _batchTime;
/// <summary>
/// Optional. Start time for corresponding data slice.
/// </summary>
public DateTime BatchTime
{
get { return this._batchTime; }
set { this._batchTime = value; }
}
private string _computeClusterName;
/// <summary>
/// Optional. The HDInsight cluster where the run was processed.
/// </summary>
public string ComputeClusterName
{
get { return this._computeClusterName; }
set { this._computeClusterName = value; }
}
private DateTime _dataSliceEnd;
/// <summary>
/// Optional. End time for corresponding data slice.
/// </summary>
public DateTime DataSliceEnd
{
get { return this._dataSliceEnd; }
set { this._dataSliceEnd = value; }
}
private DateTime _dataSliceStart;
/// <summary>
/// Optional. Start time for corresponding data slice.
/// </summary>
public DateTime DataSliceStart
{
get { return this._dataSliceStart; }
set { this._dataSliceStart = value; }
}
private string _errorMessage;
/// <summary>
/// Optional. Error message retuned if failed.
/// </summary>
public string ErrorMessage
{
get { return this._errorMessage; }
set { this._errorMessage = value; }
}
private bool _hasLogs;
/// <summary>
/// Optional. Has compute logs.
/// </summary>
public bool HasLogs
{
get { return this._hasLogs; }
set { this._hasLogs = value; }
}
private string _id;
/// <summary>
/// Optional. Run id.
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
private IList<RunRecordReference> _inputRunRecordReferences;
/// <summary>
/// Optional. The list of data slice runs that were input to this data
/// slice run.
/// </summary>
public IList<RunRecordReference> InputRunRecordReferences
{
get { return this._inputRunRecordReferences; }
set { this._inputRunRecordReferences = value; }
}
private string _logUri;
/// <summary>
/// Optional. Url to the Log files
/// </summary>
public string LogUri
{
get { return this._logUri; }
set { this._logUri = value; }
}
private IList<RunRecordReference> _outputRunRecordReferences;
/// <summary>
/// Optional. The list of data slice runs that used this data slice run
/// as input.
/// </summary>
public IList<RunRecordReference> OutputRunRecordReferences
{
get { return this._outputRunRecordReferences; }
set { this._outputRunRecordReferences = value; }
}
private int _percentComplete;
/// <summary>
/// Optional. Run execution progress as a percentage value.
/// </summary>
public int PercentComplete
{
get { return this._percentComplete; }
set { this._percentComplete = value; }
}
private string _pipelineName;
/// <summary>
/// Optional. Run pipeline name.
/// </summary>
public string PipelineName
{
get { return this._pipelineName; }
set { this._pipelineName = value; }
}
private DateTime _processingEndTime;
/// <summary>
/// Optional. Time when run finished execution.
/// </summary>
public DateTime ProcessingEndTime
{
get { return this._processingEndTime; }
set { this._processingEndTime = value; }
}
private DateTime _processingStartTime;
/// <summary>
/// Optional. Time when run began execution.
/// </summary>
public DateTime ProcessingStartTime
{
get { return this._processingStartTime; }
set { this._processingStartTime = value; }
}
private IDictionary<string, string> _properties;
/// <summary>
/// Optional. Container for all the properties/associated generated by
/// the Activity for a run and can be consumed by the same Activity or
/// others.
/// </summary>
public IDictionary<string, string> Properties
{
get { return this._properties; }
set { this._properties = value; }
}
private int _retryAttempt;
/// <summary>
/// Optional. Retry attempt number for run.
/// </summary>
public int RetryAttempt
{
get { return this._retryAttempt; }
set { this._retryAttempt = value; }
}
private string _status;
/// <summary>
/// Optional. Run status.
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
private string _tableName;
/// <summary>
/// Optional. Run table name.
/// </summary>
public string TableName
{
get { return this._tableName; }
set { this._tableName = value; }
}
private DateTime _timestamp;
/// <summary>
/// Optional. Time when run was created.
/// </summary>
public DateTime Timestamp
{
get { return this._timestamp; }
set { this._timestamp = value; }
}
private string _type;
/// <summary>
/// Optional. Run record type.
/// </summary>
public string Type
{
get { return this._type; }
set { this._type = value; }
}
/// <summary>
/// Initializes a new instance of the DataSliceRun class.
/// </summary>
public DataSliceRun()
{
this.ActivityInputProperties = new LazyDictionary<string, string>();
this.InputRunRecordReferences = new LazyList<RunRecordReference>();
this.OutputRunRecordReferences = new LazyList<RunRecordReference>();
this.Properties = new LazyDictionary<string, string>();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtractInt64129()
{
var test = new ExtractScalarTest__ExtractInt64129();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ExtractScalarTest__ExtractInt64129
{
private struct TestStruct
{
public Vector128<Int64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ExtractScalarTest__ExtractInt64129 testClass)
{
var result = Sse41.X64.Extract(_fld, 129);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable;
static ExtractScalarTest__ExtractInt64129()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
}
public ExtractScalarTest__ExtractInt64129()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.X64.Extract(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.X64.Extract(
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.X64.Extract(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.X64.Extract(
_clsVar,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr);
var result = Sse41.X64.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse41.X64.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr));
var result = Sse41.X64.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractScalarTest__ExtractInt64129();
var result = Sse41.X64.Extract(test._fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.X64.Extract(_fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.X64.Extract(test._fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((result[0] != firstOp[1]))
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41.X64)}.{nameof(Sse41.X64.Extract)}<Int64>(Vector128<Int64><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace Database_1
{
partial class Main
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));
this.status = new System.Windows.Forms.Label();
this.update = new System.Windows.Forms.Button();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.detail = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.date2 = new System.Windows.Forms.DateTimePicker();
this.label6 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.rolln = new System.Windows.Forms.TextBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.Instant_Attendance = new System.Windows.Forms.TabPage();
this.labtit = new System.Windows.Forms.Label();
this.btn_view = new System.Windows.Forms.Button();
this.num = new System.Windows.Forms.TextBox();
this.view = new System.Windows.Forms.RadioButton();
this.submit = new System.Windows.Forms.Button();
this.insrt = new System.Windows.Forms.RadioButton();
this.date1 = new System.Windows.Forms.DateTimePicker();
this.label5 = new System.Windows.Forms.Label();
this.preabs = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.Inquiry = new System.Windows.Forms.TabPage();
this.laben = new System.Windows.Forms.Label();
this.labper = new System.Windows.Forms.Label();
this.labnam = new System.Windows.Forms.Label();
this.tabControl1.SuspendLayout();
this.Instant_Attendance.SuspendLayout();
this.Inquiry.SuspendLayout();
this.SuspendLayout();
//
// status
//
this.status.AutoSize = true;
this.status.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.status.Location = new System.Drawing.Point(12, 305);
this.status.Name = "status";
this.status.Size = new System.Drawing.Size(0, 17);
this.status.TabIndex = 4;
//
// update
//
this.update.Location = new System.Drawing.Point(129, 211);
this.update.Name = "update";
this.update.Size = new System.Drawing.Size(75, 35);
this.update.TabIndex = 14;
this.update.Text = "Update";
this.update.UseVisualStyleBackColor = true;
this.update.Click += new System.EventHandler(this.update_Click);
//
// radioButton2
//
this.radioButton2.AutoSize = true;
this.radioButton2.Location = new System.Drawing.Point(21, 238);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(58, 17);
this.radioButton2.TabIndex = 13;
this.radioButton2.TabStop = true;
this.radioButton2.Text = "Absent";
this.radioButton2.UseVisualStyleBackColor = true;
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Location = new System.Drawing.Point(21, 201);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(61, 17);
this.radioButton1.TabIndex = 12;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "Present";
this.radioButton1.UseVisualStyleBackColor = true;
//
// detail
//
this.detail.Location = new System.Drawing.Point(85, 83);
this.detail.Name = "detail";
this.detail.Size = new System.Drawing.Size(103, 23);
this.detail.TabIndex = 11;
this.detail.Text = "Show Detail";
this.detail.UseVisualStyleBackColor = true;
this.detail.Click += new System.EventHandler(this.detail_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.label2.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.label2.Location = new System.Drawing.Point(138, 42);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 17);
this.label2.TabIndex = 10;
this.label2.Text = "DATE :";
//
// date2
//
this.date2.CustomFormat = "DD/MM/YY";
this.date2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.date2.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.date2.Location = new System.Drawing.Point(197, 39);
this.date2.MinDate = new System.DateTime(2010, 1, 1, 0, 0, 0, 0);
this.date2.Name = "date2";
this.date2.Size = new System.Drawing.Size(102, 23);
this.date2.TabIndex = 9;
this.date2.ValueChanged += new System.EventHandler(this.date2_ValueChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.label6.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.label6.Location = new System.Drawing.Point(18, 152);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(105, 17);
this.label6.TabIndex = 5;
this.label6.Text = "Enrpllment No :";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.label3.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.label3.Location = new System.Drawing.Point(21, 121);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(55, 17);
this.label3.TabIndex = 3;
this.label3.Text = "NAME :";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.label1.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.label1.Location = new System.Drawing.Point(6, 42);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(66, 17);
this.label1.TabIndex = 1;
this.label1.Text = "Roll No. :";
//
// rolln
//
this.rolln.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.rolln.Location = new System.Drawing.Point(78, 39);
this.rolln.MaxLength = 2;
this.rolln.Name = "rolln";
this.rolln.Size = new System.Drawing.Size(28, 23);
this.rolln.TabIndex = 0;
this.rolln.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.rolln.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.er_keypress);
//
// tabControl1
//
this.tabControl1.Controls.Add(this.Instant_Attendance);
this.tabControl1.Controls.Add(this.Inquiry);
this.tabControl1.Location = new System.Drawing.Point(2, 1);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(329, 301);
this.tabControl1.TabIndex = 8;
//
// Instant_Attendance
//
this.Instant_Attendance.Controls.Add(this.labtit);
this.Instant_Attendance.Controls.Add(this.btn_view);
this.Instant_Attendance.Controls.Add(this.num);
this.Instant_Attendance.Controls.Add(this.view);
this.Instant_Attendance.Controls.Add(this.submit);
this.Instant_Attendance.Controls.Add(this.insrt);
this.Instant_Attendance.Controls.Add(this.date1);
this.Instant_Attendance.Controls.Add(this.label5);
this.Instant_Attendance.Controls.Add(this.preabs);
this.Instant_Attendance.Controls.Add(this.label4);
this.Instant_Attendance.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.Instant_Attendance.Location = new System.Drawing.Point(4, 22);
this.Instant_Attendance.Name = "Instant_Attendance";
this.Instant_Attendance.Padding = new System.Windows.Forms.Padding(3);
this.Instant_Attendance.Size = new System.Drawing.Size(321, 275);
this.Instant_Attendance.TabIndex = 0;
this.Instant_Attendance.Text = "Instant Attendance";
this.Instant_Attendance.UseVisualStyleBackColor = true;
//
// labtit
//
this.labtit.AutoSize = true;
this.labtit.Location = new System.Drawing.Point(6, 111);
this.labtit.Name = "labtit";
this.labtit.Size = new System.Drawing.Size(0, 13);
this.labtit.TabIndex = 11;
//
// btn_view
//
this.btn_view.ForeColor = System.Drawing.SystemColors.ControlText;
this.btn_view.Location = new System.Drawing.Point(167, 220);
this.btn_view.Name = "btn_view";
this.btn_view.Size = new System.Drawing.Size(75, 34);
this.btn_view.TabIndex = 10;
this.btn_view.Text = "View";
this.btn_view.UseVisualStyleBackColor = true;
this.btn_view.Click += new System.EventHandler(this.btn_view_Click);
//
// num
//
this.num.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.num.Location = new System.Drawing.Point(9, 127);
this.num.Multiline = true;
this.num.Name = "num";
this.num.Size = new System.Drawing.Size(295, 87);
this.num.TabIndex = 2;
this.num.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.num_keypress);
//
// view
//
this.view.AutoSize = true;
this.view.ForeColor = System.Drawing.SystemColors.ControlText;
this.view.Location = new System.Drawing.Point(167, 19);
this.view.Name = "view";
this.view.Size = new System.Drawing.Size(48, 17);
this.view.TabIndex = 9;
this.view.TabStop = true;
this.view.Text = "View";
this.view.UseVisualStyleBackColor = true;
//
// submit
//
this.submit.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.submit.ForeColor = System.Drawing.SystemColors.ControlText;
this.submit.Location = new System.Drawing.Point(31, 220);
this.submit.Name = "submit";
this.submit.Size = new System.Drawing.Size(75, 34);
this.submit.TabIndex = 3;
this.submit.Text = "Submit";
this.submit.UseVisualStyleBackColor = true;
this.submit.Click += new System.EventHandler(this.submit_Click);
//
// insrt
//
this.insrt.AutoSize = true;
this.insrt.ForeColor = System.Drawing.SystemColors.ControlText;
this.insrt.Location = new System.Drawing.Point(9, 16);
this.insrt.Name = "insrt";
this.insrt.Size = new System.Drawing.Size(65, 17);
this.insrt.TabIndex = 8;
this.insrt.TabStop = true;
this.insrt.Text = "Insertion";
this.insrt.UseVisualStyleBackColor = true;
this.insrt.CheckedChanged += new System.EventHandler(this.insrt_CheckedChanged);
//
// date1
//
this.date1.Checked = false;
this.date1.CustomFormat = "DD/MM/YY";
this.date1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.date1.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.date1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.date1.Location = new System.Drawing.Point(167, 66);
this.date1.MinDate = new System.DateTime(2010, 1, 1, 0, 0, 0, 0);
this.date1.Name = "date1";
this.date1.Size = new System.Drawing.Size(102, 23);
this.date1.TabIndex = 5;
this.date1.Value = new System.DateTime(2015, 4, 12, 0, 0, 0, 0);
this.date1.ValueChanged += new System.EventHandler(this.date1_ValueChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.label5.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.label5.Location = new System.Drawing.Point(164, 50);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(63, 13);
this.label5.TabIndex = 7;
this.label5.Text = "Select Date";
//
// preabs
//
this.preabs.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.preabs.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.preabs.FormattingEnabled = true;
this.preabs.Items.AddRange(new object[] {
"Absent Numbrs",
"Present Numbers"});
this.preabs.Location = new System.Drawing.Point(9, 65);
this.preabs.Name = "preabs";
this.preabs.Size = new System.Drawing.Size(141, 24);
this.preabs.TabIndex = 1;
this.preabs.SelectedIndexChanged += new System.EventHandler(this.preabs_SelectedIndexChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F);
this.label4.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.label4.Location = new System.Drawing.Point(6, 50);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(81, 13);
this.label4.TabIndex = 6;
this.label4.Text = "Present/Absent";
//
// Inquiry
//
this.Inquiry.Controls.Add(this.laben);
this.Inquiry.Controls.Add(this.labper);
this.Inquiry.Controls.Add(this.labnam);
this.Inquiry.Controls.Add(this.update);
this.Inquiry.Controls.Add(this.label1);
this.Inquiry.Controls.Add(this.radioButton2);
this.Inquiry.Controls.Add(this.rolln);
this.Inquiry.Controls.Add(this.radioButton1);
this.Inquiry.Controls.Add(this.label3);
this.Inquiry.Controls.Add(this.detail);
this.Inquiry.Controls.Add(this.label6);
this.Inquiry.Controls.Add(this.label2);
this.Inquiry.Controls.Add(this.date2);
this.Inquiry.Location = new System.Drawing.Point(4, 22);
this.Inquiry.Name = "Inquiry";
this.Inquiry.Padding = new System.Windows.Forms.Padding(3);
this.Inquiry.Size = new System.Drawing.Size(321, 275);
this.Inquiry.TabIndex = 1;
this.Inquiry.Text = "Inquiry";
this.Inquiry.UseVisualStyleBackColor = true;
//
// laben
//
this.laben.AutoSize = true;
this.laben.Location = new System.Drawing.Point(138, 156);
this.laben.Name = "laben";
this.laben.Size = new System.Drawing.Size(0, 13);
this.laben.TabIndex = 17;
//
// labper
//
this.labper.AutoSize = true;
this.labper.Location = new System.Drawing.Point(112, 138);
this.labper.Name = "labper";
this.labper.Size = new System.Drawing.Size(0, 13);
this.labper.TabIndex = 16;
//
// labnam
//
this.labnam.AutoSize = true;
this.labnam.Location = new System.Drawing.Point(82, 123);
this.labnam.Name = "labnam";
this.labnam.Size = new System.Drawing.Size(0, 13);
this.labnam.TabIndex = 15;
//
// Main
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(333, 336);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.status);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "Main";
this.Text = "UVPCE Attendance Form";
this.Load += new System.EventHandler(this.Form1_Load);
this.tabControl1.ResumeLayout(false);
this.Instant_Attendance.ResumeLayout(false);
this.Instant_Attendance.PerformLayout();
this.Inquiry.ResumeLayout(false);
this.Inquiry.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label status;
private System.Windows.Forms.Button update;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.Button detail;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.DateTimePicker date2;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox rolln;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage Instant_Attendance;
private System.Windows.Forms.Button btn_view;
private System.Windows.Forms.TextBox num;
private System.Windows.Forms.RadioButton view;
private System.Windows.Forms.Button submit;
private System.Windows.Forms.RadioButton insrt;
private System.Windows.Forms.DateTimePicker date1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.ComboBox preabs;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TabPage Inquiry;
private System.Windows.Forms.Label labtit;
private System.Windows.Forms.Label labnam;
private System.Windows.Forms.Label labper;
private System.Windows.Forms.Label laben;
}
}
| |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
//http://treemaps.codeplex.com/
namespace Magic.Controls
{
[TemplatePart(Name = TreeMapItem.HeaderPartName, Type = typeof(FrameworkElement))]
public class TreeMapItem : HeaderedItemsControl
{
#region consts
private const string HeaderPartName = "PART_Header";
#endregion
#region fields
private double _area;
private TreeMaps _parentTreeMaps;
#endregion
#region dependency properties
public static DependencyProperty TreeMapModeProperty
= DependencyProperty.Register("TreeMapMode", typeof(TreeMapAlgo), typeof(TreeMapItem), new FrameworkPropertyMetadata(TreeMapAlgo.Squarified,FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange));
public static readonly DependencyProperty ValuePropertyNameProperty
= DependencyProperty.Register("ValuePropertyName", typeof(string), typeof(TreeMapItem), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsParentArrange | FrameworkPropertyMetadataOptions.AffectsParentMeasure));
public static readonly DependencyProperty LevelProperty
= DependencyProperty.Register("Level", typeof(int), typeof(TreeMapItem),new FrameworkPropertyMetadata(0,FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty MaxDepthProperty
= DependencyProperty.Register("MaxDepth", typeof(int), typeof(TreeMapItem),new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty MinAreaProperty
= DependencyProperty.Register("MinArea", typeof(int), typeof(TreeMapItem), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty ShouldRecurseProperty
= DependencyProperty.Register("ShouldRecurse", typeof(bool), typeof(TreeMapItem), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender));
#endregion
#region ctors
static TreeMapItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TreeMapItem), new FrameworkPropertyMetadata(typeof(TreeMapItem)));
}
public TreeMapItem()
{
this.VerticalAlignment = VerticalAlignment.Stretch;
this.HorizontalAlignment = HorizontalAlignment.Stretch;
this.VerticalContentAlignment = VerticalAlignment.Stretch;
this.HorizontalContentAlignment = HorizontalAlignment.Stretch;
this.SnapsToDevicePixels = true;
}
public TreeMapItem(int level, int maxDepth, int minArea, string valuePropertyName)
: this()
{
this.ValuePropertyName = valuePropertyName;
this.Level = level;
this.MaxDepth = maxDepth;
this.MinArea = minArea;
}
#endregion
#region properties
public TreeMapAlgo TreeMapMode
{
get { return (TreeMapAlgo)this.GetValue(TreeMapItem.TreeMapModeProperty); }
set { this.SetValue(TreeMapItem.TreeMapModeProperty, value); }
}
public string ValuePropertyName
{
get { return (string)this.GetValue(TreeMapItem.ValuePropertyNameProperty); }
set { this.SetValue(TreeMapItem.ValuePropertyNameProperty, value); }
}
public int MaxDepth
{
get { return (int)this.GetValue(TreeMapItem.MaxDepthProperty); }
internal set { this.SetValue(TreeMapItem.MaxDepthProperty, value); }
}
public int MinArea
{
get { return (int)this.GetValue(TreeMapItem.MinAreaProperty); }
internal set { this.SetValue(TreeMapItem.MinAreaProperty, value); }
}
public bool ShouldRecurse
{
get { return (bool)this.GetValue(TreeMapItem.ShouldRecurseProperty); }
internal set { this.SetValue(TreeMapItem.ShouldRecurseProperty, value); }
}
public int Level
{
get { return (int)this.GetValue(TreeMapItem.LevelProperty); }
set { this.SetValue(TreeMapItem.LevelProperty, value); }
}
internal double Area
{
get { return _area; }
}
internal ItemsControl ParentItemsControl
{
get { return ItemsControl.ItemsControlFromItemContainer(this); }
}
internal TreeMaps ParentTreeMap
{
get
{
for (ItemsControl control = this.ParentItemsControl; control != null; control = ItemsControl.ItemsControlFromItemContainer(control))
{
TreeMaps view = control as TreeMaps;
if (view != null)
return view;
}
return null;
}
}
internal TreeMapItem ParentTreeMapItem
{
get { return (this.ParentItemsControl as TreeMapItem); }
}
#endregion
#region protected methods
protected override Size ArrangeOverride(Size arrangeBounds)
{
Size size = base.ArrangeOverride(arrangeBounds);
if (this.IsValidSize(size))
_area = size.Width * size.Height;
else
_area = 0;
this.UpdateShouldRecurse();
return size;
}
protected override DependencyObject GetContainerForItemOverride()
{
return new TreeMapItem(this.Level+1,this.MaxDepth,this.MinArea,this.ValuePropertyName);
}
protected override void OnVisualParentChanged(DependencyObject oldParent)
{
base.OnVisualParentChanged(oldParent);
_parentTreeMaps = this.ParentTreeMap;
if (_parentTreeMaps != null)
{
Binding bindingMode = new Binding(TreeMaps.TreeMapModeProperty.Name);
bindingMode.Source = _parentTreeMaps;
BindingOperations.SetBinding(this, TreeMapItem.TreeMapModeProperty, bindingMode);
Binding bindingValue = new Binding(TreeMaps.ValuePropertyNameProperty.Name);
bindingValue.Source = _parentTreeMaps;
BindingOperations.SetBinding(this, TreeMapItem.ValuePropertyNameProperty, bindingValue);
Binding bindingMinArea = new Binding(TreeMaps.MinAreaProperty.Name);
bindingMinArea.Source = _parentTreeMaps;
BindingOperations.SetBinding(this, TreeMapItem.MinAreaProperty, bindingMinArea);
Binding bindingMaxDepth = new Binding(TreeMaps.MaxDepthProperty.Name);
bindingMaxDepth.Source = _parentTreeMaps;
BindingOperations.SetBinding(this, TreeMapItem.MaxDepthProperty, bindingMaxDepth);
}
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == TreeMapItem.ValuePropertyNameProperty || e.Property == TreeMapItem.DataContextProperty)
{
if (this.ValuePropertyName != null && this.DataContext != null)
{
Binding binding = new Binding(this.ValuePropertyName);
binding.Source = this.DataContext;
BindingOperations.SetBinding(this, TreeMapsPanel.WeightProperty, binding);
}
}
else if (e.Property == TreeMapItem.MaxDepthProperty)
this.UpdateShouldRecurse();
else if (e.Property == TreeMapItem.MinAreaProperty)
this.UpdateShouldRecurse();
else if (e.Property == TreeMapItem.LevelProperty)
this.UpdateShouldRecurse();
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
return (item is TreeMapItem);
}
#endregion
#region private methods
private bool IsValidSize(Size size)
{
return (!size.IsEmpty && size.Width > 0 && size.Width != double.NaN && size.Height > 0 && size.Height != double.NaN);
}
private void UpdateShouldRecurse()
{
if (!this.HasHeader)
{
this.ShouldRecurse = false;
return;
}
this.ShouldRecurse = ((this.MaxDepth == 0) || (this.Level < this.MaxDepth)) && ((this.MinArea == 0) || (this.Area >this.MinArea));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Serialization;
using WhatsAppApi;
using WhatsAppApi.Account;
using WhatsAppApi.Helper;
using WhatsAppApi.Register;
using WhatsAppApi.Response;
namespace WhatsTest
{
internal class Program
{
// DEMO STORE SHOULD BE DATABASE OR PERMANENT MEDIA IN REAL CASE
static IDictionary<string, axolotl_identities_object> axolotl_identities = new Dictionary<string, axolotl_identities_object>();
static IDictionary<uint, axolotl_prekeys_object> axolotl_prekeys = new Dictionary<uint, axolotl_prekeys_object>();
static IDictionary<uint, axolotl_sender_keys_object> axolotl_sender_keys = new Dictionary<uint, axolotl_sender_keys_object>();
static IDictionary<string, axolotl_sessions_object> axolotl_sessions = new Dictionary<string, axolotl_sessions_object>();
static IDictionary<uint, axolotl_signed_prekeys_object> axolotl_signed_prekeys = new Dictionary<uint, axolotl_signed_prekeys_object>();
static WhatsApp wa = null;
static bool debug2file = true;
static string baseDirectory = null;
static string attachmentDirectory = null;
private static void Main(string[] args)
{
var tmpEncoding = Encoding.UTF8;
System.Console.OutputEncoding = Encoding.Default;
System.Console.InputEncoding = Encoding.Default;
baseDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
if (baseDirectory.StartsWith("file:\\"))
{
baseDirectory = baseDirectory.Substring(6);
}
attachmentDirectory = System.IO.Path.Combine(baseDirectory, "attachments");
if (!System.IO.Directory.Exists(attachmentDirectory))
{
System.IO.Directory.CreateDirectory(attachmentDirectory);
}
string settingsFile = System.IO.Path.Combine(baseDirectory, "Settings.xml");
Settings settings = null;
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
if (System.IO.File.Exists(settingsFile))
{
using (TextReader reader = new StreamReader(settingsFile))
{
settings = (Settings)serializer.Deserialize(reader);
}
}
else
{
settings = new Settings();
settings.Nickname = "WhatsApiNet";
settings.Sender = "123456789";
settings.Password = "changeme";
settings.Target = "123456789";
using (TextWriter writer = new StreamWriter(settingsFile))
{
serializer.Serialize(writer, settings);
}
return;
}
string nickname = settings.Nickname ;
string sender = settings.Sender ; // Mobile number with country code (but without + or 00)
string password = settings.Password;//v2 password
string target = settings.Target;// Mobile number to send the message to
wa = new WhatsApp(sender, password, nickname, true);
//event bindings
wa.OnLoginSuccess += wa_OnLoginSuccess;
wa.OnLoginFailed += wa_OnLoginFailed;
wa.OnGetMessage += wa_OnGetMessage;
wa.OnGetMessageReadedClient += wa_OnGetMessageReadedClient;
wa.OnGetMessageReceivedClient += wa_OnGetMessageReceivedClient;
wa.OnGetMessageReceivedServer += wa_OnGetMessageReceivedServer;
wa.OnNotificationPicture += wa_OnNotificationPicture;
wa.OnGetPresence += wa_OnGetPresence;
wa.OnGetGroupParticipants += wa_OnGetGroupParticipants;
wa.OnGetLastSeen += wa_OnGetLastSeen;
wa.OnGetTyping += wa_OnGetTyping;
wa.OnGetPaused += wa_OnGetPaused;
wa.OnGetMessageImage += wa_OnGetMessageImage;
wa.OnGetMessageAudio += wa_OnGetMessageAudio;
wa.OnGetMessageVideo += wa_OnGetMessageVideo;
wa.OnGetMessageLocation += wa_OnGetMessageLocation;
wa.OnGetMessageVcard += wa_OnGetMessageVcard;
wa.OnGetPhoto += wa_OnGetPhoto;
wa.OnGetPhotoPreview += wa_OnGetPhotoPreview;
wa.OnGetGroups += wa_OnGetGroups;
wa.OnGetSyncResult += wa_OnGetSyncResult;
wa.OnGetStatus += wa_OnGetStatus;
wa.OnGetPrivacySettings += wa_OnGetPrivacySettings;
DebugAdapter.Instance.OnPrintDebug += Instance_OnPrintDebug;
wa.SendGetServerProperties();
//ISessionStore AxolotlStore
wa.OnstoreSession += wa_OnstoreSession;
wa.OnloadSession += wa_OnloadSession;
wa.OngetSubDeviceSessions += wa_OngetSubDeviceSessions;
wa.OncontainsSession += wa_OncontainsSession;
wa.OndeleteSession += wa_OndeleteSession;
// IPreKeyStore AxolotlStore
wa.OnstorePreKey += wa_OnstorePreKey;
wa.OnloadPreKey += wa_OnloadPreKey;
wa.OnloadPreKeys += wa_OnloadPreKeys;
wa.OncontainsPreKey += wa_OncontainsPreKey;
wa.OnremovePreKey += wa_OnremovePreKey;
// ISignedPreKeyStore AxolotlStore
wa.OnstoreSignedPreKey += wa_OnstoreSignedPreKey;
wa.OnloadSignedPreKey += wa_OnloadSignedPreKey;
wa.OnloadSignedPreKeys += wa_OnloadSignedPreKeys;
wa.OncontainsSignedPreKey += wa_OncontainsSignedPreKey;
wa.OnremoveSignedPreKey += wa_OnremoveSignedPreKey;
// IIdentityKeyStore AxolotlStore
wa.OngetIdentityKeyPair += wa_OngetIdentityKeyPair;
wa.OngetLocalRegistrationId += wa_OngetLocalRegistrationId;
wa.OnisTrustedIdentity += wa_OnisTrustedIdentity;
wa.OnsaveIdentity += wa_OnsaveIdentity;
wa.OnstoreLocalData += wa_OnstoreLocalData;
// Error Notification ErrorAxolotl
wa.OnErrorAxolotl += wa_OnErrorAxolotl;
wa.Connect();
string datFile = getDatFileName(sender);
byte[] nextChallenge = null;
if (File.Exists(datFile))
{
try
{
string foo = File.ReadAllText(datFile);
nextChallenge = Convert.FromBase64String(foo);
}
catch (Exception) { };
}
wa.Login(nextChallenge);
wa.SendGetPrivacyList();
wa.SendGetClientConfig();
if (wa.LoadPreKeys() == null)
wa.sendSetPreKeys(true);
ProcessChat(wa, target);
Console.ReadKey();
}
static void wa_OnGetMessageReadedClient(string from, string id)
{
Console.WriteLine("Message {0} to {1} read by client", id, from);
}
static void Instance_OnPrintDebug(object value)
{
//
if (debug2file)
{
var debugFile = System.IO.Path.Combine(baseDirectory, String.Format("debug-{0:yyyyMMdd}.log", DateTime.Now));
System.IO.File.AppendAllText(debugFile, String.Format("{0:hhmmss} - {1}\n", DateTime.Now, value));
} else
{
Console.WriteLine(value);
}
}
static void wa_OnGetPrivacySettings(Dictionary<ApiBase.VisibilityCategory, ApiBase.VisibilitySetting> settings)
{
//throw new NotImplementedException();
foreach (var setting in settings)
{
Console.WriteLine(String.Format("Got sprivacy settings {0}: {1}", setting.Key , setting.Value));
}
}
static void wa_OnGetStatus(string from, string type, string name, string status)
{
Console.WriteLine(String.Format("Got status from {0}: {1}", from, status));
}
static string getDatFileName(string pn)
{
string filename = string.Format("{0}.next.dat", pn);
return Path.Combine(Directory.GetCurrentDirectory(), filename);
}
static void wa_OnGetSyncResult(int index, string sid, Dictionary<string, string> existingUsers, string[] failedNumbers)
{
Console.WriteLine("Sync result for {0}:", sid);
foreach (KeyValuePair<string, string> item in existingUsers)
{
Console.WriteLine("Existing: {0} (username {1})", item.Key, item.Value);
}
foreach(string item in failedNumbers)
{
Console.WriteLine("Non-Existing: {0}", item);
}
}
static void wa_OnGetGroups(WaGroupInfo[] groups)
{
Console.WriteLine("Got groups:");
foreach (WaGroupInfo info in groups)
{
Console.WriteLine("\t{0} {1}", info.subject, info.id);
}
}
static void wa_OnGetPhotoPreview(string from, string id, byte[] data)
{
Console.WriteLine("Got preview photo for {0} ({1})", from, id);
//File.WriteAllBytes(string.Format("preview_{0}.jpg", from), data);
var file = System.IO.Path.Combine(attachmentDirectory, string.Format("preview_{0}.jpg", id));
File.WriteAllBytes(file, data);
}
static void wa_OnGetPhoto(string from, string id, byte[] data)
{
Console.WriteLine("Got full photo for {0} ({1})", from, id);
// File.WriteAllBytes(string.Format("{0}.jpg", from), data);
var file = System.IO.Path.Combine(attachmentDirectory, string.Format("{0}.jpg", id));
}
static void wa_OnGetMessageVcard(ProtocolTreeNode vcardNode, string from, string id, string name, byte[] data)
{
Console.WriteLine("Got vcard \"{0}\" from {1} ({2})", name, from, id);
//File.WriteAllBytes(string.Format("{0}.vcf", name), data);
var file = System.IO.Path.Combine(attachmentDirectory, string.Format("preview_{0}.vcf", id));
File.WriteAllBytes(file, data);
}
// string User new
static void wa_OnGetMessageLocation(ProtocolTreeNode locationNode, string from, string id, double lon, double lat, string url, string name, byte[] preview, string User)
{
Console.WriteLine("Got location from {0} ({1}, {2}) ({3})", from, lat, lon, id);
if(!string.IsNullOrEmpty(name))
{
Console.WriteLine("\t{0}", name);
}
//File.WriteAllBytes(string.Format("{0}{1}.jpg", lat, lon), preview);
var file = System.IO.Path.Combine(attachmentDirectory, string.Format("preview_{0}.vcf", id));
File.WriteAllBytes(file, preview);
}
static void wa_OnGetMessageVideo(ProtocolTreeNode mediaNode, string from, string id, string fileName, int fileSize, string url, byte[] preview, string name)
{
Console.WriteLine("Got video from {0}", from, fileName);
OnGetMedia(fileName, url, preview, id);
}
// string name new
static void wa_OnGetMessageAudio(ProtocolTreeNode mediaNode, string from, string id, string fileName, int fileSize, string url, byte[] preview, string name)
{
Console.WriteLine("Got audio from {0}", from, fileName);
OnGetMedia(fileName, url, preview, id);
}
// string name new
static void wa_OnGetMessageImage(ProtocolTreeNode mediaNode, string from, string id, string fileName, int size, string url, byte[] preview, string name)
{
Console.WriteLine("Got image from {0}", from, fileName);
OnGetMedia(fileName, url, preview, id);
}
static void OnGetMedia(string file, string url, byte[] data, string id)
{
var fileName = System.IO.Path.Combine(attachmentDirectory, string.Format("preview_{0}.jpg", id));
File.WriteAllBytes(file, data);
//save preview
//File.WriteAllBytes(string.Format("preview_{0}.jpg", file), data);
//download
using (WebClient wc = new WebClient())
{
wc.DownloadFileAsync(new Uri(url), file, null);
}
}
static void wa_OnGetPaused(string from)
{
Console.WriteLine("{0} stopped typing", from);
}
static void wa_OnGetTyping(string from)
{
Console.WriteLine("{0} is typing...", from);
}
static void wa_OnGetLastSeen(string from, DateTime lastSeen)
{
Console.WriteLine("{0} last seen on {1}", from, lastSeen.ToString());
}
static void wa_OnGetMessageReceivedServer(string from, string id)
{
Console.WriteLine("Message {0} to {1} received by server", id, from);
}
static void wa_OnGetMessageReceivedClient(string from, string id)
{
Console.WriteLine("Message {0} to {1} received by client", id, from);
}
static void wa_OnGetGroupParticipants(string gjid, string[] jids)
{
Console.WriteLine("Got participants from {0}:", gjid);
foreach (string jid in jids)
{
Console.WriteLine("\t{0}", jid);
}
}
static void wa_OnGetPresence(string from, string type)
{
Console.WriteLine("Presence from {0}: {1}", from, type);
}
static void wa_OnNotificationPicture(string type, string jid, string id)
{
//TODO
//throw new NotImplementedException();
}
static void wa_OnGetMessage(ProtocolTreeNode node, string from, string id, string name, string message, bool receipt_sent)
{
Console.WriteLine("Message from {0} {1}: {2}", name, from, message);
}
private static void wa_OnLoginFailed(string data)
{
Console.WriteLine("Login failed. Reason: {0}", data);
}
private static void wa_OnLoginSuccess(string phoneNumber, byte[] data)
{
Console.WriteLine("Login success. Next password:");
string sdata = Convert.ToBase64String(data);
Console.WriteLine(sdata);
try
{
File.WriteAllText(getDatFileName(phoneNumber), sdata);
}
catch (Exception) { }
}
private static void ProcessChat(WhatsApp wa, string dst)
{
var thRecv = new Thread(t =>
{
try
{
while (wa != null)
{
wa.PollMessages();
Thread.Sleep(100);
continue;
}
}
catch (ThreadAbortException)
{
}
}) {IsBackground = true};
thRecv.Start();
WhatsUserManager usrMan = new WhatsUserManager();
var tmpUser = usrMan.CreateUser(dst, "User");
while (true)
{
string line = Console.ReadLine();
if (line == null && line.Length == 0)
continue;
string command = line.Trim();
switch (command)
{
case "/query":
//var dst = dst//trim(strstr($line, ' ', FALSE));
Console.WriteLine("[] Interactive conversation with {0}:", tmpUser);
break;
case "/accountinfo":
Console.WriteLine("[] Account Info: {0}", wa.GetAccountInfo().ToString());
break;
case "/lastseen":
Console.WriteLine("[] Request last seen {0}", tmpUser);
wa.SendQueryLastOnline(tmpUser.GetFullJid());
break;
case "/exit":
wa = null;
thRecv.Abort();
return;
case "/start":
wa.SendComposing(tmpUser.GetFullJid());
break;
case "/pause":
wa.SendPaused(tmpUser.GetFullJid());
break;
default:
Console.WriteLine("[] Send message to {0}: {1}", tmpUser, line);
wa.SendMessage(tmpUser.GetFullJid(), line);
break;
}
}
}
// ALL NE REQUIRED INTERFACES FOR AXOLOTL ARE BELOW
/// <summary>
/// recieve all errormessgaes from the Axolotl process to record
/// </summary>
/// <param name="ErrorMessage"></param>
static void wa_OnErrorAxolotl(string ErrorMessage)
{
//
if (debug2file)
{
var debugFile = System.IO.Path.Combine(baseDirectory, String.Format("debug-{0:yyyyMMdd}.log", DateTime.Now));
System.IO.File.AppendAllText(debugFile, String.Format("{0:hhmmss} - {1}\n", DateTime.Now, ErrorMessage));
}
else
{
Console.WriteLine(ErrorMessage);
}
}
#region DATABASE BINDING FOR IIdentityKeyStore
/// <summary>
///
/// </summary>
/// <param name="recipientId"></param>
/// <param name="identityKey"></param>
static bool wa_OnsaveIdentity(string recipientId, byte[] identityKey)
{
if (axolotl_identities.ContainsKey(recipientId))
axolotl_identities.Remove(recipientId);
axolotl_identities.Add(recipientId, new axolotl_identities_object(){
recipient_id = recipientId,
public_key = identityKey
});
return true;
}
/// <summary>
///
/// </summary>
/// <param name="recipientId"></param>
/// <param name="identityKey"></param>
/// <returns></returns>
static bool wa_OnisTrustedIdentity(string recipientId, byte[] identityKey)
{
axolotl_identities_object trusted;
axolotl_identities.TryGetValue(recipientId, out trusted);
return true; // (trusted == null || trusted.public_key.Equals(identityKey));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
static uint wa_OngetLocalRegistrationId()
{
axolotl_identities_object identity;
axolotl_identities.TryGetValue("-1", out identity);
return (identity == null) ? 000000 : uint.Parse(identity.registration_id);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
static List<byte[]> wa_OngetIdentityKeyPair()
{
List<byte[]> result = new List<byte[]> { };
axolotl_identities_object identity;
axolotl_identities.TryGetValue("-1", out identity);
if (identity != null){
result.Add(identity.public_key);
result.Add(identity.private_key);
}
if (result.Count == 0)
return null;
return result;
}
/// <summary>
///
/// </summary>
/// <param name="registrationId"></param>
/// <param name="identityKeyPair"></param>
static void wa_OnstoreLocalData(uint registrationId, byte[] publickey, byte[] privatekey)
{
if (axolotl_identities.ContainsKey("-1"))
axolotl_identities.Remove("-1");
axolotl_identities.Add("-1", new axolotl_identities_object(){
recipient_id = "-1",
registration_id = registrationId.ToString(),
public_key = publickey,
private_key = privatekey
});
}
#endregion
#region DATABASE BINDING FOR ISignedPreKeyStore
/// <summary>
///
/// </summary>
/// <param name="preKeyId"></param>
static void wa_OnremoveSignedPreKey(uint preKeyId)
{
if (axolotl_signed_prekeys.ContainsKey(preKeyId))
axolotl_signed_prekeys.Remove(preKeyId);
}
/// <summary>
///
/// </summary>
/// <param name="preKeyId"></param>
/// <returns></returns>
static bool wa_OncontainsSignedPreKey(uint preKeyId)
{
axolotl_signed_prekeys_object prekey;
axolotl_signed_prekeys.TryGetValue(preKeyId, out prekey);
return (prekey == null) ? false : true;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
static List<byte[]> wa_OnloadSignedPreKeys()
{
List<byte[]> result = new List<byte[]> { };
foreach (axolotl_signed_prekeys_object key in axolotl_signed_prekeys.Values)
result.Add(key.record);
if (result.Count == 0)
return null;
return result;
}
/// <summary>
///
/// </summary>
/// <param name="preKeyId"></param>
/// <returns></returns>
static byte[] wa_OnloadSignedPreKey(uint preKeyId)
{
axolotl_signed_prekeys_object prekey;
axolotl_signed_prekeys.TryGetValue(preKeyId, out prekey);
return (prekey == null) ? new byte[] { } : prekey.record;
}
/// <summary>
///
/// </summary>
/// <param name="signedPreKeyId"></param>
/// <param name="signedPreKeyRecord"></param>
static void wa_OnstoreSignedPreKey(uint signedPreKeyId, byte[] signedPreKeyRecord)
{
if (axolotl_signed_prekeys.ContainsKey(signedPreKeyId))
axolotl_signed_prekeys.Remove(signedPreKeyId);
axolotl_signed_prekeys.Add(signedPreKeyId, new axolotl_signed_prekeys_object(){
prekey_id = signedPreKeyId,
record = signedPreKeyRecord
});
}
#endregion
#region DATABASE BINDING FOR IPreKeyStore
/// <summary>
///
/// </summary>
/// <param name="preKeyId"></param>
static void wa_OnremovePreKey(uint preKeyId)
{
if (axolotl_prekeys.ContainsKey(preKeyId))
axolotl_prekeys.Remove(preKeyId);
}
/// <summary>
///
/// </summary>
/// <param name="preKeyId"></param>
/// <returns></returns>
static bool wa_OncontainsPreKey(uint preKeyId)
{
axolotl_prekeys_object prekey;
axolotl_prekeys.TryGetValue(preKeyId, out prekey);
return (prekey == null) ? false : true;
}
/// <summary>
///
/// </summary>
/// <param name="preKeyId"></param>
/// <returns></returns>
static byte[] wa_OnloadPreKey(uint preKeyId)
{
axolotl_prekeys_object prekey;
axolotl_prekeys.TryGetValue(preKeyId, out prekey);
return (prekey == null) ? new byte[] { } : prekey.record;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
static List<byte[]> wa_OnloadPreKeys()
{
List<byte[]> result = new List<byte[]> { };
foreach (axolotl_prekeys_object key in axolotl_prekeys.Values)
result.Add(key.record);
if (result.Count == 0)
return null;
return result;
}
/// <summary>
///
/// </summary>
/// <param name="prekeyId"></param>
/// <param name="preKeyRecord"></param>
static void wa_OnstorePreKey(uint prekeyId, byte[] preKeyRecord)
{
if (axolotl_prekeys.ContainsKey(prekeyId))
axolotl_prekeys.Remove(prekeyId);
axolotl_prekeys.Add(prekeyId, new axolotl_prekeys_object()
{
prekey_id = prekeyId.ToString(),
record = preKeyRecord
});
}
#endregion
#region DATABASE BINDING FOR ISessionStore
/// <summary>
///
/// </summary>
/// <param name="recipientId"></param>
/// <param name="deviceId"></param>
static void wa_OndeleteSession(string recipientId, uint deviceId)
{
if (axolotl_sessions.ContainsKey(recipientId))
axolotl_sessions.Remove(recipientId);
}
/// <summary>
///
/// </summary>
/// <param name="recipientId"></param>
/// <param name="deviceId"></param>
/// <returns></returns>
static bool wa_OncontainsSession(string recipientId, uint deviceId)
{
axolotl_sessions_object session;
axolotl_sessions.TryGetValue(recipientId, out session);
return (session == null) ? false : true;
}
/// <summary>
///
/// </summary>
/// <param name="recipientId"></param>
/// <returns></returns>
static List<uint> wa_OngetSubDeviceSessions(string recipientId)
{
List<uint> result = new List<uint> { };
foreach (axolotl_sessions_object key in axolotl_sessions.Values)
result.Add(key.device_id);
return result;
}
/// <summary>
///
/// </summary>
/// <param name="recipientId"></param>
/// <param name="deviceId"></param>
/// <returns></returns>
static byte[] wa_OnloadSession(string recipientId, uint deviceId)
{
axolotl_sessions_object session;
axolotl_sessions.TryGetValue(recipientId, out session);
return (session == null) ? new byte[] { } : session.record;
}
/// <summary>
///
/// </summary>
/// <param name="recipientId"></param>
/// <param name="deviceId"></param>
/// <param name="sessionRecord"></param>
static void wa_OnstoreSession(string recipientId, uint deviceId, byte[] sessionRecord)
{
if (axolotl_sessions.ContainsKey(recipientId))
axolotl_sessions.Remove(recipientId);
axolotl_sessions.Add(recipientId, new axolotl_sessions_object(){
device_id = deviceId,
recipient_id = recipientId,
record = sessionRecord
});
}
#endregion
}
public class axolotl_identities_object {
public string recipient_id { get; set; }
public string registration_id { get; set; }
public byte[] public_key { get; set; }
public byte[] private_key { get; set; }
}
public class axolotl_prekeys_object {
public string prekey_id { get; set; }
public byte[] record { get; set; }
}
public class axolotl_sender_keys_object {
public uint sender_key_id { get; set; }
public byte[] record { get; set; }
}
public class axolotl_sessions_object {
public string recipient_id { get; set; }
public uint device_id { get; set; }
public byte[] record { get; set; }
}
public class axolotl_signed_prekeys_object {
public uint prekey_id { get; set; }
public byte[] record { get; set; }
}
}
| |
#region copyright
// Copyright (c) CBC/Radio-Canada. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#endregion
using System;
using AutoMapper;
using Xunit;
namespace LinkIt.AutoMapperExtensions.Tests
{
public class AutoMapReference_ContextualizationTests
{
private readonly MapperConfiguration _config;
private readonly IMapper _mapper;
public AutoMapReference_ContextualizationTests()
{
_config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<MyMediaLinkedSource, MyMediaSummaryDto>()
.MapLinkedSource()
.ForMember(dto => dto.Id, member => member.MapFrom(source => source.Model.Id));
cfg.CreateMap<MyComplexLinkedSource, MyComplexDto>()
.MapLinkedSource();
});
_mapper = _config.CreateMapper();
}
[Fact]
public void AssertConfigurationIsValid()
{
_config.AssertConfigurationIsValid();
}
[Fact]
public void Map_WithValueContextualization_ShouldContextualizeValue()
{
var linkedSource = new MyMediaLinkedSource
{
Model = new MyMedia
{
Id = 1,
Title = "The title"
},
Contextualization = new MyMediaContextualization
{
Id = 1,
SeekTimeInSec = 32,
Title = "Overridden title"
}
};
var actual = _mapper.Map<MyMediaSummaryDto>(linkedSource);
Assert.Equal(linkedSource.Contextualization.Title, actual.Title);
}
[Fact]
public void Map_WithNullValueInContextualization_ShouldNotContextualizeValue()
{
var linkedSource = new MyMediaLinkedSource
{
Model = new MyMedia
{
Id = 1,
Title = "The title"
},
Contextualization = new MyMediaContextualization
{
Id = 1,
SeekTimeInSec = 32,
Title = null
}
};
var actual = _mapper.Map<MyMediaSummaryDto>(linkedSource);
Assert.Equal(linkedSource.Model.Title, actual.Title);
}
[Fact]
public void Map_WithEmtpyOrWhitespaceStringValueInContextualization_ShouldNotContextualizeValue() {
var linkedSource = new MyMediaLinkedSource {
Model = new MyMedia {
Id = 1,
Title = "The title"
},
Contextualization = new MyMediaContextualization {
Id = 1,
SeekTimeInSec = 32,
Title = " "
}
};
var actual = _mapper.Map<MyMediaSummaryDto>(linkedSource);
Assert.Equal(linkedSource.Model.Title, actual.Title);
}
[Fact]
public void Map_WithAdditionInContextualization_ShouldMapAddition()
{
var linkedSource = new MyMediaLinkedSource
{
Model = new MyMedia
{
Id = 1,
Title = "The title"
},
Contextualization = new MyMediaContextualization
{
Id = 1,
SeekTimeInSec = 32,
Title = "Overridden title"
}
};
var actual = _mapper.Map<MyMediaSummaryDto>(linkedSource);
Assert.Equal(linkedSource.Contextualization.SeekTimeInSec, actual.SeekTimeInSec);
}
[Fact]
public void Map_WithNullContextualization_ShouldNotContextualizeValue()
{
var linkedSource = new MyMediaLinkedSource
{
Model = new MyMedia
{
Id = 1,
Title = "The title"
},
Contextualization = null
};
var actual = _mapper.Map<MyMediaSummaryDto>(linkedSource);
Assert.Equal(linkedSource.Model.Title, actual.Title);
}
[Fact]
public void Map_WithNestedContextualizedLinkedSource_ShouldContextualizeValue()
{
var linkedSource = new MyComplexLinkedSource
{
Model = new MyComplexModel(),
Media = new MyMediaLinkedSource
{
Model = new MyMedia
{
Id = 1,
Title = "The title"
},
Contextualization = new MyMediaContextualization()
{
Id = 1,
SeekTimeInSec = 32,
Title = "Overridden title"
}
}
};
var actual = _mapper.Map<MyComplexDto>(linkedSource);
Assert.Equal(linkedSource.Media.Contextualization.Title, actual.Media.Title);
}
[Fact]
public void Map_ValueTypeContextualizationWithDefault_ShouldUseDefault() {
var linkedSource = new MyMediaLinkedSource {
Model = new MyMedia {
Id = 1,
Title = "The title",
VolumeLevel = 7,
BassEq = 5
},
Contextualization = new MyMediaContextualization {
Id = 1,
SeekTimeInSec = 32,
Title = "Overridden title",
Image = null,
VolumeLevel = 0,
BassEq = null
},
Image = new Uri("http://www.example.com/default.gif")
};
var actual = _mapper.Map<MyMediaSummaryDto>(linkedSource);
Assert.Equal(0, actual.VolumeLevel);
Assert.Equal(5, actual.BassEq.Value);
}
[Fact]
public void Map_ValueTypeContextualizationWithOverrides_ShouldContextualize() {
var linkedSource = new MyMediaLinkedSource {
Model = new MyMedia {
Id = 1,
Title = "The title",
VolumeLevel = 7,
BassEq = 5
},
Contextualization = new MyMediaContextualization {
Id = 1,
SeekTimeInSec = 32,
Title = "Overridden title",
Image = null,
VolumeLevel = 1,
BassEq = 2
},
Image = new Uri("http://www.example.com/default.gif")
};
var actual = _mapper.Map<MyMediaSummaryDto>(linkedSource);
Assert.Equal(1, actual.VolumeLevel);
Assert.Equal(2, actual.BassEq);
}
public class MyMediaLinkedSource
{
public MyMedia Model { get; set; }
public MyMediaContextualization Contextualization { get; set; }
public Uri Image { get; set; }
}
public class MyMedia
{
public int Id { get; set; }
public string Title { get; set; }
public int VolumeLevel { get; set; }
public int? BassEq { get; set; }
}
public class MyMediaContextualization
{
public int Id { get; set; }
public string Title { get; set; }
public int SeekTimeInSec { get; set; }
public int? VolumeLevel { get; set; }
public int? BassEq { get; set; }
public Uri Image { get; set; }
}
public class MyMediaSummaryDto
{
public int Id { get; set; }
public string Title { get; set; }
public int SeekTimeInSec { get; set; }
public Uri Image { get; set; }
public int VolumeLevel { get; set; }
public int? BassEq { get; set; }
}
public class MyComplexLinkedSource
{
public MyComplexModel Model { get; set; }
public MyMediaLinkedSource Media { get; set; }
}
public class MyComplexModel
{
public int Id { get; set; }
public string Title { get; set; }
public int? MediaId { get; set; }
}
public class MyComplexDto
{
public int Id { get; set; }
public string Title { get; set; }
public MyMediaSummaryDto Media { get; set; }
}
}
}
| |
'From Squeak3.7alpha of 11 September 2003 [latest update: #5764] on 4 March 2004 at 3:17:53 pm'!
"Change Set: q09-colorCsTT-nk
Date: 9 July 2003
Author: Ned Konz
Adopted for Squeak 3.7a on 3/4/04 (sw), from Squeakland update 0162colorCsTurtleTrails-nk.cs. There were three collisions with MCP changes but in each case Ned's Squeakland version subsumed the MCP change, so all the code in this update is identical to the Squeakland version.
* Makes turtle trails appear above the background sketch if any
* Makes #color:sees: and #touchesColor: tests work right with display depths > 8.
* Makes #color:sees: and #touchesColor: work right in the World
* Makes the grid visible to #color:sees:, #colorUnder and #touchesColor:
It may break some scripts that use #color:sees: or #touchesColor: on playfields that have background grids, if the color being sought is exactly the same color as the color of the grid. To fix these scripts, change the grid color slightly.
It also will use more memory for the turtle trails form when your display depth is > 8. However, this memory will be discarded before saving the image.
This change set also removes an unnecessary ColorPatchCanvas copy that was in #patchAt:without:andNothingAbove:
v2: made sure that backgroundMorph gets nil'd out when it's unlocked and then deleted."!
!FormCanvas class methodsFor: 'instance creation' stamp: 'nk 7/4/2003 10:11'!
extent: extent depth: depth origin: aPoint clipRect: aRectangle
^ self new
setForm: (Form extent: extent depth: depth);
setOrigin: aPoint clipRect: aRectangle;
yourself! !
!Morph methodsFor: 'geometry eToy' stamp: 'nk 7/7/2003 17:18'!
color: sensitiveColor sees: soughtColor
"Return true if any of my pixels of sensitiveColor intersect with pixels of soughtColor."
"Make a mask with black where sensitiveColor is, white elsewhere"
| myImage sensitivePixelMask map patchBelowMe tfm morphAsFlexed i1 pasteUp |
pasteUp _ self world ifNil: [ ^false ].
tfm := self transformFrom: pasteUp.
morphAsFlexed := tfm isIdentity
ifTrue: [self]
ifFalse: [TransformationMorph new flexing: self clone byTransformation: tfm].
myImage := morphAsFlexed imageForm offset: 0 @ 0.
sensitivePixelMask := Form extent: myImage extent depth: 1.
"ensure at most a 16-bit map"
map := Bitmap new: (1 bitShift: (myImage depth - 1 min: 15)).
map at: (i1 := sensitiveColor indexInMap: map) put: 1.
sensitivePixelMask
copyBits: sensitivePixelMask boundingBox
from: myImage form
at: 0 @ 0
colorMap: map.
"get an image of the world below me"
patchBelowMe := pasteUp
patchAt: morphAsFlexed fullBounds
without: self
andNothingAbove: false.
"
sensitivePixelMask displayAt: 0@0.
patchBelowMe displayAt: 100@0.
"
"intersect world pixels of the color we're looking for with the sensitive pixels"
map at: i1 put: 0. "clear map and reuse it"
map at: (soughtColor indexInMap: map) put: 1.
sensitivePixelMask
copyBits: patchBelowMe boundingBox
from: patchBelowMe
at: 0 @ 0
clippingBox: patchBelowMe boundingBox
rule: Form and
fillColor: nil
map: map.
"
sensitivePixelMask displayAt: 200@0.
"
^(sensitivePixelMask tallyPixelValues second) > 0! !
!Morph methodsFor: 'geometry eToy' stamp: 'nk 7/7/2003 17:19'!
touchesColor: soughtColor
"Return true if any of my pixels overlap pixels of soughtColor."
"Make a shadow mask with black in my shape, white elsewhere"
| map patchBelowMe shadowForm tfm morphAsFlexed pasteUp |
pasteUp := self world ifNil: [ ^false ].
tfm := self transformFrom: pasteUp.
morphAsFlexed := tfm isIdentity
ifTrue: [self]
ifFalse: [TransformationMorph new flexing: self clone byTransformation: tfm].
shadowForm := morphAsFlexed shadowForm offset: 0 @ 0.
"get an image of the world below me"
patchBelowMe := (pasteUp
patchAt: morphAsFlexed fullBounds
without: self
andNothingAbove: false) offset: 0 @ 0.
"
shadowForm displayAt: 0@0.
patchBelowMe displayAt: 100@0.
"
"intersect world pixels of the color we're looking for with our shape."
"ensure a maximum 16-bit map"
map := Bitmap new: (1 bitShift: (patchBelowMe depth - 1 min: 15)).
map at: (soughtColor indexInMap: map) put: 1.
shadowForm
copyBits: patchBelowMe boundingBox
from: patchBelowMe
at: 0 @ 0
clippingBox: patchBelowMe boundingBox
rule: Form and
fillColor: nil
map: map.
"
shadowForm displayAt: 200@0.
"
^(shadowForm tallyPixelValues second) > 0! !
!PasteUpMorph methodsFor: 'drawing' stamp: 'nk 7/4/2003 16:07'!
drawOn: aCanvas
"Draw in order:
- background color
- grid, if any
- background sketch, if any
- Update and draw the turtleTrails form. See the comment in updateTrailsForm.
- cursor box if any
Later (in drawSubmorphsOn:) I will skip drawing the background sketch."
"draw background fill"
super drawOn: aCanvas.
"draw grid"
(self griddingOn and: [self gridVisible])
ifTrue:
[aCanvas fillRectangle: self bounds
fillStyle: (self
gridFormOrigin: self gridOrigin
grid: self gridModulus
background: nil
line: Color lightGray)].
"draw background sketch."
backgroundMorph ifNotNil: [
self clipSubmorphs ifTrue: [
aCanvas clipBy: self clippingBounds
during: [ :canvas | canvas fullDrawMorph: backgroundMorph ]]
ifFalse: [ aCanvas fullDrawMorph: backgroundMorph ]].
"draw turtle trails"
self updateTrailsForm.
turtleTrailsForm
ifNotNil: [aCanvas paintImage: turtleTrailsForm at: self position].
"draw cursor"
(submorphs notEmpty and: [self indicateCursor])
ifTrue:
[aCanvas
frameRectangle: self selectedRect
width: 2
color: Color black]! !
!PasteUpMorph methodsFor: 'painting' stamp: 'nk 7/4/2003 15:59'!
drawSubmorphsOn: aCanvas
"Display submorphs back to front, but skip my background sketch."
| drawBlock |
submorphs isEmpty ifTrue: [^self].
drawBlock := [:canvas | submorphs reverseDo: [:m | m ~~ backgroundMorph ifTrue: [ canvas fullDrawMorph: m ]]].
self clipSubmorphs
ifTrue: [aCanvas clipBy: self clippingBounds during: drawBlock]
ifFalse: [drawBlock value: aCanvas]! !
!PasteUpMorph methodsFor: 'pen' stamp: 'nk 7/7/2003 11:17'!
createOrResizeTrailsForm
"If necessary, create a new turtleTrailsForm or resize the existing one to fill my bounds.
On return, turtleTrailsForm exists and is the correct size.
Use the Display depth so that color comparisons (#color:sees: and #touchesColor:) will work right."
| newForm |
(turtleTrailsForm isNil or: [ turtleTrailsForm extent ~= self extent ]) ifTrue:
["resize TrailsForm if my size has changed"
newForm _ Form extent: self extent depth: Display depth.
turtleTrailsForm ifNotNil: [
newForm copy: self bounds from: turtleTrailsForm
to: 0@0 rule: Form paint ].
turtleTrailsForm _ newForm.
turtlePen _ nil].
"Recreate Pen for this form"
turtlePen ifNil: [turtlePen _ Pen newOnForm: turtleTrailsForm].! !
!PasteUpMorph methodsFor: 'project state' stamp: 'nk 7/4/2003 16:47'!
handsDo: aBlock
^ worldState ifNotNil: [ worldState handsDo: aBlock ]! !
!PasteUpMorph methodsFor: 'project state' stamp: 'nk 7/4/2003 16:46'!
handsReverseDo: aBlock
^ worldState ifNotNil: [ worldState handsReverseDo: aBlock ]! !
!PasteUpMorph methodsFor: 'submorphs-accessing' stamp: 'nk 7/4/2003 16:49'!
morphsInFrontOf: someMorph overlapping: aRectangle do: aBlock
"Include hands if the receiver is the World"
self handsDo:[:m|
m == someMorph ifTrue:["Try getting out quickly"
owner ifNil:[^self].
^owner morphsInFrontOf: self overlapping: aRectangle do: aBlock].
"The hand only overlaps if it's not the hardware cursor"
m needsToBeDrawn ifTrue:[
(m fullBoundsInWorld intersects: aRectangle)
ifTrue:[aBlock value: m]]].
^super morphsInFrontOf: someMorph overlapping: aRectangle do: aBlock! !
!PasteUpMorph methodsFor: 'world state' stamp: 'nk 7/7/2003 11:15'!
patchAt: patchRect without: stopMorph andNothingAbove: stopThere
"Return a complete rendering of this patch of the display screen
without stopMorph, and possibly without anything above it."
| c |
c _ ColorPatchCanvas
extent: patchRect extent
depth: Display depth
origin: patchRect topLeft negated
clipRect: (0@0 extent: patchRect extent).
c stopMorph: stopMorph.
c doStop: stopThere.
(self bounds containsRect: patchRect) ifFalse:
["Need to fill area outside bounds with black."
c form fillColor: Color black].
(self bounds intersects: patchRect) ifFalse:
["Nothing within bounds to show."
^ c form].
self fullDrawOn: c.
stopThere ifFalse: [ self world handsReverseDo: [:h | h drawSubmorphsOn: c]].
^c form
! !
!PasteUpMorph methodsFor: 'private' stamp: 'nk 7/8/2003 09:18'!
privateRemoveMorph: aMorph
backgroundMorph == aMorph ifTrue: [ backgroundMorph _ nil ].
^super privateRemoveMorph: aMorph.
! !
| |
using System.Text.RegularExpressions;
using GitVersion.Common;
using GitVersion.Extensions;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using GitVersion.Model.Exceptions;
namespace GitVersion.Configuration;
public class BranchConfigurationCalculator : IBranchConfigurationCalculator
{
private const string FallbackConfigName = "Fallback";
private const int MaxRecursions = 50;
private readonly ILog log;
private readonly IRepositoryStore repositoryStore;
public BranchConfigurationCalculator(ILog log, IRepositoryStore repositoryStore)
{
this.log = log.NotNull();
this.repositoryStore = repositoryStore.NotNull();
}
/// <summary>
/// Gets the <see cref="BranchConfig"/> for the current commit.
/// </summary>
public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit? currentCommit, Config configuration, IList<IBranch>? excludedInheritBranches = null) =>
GetBranchConfigurationInternal(0, targetBranch, currentCommit, configuration, excludedInheritBranches);
private BranchConfig GetBranchConfigurationInternal(int recursions, IBranch targetBranch, ICommit? currentCommit, Config configuration, IList<IBranch>? excludedInheritBranches = null)
{
if (recursions >= MaxRecursions)
{
throw new InfiniteLoopProtectionException($"Inherited branch configuration caused {recursions} recursions. Aborting!");
}
var matchingBranches = configuration.GetConfigForBranch(targetBranch.Name.WithoutRemote);
if (matchingBranches == null)
{
this.log.Info($"No branch configuration found for branch {targetBranch}, falling back to default configuration");
matchingBranches = BranchConfig.CreateDefaultBranchConfig(FallbackConfigName)
.Apply(new BranchConfig
{
Regex = "",
VersioningMode = configuration.VersioningMode,
Increment = configuration.Increment ?? IncrementStrategy.Inherit
});
}
if (matchingBranches.Increment == IncrementStrategy.Inherit)
{
matchingBranches = InheritBranchConfiguration(recursions, targetBranch, matchingBranches, currentCommit, configuration, excludedInheritBranches);
if (matchingBranches.Name.IsEquivalentTo(FallbackConfigName) && matchingBranches.Increment == IncrementStrategy.Inherit)
{
// We tried, and failed to inherit, just fall back to patch
matchingBranches.Increment = IncrementStrategy.Patch;
}
}
return matchingBranches;
}
// TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases
private BranchConfig InheritBranchConfiguration(int recursions, IBranch targetBranch, BranchConfig branchConfiguration, ICommit? currentCommit, Config configuration, IList<IBranch>? excludedInheritBranches)
{
using (this.log.IndentLog("Attempting to inherit branch configuration from parent branch"))
{
recursions += 1;
var excludedBranches = new[] { targetBranch };
// Check if we are a merge commit. If so likely we are a pull request
if (currentCommit != null)
{
var parentCount = currentCommit.Parents.Count();
if (parentCount == 2)
{
excludedBranches = CalculateWhenMultipleParents(currentCommit, ref targetBranch, excludedBranches);
}
}
excludedInheritBranches ??= this.repositoryStore.GetExcludedInheritBranches(configuration).ToList();
excludedBranches = excludedBranches.Where(b => excludedInheritBranches.All(bte => !b.Equals(bte))).ToArray();
// Add new excluded branches.
foreach (var excludedBranch in excludedBranches)
{
excludedInheritBranches.Add(excludedBranch);
}
var branchesToEvaluate = this.repositoryStore.ExcludingBranches(excludedInheritBranches)
.Distinct(new LocalRemoteBranchEqualityComparer())
.ToList();
var branchPoint = this.repositoryStore
.FindCommitBranchWasBranchedFrom(targetBranch, configuration, excludedInheritBranches.ToArray());
List<IBranch> possibleParents;
if (branchPoint == BranchCommit.Empty)
{
possibleParents = this.repositoryStore.GetBranchesContainingCommit(targetBranch.Tip, branchesToEvaluate)
// It fails to inherit Increment branch configuration if more than 1 parent;
// therefore no point to get more than 2 parents
.Take(2)
.ToList();
}
else
{
var branches = this.repositoryStore.GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate).ToList();
if (branches.Count > 1)
{
var currentTipBranches = this.repositoryStore.GetBranchesContainingCommit(currentCommit, branchesToEvaluate).ToList();
possibleParents = branches.Except(currentTipBranches).ToList();
}
else
{
possibleParents = branches;
}
}
this.log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.ToString())));
if (possibleParents.Count == 1)
{
var branchConfig = GetBranchConfigurationInternal(recursions, possibleParents[0], currentCommit, configuration, excludedInheritBranches);
// If we have resolved a fallback config we should not return that we have got config
if (branchConfig.Name != FallbackConfigName)
{
return new BranchConfig(branchConfiguration)
{
Increment = branchConfig.Increment,
PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion,
// If we are inheriting from develop then we should behave like develop
TracksReleaseBranches = branchConfig.TracksReleaseBranches
};
}
}
// If we fail to inherit it is probably because the branch has been merged and we can't do much. So we will fall back to develop's config
// if develop exists and main if not
var errorMessage = possibleParents.Count == 0
? "Failed to inherit Increment branch configuration, no branches found."
: "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.ToString()));
var chosenBranch = this.repositoryStore.GetChosenBranch(configuration);
if (chosenBranch == null)
{
// TODO We should call the build server to generate this exception, each build server works differently
// for fetch issues and we could give better warnings.
throw new InvalidOperationException("Gitversion could not determine which branch to treat as the development branch (default is 'develop') nor release-able branch (default is 'main' or 'master'), either locally or remotely. Ensure the local clone and checkout match the requirements or considering using 'GitVersion Dynamic Repositories'");
}
this.log.Warning($"{errorMessage}{System.Environment.NewLine}Falling back to {chosenBranch} branch config");
// To prevent infinite loops, make sure that a new branch was chosen.
if (targetBranch.Equals(chosenBranch))
{
var developOrMainConfig =
ChooseMainOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(
chosenBranch, branchConfiguration, configuration);
if (developOrMainConfig != null)
{
return developOrMainConfig;
}
this.log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead.");
return new BranchConfig(branchConfiguration)
{
Increment = IncrementStrategy.Patch
};
}
var inheritingBranchConfig = GetBranchConfigurationInternal(recursions, chosenBranch, currentCommit, configuration, excludedInheritBranches);
var configIncrement = inheritingBranchConfig.Increment;
if (inheritingBranchConfig.Name.IsEquivalentTo(FallbackConfigName) && configIncrement == IncrementStrategy.Inherit)
{
this.log.Warning("Fallback config inherits by default, dropping to patch increment");
configIncrement = IncrementStrategy.Patch;
}
return new BranchConfig(branchConfiguration)
{
Increment = configIncrement,
PreventIncrementOfMergedBranchVersion = inheritingBranchConfig.PreventIncrementOfMergedBranchVersion,
// If we are inheriting from develop then we should behave like develop
TracksReleaseBranches = inheritingBranchConfig.TracksReleaseBranches
};
}
}
private IBranch[] CalculateWhenMultipleParents(ICommit currentCommit, ref IBranch currentBranch, IBranch[] excludedBranches)
{
var parents = currentCommit.Parents.ToArray();
var branches = this.repositoryStore.GetBranchesForCommit(parents[1]).ToList();
if (branches.Count == 1)
{
var branch = branches[0];
excludedBranches = new[]
{
currentBranch,
branch
};
currentBranch = branch;
}
else if (branches.Count > 1)
{
currentBranch = branches.FirstOrDefault(b => b.Name.WithoutRemote == Config.MainBranchKey) ?? branches.First();
}
else
{
var possibleTargetBranches = this.repositoryStore.GetBranchesForCommit(parents[0]).ToList();
if (possibleTargetBranches.Count > 1)
{
currentBranch = possibleTargetBranches.FirstOrDefault(b => b.Name.WithoutRemote == Config.MainBranchKey) ?? possibleTargetBranches.First();
}
else
{
currentBranch = possibleTargetBranches.FirstOrDefault() ?? currentBranch;
}
}
this.log.Info($"HEAD is merge commit, this is likely a pull request using {currentBranch} as base");
return excludedBranches;
}
private static BranchConfig? ChooseMainOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(IBranch chosenBranch, BranchConfig branchConfiguration, Config config)
{
BranchConfig? mainOrDevelopConfig = null;
var developBranchRegex = config.Branches[Config.DevelopBranchKey]?.Regex ?? Config.DevelopBranchRegex;
var mainBranchRegex = config.Branches[Config.MainBranchKey]?.Regex ?? Config.MainBranchRegex;
if (Regex.IsMatch(chosenBranch.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase))
{
// Normally we would not expect this to happen but for safety we add a check
if (config.Branches[Config.DevelopBranchKey]?.Increment !=
IncrementStrategy.Inherit)
{
mainOrDevelopConfig = new BranchConfig(branchConfiguration)
{
Increment = config.Branches[Config.DevelopBranchKey]?.Increment
};
}
}
else if (Regex.IsMatch(chosenBranch.Name.Friendly, mainBranchRegex, RegexOptions.IgnoreCase))
{
// Normally we would not expect this to happen but for safety we add a check
if (config.Branches[Config.MainBranchKey]?.Increment !=
IncrementStrategy.Inherit)
{
mainOrDevelopConfig = new BranchConfig(branchConfiguration)
{
Increment = config.Branches[Config.DevelopBranchKey]?.Increment
};
}
}
return mainOrDevelopConfig;
}
private class LocalRemoteBranchEqualityComparer : IEqualityComparer<IBranch>
{
public bool Equals(IBranch? b1, IBranch? b2)
{
if (b1 == null && b2 == null)
return true;
if (b1 == null || b2 == null)
return false;
return b1.Name.WithoutRemote.Equals(b2.Name.WithoutRemote);
}
public int GetHashCode(IBranch b) => b.Name.WithoutRemote.GetHashCode();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
#if HTTP_DLL
internal enum WindowsProxyUsePolicy
#else
public enum WindowsProxyUsePolicy
#endif
{
DoNotUseProxy = 0, // Don't use a proxy at all.
UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported.
UseWinInetProxy = 2, // WPAD protocol and PAC files supported.
UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property.
}
#if HTTP_DLL
internal enum CookieUsePolicy
#else
public enum CookieUsePolicy
#endif
{
IgnoreCookies = 0,
UseInternalCookieStoreOnly = 1,
UseSpecifiedCookieContainer = 2
}
#if HTTP_DLL
internal class WinHttpHandler : HttpMessageHandler
#else
public class WinHttpHandler : HttpMessageHandler
#endif
{
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private object _lockObject = new object();
private bool _doManualDecompressionCheck = false;
private WinInetProxyHelper _proxyHelper = null;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
private CookieContainer _cookieContainer = null;
private SslProtocols _sslProtocols = SecurityProtocol.DefaultSecurityProtocols;
private Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> _serverCertificateValidationCallback = null;
private bool _checkCertificateRevocationList = false;
private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual;
private X509Certificate2Collection _clientCertificates = null; // Only create collection when required.
private ICredentials _serverCredentials = null;
private bool _preAuthenticate = false;
private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
private ICredentials _defaultProxyCredentials = CredentialCache.DefaultCredentials;
private IWebProxy _proxy = null;
private int _maxConnectionsPerServer = int.MaxValue;
private TimeSpan _connectTimeout = TimeSpan.FromSeconds(60);
private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30);
private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30);
private int _maxResponseHeadersLength = 64 * 1024;
private int _maxResponseDrainSize = 64 * 1024;
private volatile bool _operationStarted;
private volatile bool _disposed;
private SafeWinHttpHandle _sessionHandle;
private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper();
public WinHttpHandler()
{
}
#region Properties
public bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
public int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
public CookieUsePolicy CookieUsePolicy
{
get
{
return _cookieUsePolicy;
}
set
{
if (value != CookieUsePolicy.IgnoreCookies
&& value != CookieUsePolicy.UseInternalCookieStoreOnly
&& value != CookieUsePolicy.UseSpecifiedCookieContainer)
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_cookieUsePolicy = value;
}
}
public CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
public SslProtocols SslProtocols
{
get
{
return _sslProtocols;
}
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: false);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
public Func<
HttpRequestMessage,
X509Certificate2,
X509Chain,
SslPolicyErrors,
bool> ServerCertificateValidationCallback
{
get
{
return _serverCertificateValidationCallback;
}
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
public bool CheckCertificateRevocationList
{
get
{
return _checkCertificateRevocationList;
}
set
{
_checkCertificateRevocationList = value;
}
}
public ClientCertificateOption ClientCertificateOption
{
get
{
return _clientCertificateOption;
}
set
{
if (value != ClientCertificateOption.Manual
&& value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
public X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
public bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public ICredentials ServerCredentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
public WindowsProxyUsePolicy WindowsProxyUsePolicy
{
get
{
return _windowsProxyUsePolicy;
}
set
{
if (value != WindowsProxyUsePolicy.DoNotUseProxy &&
value != WindowsProxyUsePolicy.UseWinHttpProxy &&
value != WindowsProxyUsePolicy.UseWinInetProxy &&
value != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_windowsProxyUsePolicy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get
{
return _defaultProxyCredentials;
}
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
public IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
public int MaxConnectionsPerServer
{
get
{
return _maxConnectionsPerServer;
}
set
{
if (value < 1)
{
// In WinHTTP, setting this to 0 results in it being reset to 2.
// So, we'll only allow settings above 0.
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
public TimeSpan ConnectTimeout
{
get
{
return _connectTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_connectTimeout = value;
}
}
public TimeSpan SendTimeout
{
get
{
return _sendTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_sendTimeout = value;
}
}
public TimeSpan ReceiveHeadersTimeout
{
get
{
return _receiveHeadersTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_receiveHeadersTimeout = value;
}
}
public TimeSpan ReceiveDataTimeout
{
get
{
return _receiveDataTimeout;
}
set
{
if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_receiveDataTimeout = value;
}
}
public int MaxResponseHeadersLength
{
get
{
return _maxResponseHeadersLength;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
public int MaxResponseDrainSize
{
get
{
return _maxResponseDrainSize;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseDrainSize = value;
}
}
#endregion
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing && _sessionHandle != null)
{
SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle);
}
}
base.Dispose(disposing);
}
#if HTTP_DLL
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#else
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException("request", SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => ((WinHttpRequestState)s).Handler.StartRequest(s),
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
return tcs.Task;
}
private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage)
{
bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue &&
requestMessage.Headers.TransferEncodingChunked.Value;
HttpContent requestContent = requestMessage.Content;
if (requestContent != null)
{
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up
// stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain
// the same behavior.
requestContent.Headers.ContentLength = null;
}
}
else
{
if (!chunkedMode)
{
// Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given.
// Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and
// buffers the content as well in some cases. But the WinHttpHandler can't access
// the protected internal TryComputeLength() method of the content. So, it
// will use'Transfer-Encoding: chunked' semantics.
chunkedMode = true;
requestMessage.Headers.TransferEncodingChunked = true;
}
}
}
else if (chunkedMode)
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
return chunkedMode;
}
private static void AddRequestHeaders(
SafeWinHttpHandle requestHandle,
HttpRequestMessage requestMessage,
CookieContainer cookies)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (cookies != null)
{
string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString());
// Serialize entity-body (content) headers.
if (requestMessage.Content != null)
{
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = requestMessage.Content.Headers.ContentLength.Value;
requestMessage.Content.Headers.ContentLength = null;
requestMessage.Content.Headers.ContentLength = contentLength;
}
requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString());
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void EnsureSessionHandleExists(WinHttpRequestState state)
{
if (_sessionHandle == null)
{
lock (_lockObject)
{
if (_sessionHandle == null)
{
uint accessType;
// If a custom proxy is specified and it is really the system web proxy
// (initial WebRequest.DefaultWebProxy) then we need to update the settings
// since that object is only a sentinel.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
Debug.Assert(state.Proxy != null);
try
{
state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
catch (PlatformNotSupportedException)
{
// This is the system web proxy.
state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
state.Proxy = null;
}
}
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy)
{
// Either no proxy at all or a custom IWebProxy proxy is specified.
// For a custom IWebProxy, we'll need to calculate and set the proxy
// on a per request handle basis using the request Uri. For now,
// we set the session handle to have no proxy.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy)
{
// Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY;
}
else
{
// Use WinInet per-user proxy settings.
accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
}
_sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
accessType,
Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
if (_sessionHandle.IsInvalid)
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER)
{
ThrowOnInvalidHandle(_sessionHandle);
}
// We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support
// WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy
// settings ourself using our WinInetProxyHelper object.
_proxyHelper = new WinInetProxyHelper();
_sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
_proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME,
_proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(_sessionHandle);
}
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
_sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
// This option is not available on downlevel Windows versions. While it improves
// performance, we can ignore the error that the option is not available.
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
}
}
}
private async void StartRequest(object obj)
{
WinHttpRequestState state = (WinHttpRequestState)obj;
bool secureConnection = false;
HttpResponseMessage responseMessage = null;
Exception savedException = null;
SafeWinHttpHandle connectHandle = null;
if (state.CancellationToken.IsCancellationRequested)
{
state.Tcs.TrySetCanceled(state.CancellationToken);
return;
}
try
{
EnsureSessionHandleExists(state);
SetSessionHandleOptions();
// Specify an HTTP server.
connectHandle = Interop.WinHttp.WinHttpConnect(
_sessionHandle,
state.RequestMessage.RequestUri.Host,
(ushort)state.RequestMessage.RequestUri.Port,
0);
ThrowOnInvalidHandle(connectHandle);
connectHandle.SetParentHandle(_sessionHandle);
if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https)
{
secureConnection = true;
}
else
{
secureConnection = false;
}
// Try to use the requested version if a known/supported version was explicitly requested.
// Otherwise, we simply use winhttp's default.
string httpVersion = null;
if (state.RequestMessage.Version == HttpVersion.Version10)
{
httpVersion = "HTTP/1.0";
}
else if (state.RequestMessage.Version == HttpVersion.Version11)
{
httpVersion = "HTTP/1.1";
}
// Create an HTTP request handle.
state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest(
connectHandle,
state.RequestMessage.Method.Method,
state.RequestMessage.RequestUri.PathAndQuery,
httpVersion,
Interop.WinHttp.WINHTTP_NO_REFERER,
Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(state.RequestHandle);
state.RequestHandle.SetParentHandle(connectHandle);
// Set callback function.
SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate);
// Set needed options on the request handle.
SetRequestHandleOptions(state);
bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage);
AddRequestHeaders(
state.RequestHandle,
state.RequestMessage,
_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null);
uint proxyAuthScheme = 0;
uint serverAuthScheme = 0;
state.RetryRequest = false;
// The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle.
// We will detect a cancellation request on the cancellation token by registering a callback.
// If the callback is invoked, then we begin the abort process by disposing the handle. This
// will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks
// on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide
// a more timely, cooperative, cancellation pattern.
using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state))
{
do
{
_authHelper.PreAuthenticateRequest(state, proxyAuthScheme);
await InternalSendRequestAsync(state).ConfigureAwait(false);
if (state.RequestMessage.Content != null)
{
await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false);
}
bool receivedResponse = await InternalReceiveResponseHeadersAsync(state).ConfigureAwait(false);
if (receivedResponse)
{
// If we're manually handling cookies, we need to add them to the container after
// each response has been received.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
}
_authHelper.CheckResponseForAuthentication(
state,
ref proxyAuthScheme,
ref serverAuthScheme);
}
} while (state.RetryRequest);
}
state.CancellationToken.ThrowIfCancellationRequested();
responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck);
// Since the headers have been read, set the "receive" timeout to be based on each read
// call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each
// lower layer winsock read.
uint optionData = (uint)_receiveDataTimeout.TotalMilliseconds;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData);
}
catch (Exception ex)
{
if (state.SavedException != null)
{
savedException = state.SavedException;
}
else
{
savedException = ex;
}
}
finally
{
SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle);
}
// Move the main task to a terminal state. This releases any callers of SendAsync() that are awaiting.
if (responseMessage != null)
{
state.Tcs.TrySetResult(responseMessage);
}
else
{
HandleAsyncException(state, savedException);
}
}
private void SetSessionHandleOptions()
{
SetSessionHandleConnectionOptions();
SetSessionHandleTlsOptions();
SetSessionHandleTimeoutOptions();
}
private void SetSessionHandleConnectionOptions()
{
uint optionData = (uint)_maxConnectionsPerServer;
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData);
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData);
}
private void SetSessionHandleTlsOptions()
{
uint optionData = 0;
if ((_sslProtocols & SslProtocols.Tls) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1;
}
if ((_sslProtocols & SslProtocols.Tls11) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
}
if ((_sslProtocols & SslProtocols.Tls12) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
}
SetWinHttpOption(_sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData);
}
private void SetSessionHandleTimeoutOptions()
{
if (!Interop.WinHttp.WinHttpSetTimeouts(
_sessionHandle,
0,
(int)_connectTimeout.TotalMilliseconds,
(int)_sendTimeout.TotalMilliseconds,
(int)_receiveHeadersTimeout.TotalMilliseconds))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
}
private void SetRequestHandleProxyOptions(WinHttpRequestState state)
{
// We've already set the proxy on the session handle if we're using no proxy or default proxy settings.
// We only need to change it on the request handle if we have a specific IWebProxy or need to manually
// implement Wininet-style auto proxy detection.
if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy ||
state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy)
{
var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO();
bool updateProxySettings = false;
Uri uri = state.RequestMessage.RequestUri;
try
{
if (state.Proxy != null)
{
Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy);
updateProxySettings = true;
if (state.Proxy.IsBypassed(uri))
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY;
}
else
{
proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY;
Uri proxyUri = state.Proxy.GetProxy(uri);
string proxyString = string.Format(
CultureInfo.InvariantCulture,
"{0}://{1}",
proxyUri.Scheme,
proxyUri.Authority);
proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString);
}
}
else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed)
{
updateProxySettings = true;
_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo);
}
if (updateProxySettings)
{
GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned);
try
{
SetWinHttpOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_PROXY,
pinnedHandle.AddrOfPinnedObject(),
(uint)Marshal.SizeOf(proxyInfo));
}
finally
{
pinnedHandle.Free();
}
}
}
finally
{
Marshal.FreeHGlobal(proxyInfo.Proxy);
Marshal.FreeHGlobal(proxyInfo.ProxyBypass);
}
}
}
private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticDecompression != DecompressionMethods.None)
{
if ((_automaticDecompression & DecompressionMethods.GZip) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP;
}
if ((_automaticDecompression & DecompressionMethods.Deflate) != 0)
{
optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
}
try
{
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData);
}
catch (WinHttpException ex)
{
if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION)
{
throw;
}
// We are running on a platform earlier than Win8.1 for which WINHTTP.DLL
// doesn't support this option. So, we'll have to do the decompression
// manually.
_doManualDecompressionCheck = true;
}
}
}
private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = 0;
if (_automaticRedirection)
{
optionData = (uint)_maxAutomaticRedirections;
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS,
ref optionData);
}
optionData = _automaticRedirection ?
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP :
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData);
}
private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle)
{
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ||
_cookieUsePolicy == CookieUsePolicy.IgnoreCookies)
{
uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle)
{
// If we have a custom server certificate validation callback method then
// we need to have WinHTTP ignore some errors so that the callback method
// will have a chance to be called.
uint optionData;
if (_serverCertificateValidationCallback != null)
{
optionData =
Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData);
}
else if (_checkCertificateRevocationList)
{
// If no custom validation method, then we let WinHTTP do the revocation check itself.
optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData);
}
}
private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri)
{
if (requestUri.Scheme != UriScheme.Https)
{
return;
}
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
clientCertificate.Handle,
(uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>());
}
else
{
SetNoClientCertificate(requestHandle);
}
}
internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle)
{
SetWinHttpOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
IntPtr.Zero,
0);
}
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// Set WinHTTP to send/prevent default credentials for either proxy or server auth.
bool useDefaultCredentials = false;
if (state.ServerCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.WindowsProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy)
{
if (state.Proxy == null && _defaultProxyCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.Proxy != null && state.Proxy.Credentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
}
uint optionData = useDefaultCredentials ?
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_AUTOLOGON_POLICY, ref optionData);
}
private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle)
{
uint optionData = (uint)_maxResponseHeadersLength;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData);
optionData = (uint)_maxResponseDrainSize;
SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData);
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
(uint)optionData.Length))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static void SetWinHttpOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionSize)
{
if (!Interop.WinHttp.WinHttpSetOption(
handle,
option,
optionData,
optionSize))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private void HandleAsyncException(WinHttpRequestState state, Exception ex)
{
if (state.CancellationToken.IsCancellationRequested)
{
// If the exception was due to the cancellation token being canceled, throw cancellation exception.
state.Tcs.TrySetCanceled(state.CancellationToken);
}
else if (ex is WinHttpException || ex is IOException)
{
// Wrap expected exceptions as HttpRequestExceptions since this is considered an error during
// execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions
// are 'unexpected' or caused by user error and should not be wrapped.
state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex));
}
else
{
state.Tcs.TrySetException(ex);
}
}
private void SetOperationStarted()
{
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void SetStatusCallback(
SafeWinHttpHandle requestHandle,
Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback)
{
// TODO: Issue #5036. Having the status callback use WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS
// isn't strictly necessary. However, some of the notification flags are required.
// This will be addressed this as part of WinHttpHandler performance improvements.
IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback(
requestHandle,
callback,
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
IntPtr.Zero);
if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed.
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
}
private void ThrowOnInvalidHandle(SafeWinHttpHandle handle)
{
if (handle.IsInvalid)
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private Task<bool> InternalSendRequestAsync(WinHttpRequestState state)
{
state.TcsSendRequest = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.TcsSendRequest.Task;
}
private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend)
{
using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend))
{
await state.RequestMessage.Content.CopyToAsync(
requestStream,
state.TransportContext).ConfigureAwait(false);
await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false);
}
}
private Task<bool> InternalReceiveResponseHeadersAsync(WinHttpRequestState state)
{
state.TcsReceiveResponseHeaders =
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero))
{
throw WinHttpException.CreateExceptionUsingLastError();
}
}
return state.TcsReceiveResponseHeaders.Task;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public abstract class HttpClientHandlerTest_Cookies : HttpClientHandlerTestBase
{
private const string s_cookieName = "ABC";
private const string s_cookieValue = "123";
private const string s_expectedCookieHeaderValue = "ABC=123";
private const string s_customCookieHeaderValue = "CustomCookie=456";
private const string s_simpleContent = "Hello world!";
public HttpClientHandlerTest_Cookies(ITestOutputHelper output) : base(output) { }
//
// Send cookie tests
//
private static CookieContainer CreateSingleCookieContainer(Uri uri) => CreateSingleCookieContainer(uri, s_cookieName, s_cookieValue);
private static CookieContainer CreateSingleCookieContainer(Uri uri, string cookieName, string cookieValue)
{
var container = new CookieContainer();
container.Add(uri, new Cookie(cookieName, cookieValue));
return container;
}
private static string GetCookieHeaderValue(string cookieName, string cookieValue) => $"{cookieName}={cookieValue}";
[Fact]
public async Task GetAsync_DefaultCoookieContainer_NoCookieSent()
{
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
using (HttpClient client = CreateHttpClient())
{
await client.GetAsync(uri);
}
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
Assert.Equal(0, requestData.GetHeaderValueCount("Cookie"));
});
}
[Theory]
[MemberData(nameof(CookieNamesValuesAndUseCookies))]
public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue, bool useCookies)
{
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.CookieContainer = CreateSingleCookieContainer(uri, cookieName, cookieValue);
handler.UseCookies = useCookies;
using (HttpClient client = CreateHttpClient(handler))
{
await client.GetAsync(uri);
}
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
if (useCookies)
{
Assert.Equal(GetCookieHeaderValue(cookieName, cookieValue), requestData.GetSingleHeaderValue("Cookie"));
}
else
{
Assert.Equal(0, requestData.GetHeaderValueCount("Cookie"));
}
});
}
[Fact]
public async Task GetAsync_SetCookieContainerMultipleCookies_CookiesSent()
{
var cookies = new Cookie[]
{
new Cookie("hello", "world"),
new Cookie("foo", "bar"),
new Cookie("ABC", "123")
};
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
HttpClientHandler handler = CreateHttpClientHandler();
var cookieContainer = new CookieContainer();
foreach (Cookie c in cookies)
{
cookieContainer.Add(uri, c);
}
handler.CookieContainer = cookieContainer;
using (HttpClient client = CreateHttpClient(handler))
{
await client.GetAsync(uri);
}
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
string expectedHeaderValue = string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}").ToArray());
Assert.Equal(expectedHeaderValue, requestData.GetSingleHeaderValue("Cookie"));
});
}
[Fact]
public async Task GetAsync_AddCookieHeader_CookieHeaderSent()
{
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
using (HttpClient client = CreateHttpClient())
{
var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri) { Version = VersionFromUseHttp2 };
requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue);
await client.SendAsync(requestMessage);
}
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
Assert.Equal(s_customCookieHeaderValue, requestData.GetSingleHeaderValue("Cookie"));
});
}
[Fact]
public async Task GetAsync_AddMultipleCookieHeaders_CookiesSent()
{
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
using (HttpClient client = CreateHttpClient())
{
var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri) { Version = VersionFromUseHttp2 };
requestMessage.Headers.Add("Cookie", "A=1");
requestMessage.Headers.Add("Cookie", "B=2");
requestMessage.Headers.Add("Cookie", "C=3");
await client.SendAsync(requestMessage);
}
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
// Multiple Cookie header values are treated as any other header values and are
// concatenated using ", " as the separator.
string cookieHeaderValue = requestData.GetSingleHeaderValue("Cookie");
var cookieValues = cookieHeaderValue.Split(new string[] { ", " }, StringSplitOptions.None);
Assert.Contains("A=1", cookieValues);
Assert.Contains("B=2", cookieValues);
Assert.Contains("C=3", cookieValues);
Assert.Equal(3, cookieValues.Count());
});
}
private string GetCookieValue(HttpRequestData request)
{
if (!LoopbackServerFactory.IsHttp2)
{
// HTTP/1.x must have only one value.
return request.GetSingleHeaderValue("Cookie");
}
string cookieHeaderValue = null;
string[] cookieHeaderValues = request.GetHeaderValues("Cookie");
foreach (string header in cookieHeaderValues)
{
if (cookieHeaderValue == null)
{
cookieHeaderValue = header;
}
else
{
// rfc7540 8.1.2.5 states multiple cookie headers should be represented as single value.
cookieHeaderValue = String.Concat(cookieHeaderValue, "; ", header);
}
}
return cookieHeaderValue;
}
[ConditionalFact]
public async Task GetAsync_SetCookieContainerAndCookieHeader_BothCookiesSent()
{
if (IsCurlHandler)
{
// CurlHandler ignores container cookies when custom Cookie header is set.
// SocketsHttpHandler behaves the expected way. Not worth fixing in CurlHandler as it is going away.
throw new SkipTestException("Platform limitation with curl");
}
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.CookieContainer = CreateSingleCookieContainer(url);
using (HttpClient client = CreateHttpClient(handler))
{
var requestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue);
Task<HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage);
Task<HttpRequestData> serverTask = server.HandleRequestAsync();
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
HttpRequestData requestData = await serverTask;
string cookieHeaderValue = GetCookieValue(requestData);
var cookies = cookieHeaderValue.Split(new string[] { "; " }, StringSplitOptions.None);
Assert.Contains(s_expectedCookieHeaderValue, cookies);
Assert.Contains(s_customCookieHeaderValue, cookies);
Assert.Equal(2, cookies.Count());
}
});
}
[ConditionalFact]
public async Task GetAsync_SetCookieContainerAndMultipleCookieHeaders_BothCookiesSent()
{
if (IsCurlHandler)
{
// CurlHandler ignores container cookies when custom Cookie header is set.
// SocketsHttpHandler behaves the expected way. Not worth fixing in CurlHandler as it is going away.
throw new SkipTestException("Platform limitation with curl");
}
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.CookieContainer = CreateSingleCookieContainer(url);
using (HttpClient client = CreateHttpClient(handler))
{
var requestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Version = VersionFromUseHttp2 };
requestMessage.Headers.Add("Cookie", "A=1");
requestMessage.Headers.Add("Cookie", "B=2");
Task<HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage);
Task<HttpRequestData> serverTask = server.HandleRequestAsync();
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
HttpRequestData requestData = await serverTask;
string cookieHeaderValue = GetCookieValue(requestData);
// Multiple Cookie header values are treated as any other header values and are
// concatenated using ", " as the separator. The container cookie is concatenated to
// one of these values using the "; " cookie separator.
var cookieValues = cookieHeaderValue.Split(new string[] { ", " }, StringSplitOptions.None);
Assert.Equal(2, cookieValues.Count());
// Find container cookie and remove it so we can validate the rest of the cookie header values
bool sawContainerCookie = false;
for (int i = 0; i < cookieValues.Length; i++)
{
if (cookieValues[i].Contains(';'))
{
Assert.False(sawContainerCookie);
var cookies = cookieValues[i].Split(new string[] { "; " }, StringSplitOptions.None);
Assert.Equal(2, cookies.Count());
Assert.Contains(s_expectedCookieHeaderValue, cookies);
sawContainerCookie = true;
cookieValues[i] = cookies.Where(c => c != s_expectedCookieHeaderValue).Single();
}
}
Assert.Contains("A=1", cookieValues);
Assert.Contains("B=2", cookieValues);
}
});
}
[Fact]
public async Task GetAsyncWithRedirect_SetCookieContainer_CorrectCookiesSent()
{
const string path1 = "/foo";
const string path2 = "/bar";
await LoopbackServerFactory.CreateClientAndServerAsync(async url =>
{
Uri url1 = new Uri(url, path1);
Uri url2 = new Uri(url, path2);
Uri unusedUrl = new Uri(url, "/unused");
HttpClientHandler handler = CreateHttpClientHandler();
handler.CookieContainer = new CookieContainer();
handler.CookieContainer.Add(url1, new Cookie("cookie1", "value1"));
handler.CookieContainer.Add(url2, new Cookie("cookie2", "value2"));
handler.CookieContainer.Add(unusedUrl, new Cookie("cookie3", "value3"));
using (HttpClient client = CreateHttpClient(handler))
{
client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling
await client.GetAsync(url1);
}
},
async server =>
{
HttpRequestData requestData1 = await server.HandleRequestAsync(HttpStatusCode.Found, new HttpHeaderData[] { new HttpHeaderData("Location", path2) });
Assert.Equal("cookie1=value1", requestData1.GetSingleHeaderValue("Cookie"));
HttpRequestData requestData2 = await server.HandleRequestAsync(content: s_simpleContent);
Assert.Equal("cookie2=value2", requestData2.GetSingleHeaderValue("Cookie"));
});
}
//
// Receive cookie tests
//
[Theory]
[MemberData(nameof(CookieNamesValuesAndUseCookies))]
public async Task GetAsync_ReceiveSetCookieHeader_CookieAdded(string cookieName, string cookieValue, bool useCookies)
{
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.UseCookies = useCookies;
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
Task<HttpRequestData> serverTask = server.HandleRequestAsync(
HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", GetCookieHeaderValue(cookieName, cookieValue)) }, s_simpleContent);
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
if (useCookies)
{
Assert.Equal(1, collection.Count);
Assert.Equal(cookieName, collection[0].Name);
Assert.Equal(cookieValue, collection[0].Value);
}
else
{
Assert.Equal(0, collection.Count);
}
}
});
}
[Fact]
public async Task GetAsync_ReceiveMultipleSetCookieHeaders_CookieAdded()
{
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
Task<HttpRequestData> serverTask = server.HandleRequestAsync(
HttpStatusCode.OK,
new HttpHeaderData[]
{
new HttpHeaderData("Set-Cookie", "A=1; Path=/"),
new HttpHeaderData("Set-Cookie", "B=2; Path=/"),
new HttpHeaderData("Set-Cookie", "C=3; Path=/")
},
s_simpleContent);
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
Assert.Equal(3, collection.Count);
// Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie>
Cookie[] cookies = new Cookie[3];
collection.CopyTo(cookies, 0);
Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1");
Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2");
Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3");
}
});
}
[Fact]
public async Task GetAsync_ReceiveSetCookieHeader_CookieUpdated()
{
const string newCookieValue = "789";
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.CookieContainer = CreateSingleCookieContainer(url);
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
Task<HttpRequestData> serverTask = server.HandleRequestAsync(
HttpStatusCode.OK,
new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", $"{s_cookieName}={newCookieValue}") },
s_simpleContent);
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
Assert.Equal(1, collection.Count);
Assert.Equal(s_cookieName, collection[0].Name);
Assert.Equal(newCookieValue, collection[0].Value);
}
});
}
[Fact]
public async Task GetAsync_ReceiveSetCookieHeader_CookieRemoved()
{
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.CookieContainer = CreateSingleCookieContainer(url);
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
Task<HttpRequestData> serverTask = server.HandleRequestAsync(
HttpStatusCode.OK,
new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", $"{s_cookieName}=; Expires=Sun, 06 Nov 1994 08:49:37 GMT") },
s_simpleContent);
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
Assert.Equal(0, collection.Count);
}
});
}
[Fact]
public async Task GetAsync_ReceiveInvalidSetCookieHeader_ValidCookiesAdded()
{
if (IsNetfxHandler)
{
// NetfxHandler incorrectly only processes one valid cookie
return;
}
await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
Task<HttpRequestData> serverTask = server.HandleRequestAsync(
HttpStatusCode.OK,
new HttpHeaderData[]
{
new HttpHeaderData("Set-Cookie", "A=1; Path=/;Expires=asdfsadgads"), // invalid Expires
new HttpHeaderData("Set-Cookie", "B=2; Path=/"),
new HttpHeaderData("Set-Cookie", "C=3; Path=/")
},
s_simpleContent);
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
Assert.Equal(2, collection.Count);
// Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie>
Cookie[] cookies = new Cookie[3];
collection.CopyTo(cookies, 0);
Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2");
Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3");
}
});
}
[Fact]
public async Task GetAsyncWithRedirect_ReceiveSetCookie_CookieSent()
{
const string path1 = "/foo";
const string path2 = "/bar";
await LoopbackServerFactory.CreateClientAndServerAsync(async url =>
{
Uri url1 = new Uri(url, path1);
HttpClientHandler handler = CreateHttpClientHandler();
using (HttpClient client = CreateHttpClient(handler))
{
client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling
await client.GetAsync(url1);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
Assert.Equal(2, collection.Count);
// Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie>
Cookie[] cookies = new Cookie[2];
collection.CopyTo(cookies, 0);
Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1");
Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2");
}
},
async server =>
{
HttpRequestData requestData1 = await server.HandleRequestAsync(
HttpStatusCode.Found,
new HttpHeaderData[]
{
new HttpHeaderData("Location", $"{path2}"),
new HttpHeaderData("Set-Cookie", "A=1; Path=/")
});
Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie"));
HttpRequestData requestData2 = await server.HandleRequestAsync(
HttpStatusCode.OK,
new HttpHeaderData[]
{
new HttpHeaderData("Set-Cookie", "B=2; Path=/")
},
s_simpleContent);
Assert.Equal("A=1", requestData2.GetSingleHeaderValue("Cookie"));
});
}
[Fact]
public async Task GetAsyncWithBasicAuth_ReceiveSetCookie_CookieSent()
{
if (IsWinHttpHandler)
{
// Issue #26986
// WinHttpHandler does not process the cookie.
return;
}
await LoopbackServerFactory.CreateClientAndServerAsync(async url =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = new NetworkCredential("user", "pass");
using (HttpClient client = CreateHttpClient(handler))
{
await client.GetAsync(url);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
Assert.Equal(2, collection.Count);
// Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie>
Cookie[] cookies = new Cookie[2];
collection.CopyTo(cookies, 0);
Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1");
Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2");
}
},
async server =>
{
HttpRequestData requestData1 = await server.HandleRequestAsync(
HttpStatusCode.Unauthorized,
new HttpHeaderData[]
{
new HttpHeaderData("WWW-Authenticate", "Basic realm=\"WallyWorld\""),
new HttpHeaderData("Set-Cookie", "A=1; Path=/")
});
Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie"));
HttpRequestData requestData2 = await server.HandleRequestAsync(
HttpStatusCode.OK,
new HttpHeaderData[]
{
new HttpHeaderData("Set-Cookie", "B=2; Path=/")
},
s_simpleContent);
Assert.Equal("A=1", requestData2.GetSingleHeaderValue("Cookie"));
});
}
//
// MemberData stuff
//
private static string GenerateCookie(string name, char repeat, int overallHeaderValueLength)
{
string emptyHeaderValue = $"{name}=; Path=/";
Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length);
int valueCount = overallHeaderValueLength - emptyHeaderValue.Length;
return new string(repeat, valueCount);
}
public static IEnumerable<object[]> CookieNamesValuesAndUseCookies()
{
foreach (bool useCookies in new[] { true, false })
{
yield return new object[] { "ABC", "123", useCookies };
yield return new object[] { "Hello", "World", useCookies };
yield return new object[] { "foo", "bar", useCookies };
yield return new object[] { "Hello World", "value", useCookies };
yield return new object[] { ".AspNetCore.Session", "RAExEmXpoCbueP_QYM", useCookies };
yield return new object[]
{
".AspNetCore.Antiforgery.Xam7_OeLcN4",
"CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM",
useCookies
};
// WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values,
// using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders
// returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer.
// Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the
// iteration index, which would cause header values to be missed if not handled correctly.
//
// In particular, WinHttpQueryHeader behaves as follows for the following header value lengths:
// * 0-127 chars: succeeds, index advances from 0 to 1.
// * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1.
// * 256+ chars: fails due to insufficient buffer, index stays at 0.
//
// The below overall header value lengths were chosen to exercise reading header values at these
// edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers.
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126), useCookies };
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127), useCookies };
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128), useCookies };
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129), useCookies };
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254), useCookies };
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255), useCookies };
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256), useCookies };
yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257), useCookies };
}
}
}
public abstract class HttpClientHandlerTest_Cookies_Http11 : HttpClientHandlerTestBase
{
public HttpClientHandlerTest_Cookies_Http11(ITestOutputHelper output) : base(output) { }
[Fact]
public async Task GetAsync_ReceiveMultipleSetCookieHeaders_CookieAdded()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
using (HttpClient client = CreateHttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(
HttpStatusCode.OK,
$"Set-Cookie: A=1; Path=/\r\n" +
$"Set-Cookie : B=2; Path=/\r\n" + // space before colon to verify header is trimmed and recognized
$"Set-Cookie: C=3; Path=/\r\n",
"Hello world!");
await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask);
CookieCollection collection = handler.CookieContainer.GetCookies(url);
Assert.Equal(3, collection.Count);
// Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie>
Cookie[] cookies = new Cookie[3];
collection.CopyTo(cookies, 0);
Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1");
Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2");
Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3");
}
});
}
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct Int32 : IComparable, IConvertible, IFormattable, IComparable<int>, IEquatable<int>, ISpanFormattable
{
private readonly int m_value; // Do not rename (binary serialization)
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns :
// 0 if the values are equal
// Negative number if _value is less than value
// Positive number if _value is more than value
// null is considered to be less than any instance, hence returns positive number
// If object is not of type Int32, this method throws an ArgumentException.
//
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (value is int)
{
// NOTE: Cannot use return (_value - value) as this causes a wrap
// around in cases where _value - value > MaxValue.
int i = (int)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeInt32);
}
public int CompareTo(int value)
{
// NOTE: Cannot use return (_value - value) as this causes a wrap
// around in cases where _value - value > MaxValue.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(object obj)
{
if (!(obj is int))
{
return false;
}
return m_value == ((int)obj).m_value;
}
[NonVersionable]
public bool Equals(int obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return m_value;
}
public override string ToString()
{
return Number.FormatInt32(m_value, null, null);
}
public string ToString(string format)
{
return Number.FormatInt32(m_value, format, null);
}
public string ToString(IFormatProvider provider)
{
return Number.FormatInt32(m_value, null, provider);
}
public string ToString(string format, IFormatProvider provider)
{
return Number.FormatInt32(m_value, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten);
}
public static int Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static int Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
public static int Parse(string s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
public static int Parse(string s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String. Returns false rather
// than throwing exceptin if input is invalid
//
public static bool TryParse(string s, out int result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
public static bool TryParse(ReadOnlySpan<char> s, out int result)
{
return Number.TryParseInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
// Parses an integer from a String in the given style. Returns false rather
// than throwing exceptin if input is invalid
//
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out int result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Int32;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return m_value;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// 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.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
/// <summary>
/// Static class containing the WinHttp global callback and associated routines.
/// </summary>
internal static class WinHttpRequestCallback
{
public static Interop.WinHttp.WINHTTP_STATUS_CALLBACK StaticCallbackDelegate =
new Interop.WinHttp.WINHTTP_STATUS_CALLBACK(WinHttpCallback);
public static void WinHttpCallback(
IntPtr handle,
IntPtr context,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
WinHttpTraceHelper.TraceCallbackStatus("WinHttpCallback", handle, context, internetStatus);
if (Environment.HasShutdownStarted)
{
WinHttpTraceHelper.Trace("WinHttpCallback: Environment.HasShutdownStarted returned True");
return;
}
if (context == IntPtr.Zero)
{
return;
}
WinHttpRequestState state = WinHttpRequestState.FromIntPtr(context);
Debug.Assert(state != null, "WinHttpCallback must have a non-null state object");
RequestCallback(handle, state, internetStatus, statusInformation, statusInformationLength);
}
private static void RequestCallback(
IntPtr handle,
WinHttpRequestState state,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
try
{
switch (internetStatus)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
OnRequestHandleClosing(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
OnRequestSendRequestComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
Debug.Assert(statusInformationLength == sizeof(int));
int bytesAvailable = Marshal.ReadInt32(statusInformation);
OnRequestDataAvailable(state, bytesAvailable);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
OnRequestReadComplete(state, statusInformationLength);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
OnRequestWriteComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
OnRequestReceiveResponseHeadersComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT:
string redirectUriString = Marshal.PtrToStringUni(statusInformation);
var redirectUri = new Uri(redirectUriString);
OnRequestRedirect(state, redirectUri);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
OnRequestSendingRequest(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
Debug.Assert(
statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(),
"RequestCallback: statusInformationLength=" + statusInformationLength +
" must be sizeof(WINHTTP_ASYNC_RESULT)=" + Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>());
var asyncResult = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(statusInformation);
OnRequestError(state, asyncResult);
return;
default:
return;
}
}
catch (Exception ex)
{
Interop.WinHttp.WinHttpCloseHandle(handle);
state.SavedException = ex;
}
}
private static void OnRequestHandleClosing(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null");
// This is the last notification callback that WinHTTP will send. Therefore, we can
// now explicitly dispose the state object which will free its corresponding GCHandle.
// This will then allow the state object to be garbage collected.
state.Dispose();
}
private static void OnRequestSendRequestComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null");
Debug.Assert(state.LifecycleAwaitable != null, "OnRequestSendRequestComplete: LifecycleAwaitable is null");
state.LifecycleAwaitable.SetResult(1);
}
private static void OnRequestDataAvailable(WinHttpRequestState state, int bytesAvailable)
{
Debug.Assert(state != null, "OnRequestDataAvailable: state is null");
state.LifecycleAwaitable.SetResult(bytesAvailable);
}
private static void OnRequestReadComplete(WinHttpRequestState state, uint bytesRead)
{
Debug.Assert(state != null, "OnRequestReadComplete: state is null");
// If we read to the end of the stream and we're using 'Content-Length' semantics on the response body,
// then verify we read at least the number of bytes required.
if (bytesRead == 0
&& state.ExpectedBytesToRead.HasValue
&& state.CurrentBytesRead < state.ExpectedBytesToRead.Value)
{
state.LifecycleAwaitable.SetException(new IOException(string.Format(
SR.net_http_io_read_incomplete,
state.ExpectedBytesToRead.Value,
state.CurrentBytesRead)));
}
else
{
state.CurrentBytesRead += (long)bytesRead;
state.LifecycleAwaitable.SetResult((int)bytesRead);
}
}
private static void OnRequestWriteComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestWriteComplete: state is null");
Debug.Assert(state.TcsInternalWriteDataToRequestStream != null, "TcsInternalWriteDataToRequestStream is null");
Debug.Assert(!state.TcsInternalWriteDataToRequestStream.Task.IsCompleted, "TcsInternalWriteDataToRequestStream.Task is completed");
state.TcsInternalWriteDataToRequestStream.TrySetResult(true);
}
private static void OnRequestReceiveResponseHeadersComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestReceiveResponseHeadersComplete: state is null");
Debug.Assert(state.LifecycleAwaitable != null, "LifecycleAwaitable is null");
state.LifecycleAwaitable.SetResult(1);
}
private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri)
{
Debug.Assert(state != null, "OnRequestRedirect: state is null");
Debug.Assert(redirectUri != null, "OnRequestRedirect: redirectUri is null");
// If we're manually handling cookies, we need to reset them based on the new URI.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
// Add any cookies that may have arrived with redirect response.
WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state);
// Reset cookie request headers based on redirectUri.
WinHttpCookieContainerAdapter.ResetCookieRequestHeaders(state, redirectUri);
}
state.RequestMessage.RequestUri = redirectUri;
// Redirection to a new uri may require a new connection through a potentially different proxy.
// If so, we will need to respond to additional 407 proxy auth demands and re-attach any
// proxy credentials. The ProcessResponse() method looks at the state.LastStatusCode
// before attaching proxy credentials and marking the HTTP request to be re-submitted.
// So we need to reset the LastStatusCode remembered. Otherwise, it will see additional 407
// responses as an indication that proxy auth failed and won't retry the HTTP request.
if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
state.LastStatusCode = 0;
}
// For security reasons, we drop the server credential if it is a
// NetworkCredential. But we allow credentials in a CredentialCache
// since they are specifically tied to URI's.
if (!(state.ServerCredentials is CredentialCache))
{
state.ServerCredentials = null;
}
}
private static void OnRequestSendingRequest(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendingRequest: state is null");
Debug.Assert(state.RequestHandle != null, "OnRequestSendingRequest: state.RequestHandle is null");
if (state.RequestMessage.RequestUri.Scheme != UriScheme.Https)
{
// Not SSL/TLS.
return;
}
// Grab the channel binding token (CBT) information from the request handle and put it into
// the TransportContext object.
state.TransportContext.SetChannelBinding(state.RequestHandle);
if (state.ServerCertificateValidationCallback != null)
{
IntPtr certHandle = IntPtr.Zero;
uint certHandleSize = (uint)IntPtr.Size;
if (!Interop.WinHttp.WinHttpQueryOption(
state.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_SERVER_CERT_CONTEXT,
ref certHandle,
ref certHandleSize))
{
int lastError = Marshal.GetLastWin32Error();
WinHttpTraceHelper.Trace(
"OnRequestSendingRequest: Error getting WINHTTP_OPTION_SERVER_CERT_CONTEXT, {0}",
lastError);
if (lastError == Interop.WinHttp.ERROR_WINHTTP_INCORRECT_HANDLE_STATE)
{
// Not yet an SSL/TLS connection. This occurs while connecting thru a proxy where the
// CONNECT verb hasn't yet been processed due to the proxy requiring authentication.
// We need to ignore this notification. Another notification will be sent once the final
// connection thru the proxy is completed.
return;
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
// Create a managed wrapper around the certificate handle. Since this results in duplicating
// the handle, we will close the original handle after creating the wrapper.
var serverCertificate = new X509Certificate2(certHandle);
Interop.Crypt32.CertFreeCertificateContext(certHandle);
X509Chain chain = null;
SslPolicyErrors sslPolicyErrors;
try
{
WinHttpCertificateHelper.BuildChain(
serverCertificate,
state.RequestMessage.RequestUri.Host,
state.CheckCertificateRevocationList,
out chain,
out sslPolicyErrors);
bool result = state.ServerCertificateValidationCallback(
state.RequestMessage,
serverCertificate,
chain,
sslPolicyErrors);
if (!result)
{
throw WinHttpException.CreateExceptionUsingError(
(int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE);
}
}
finally
{
if (chain != null)
{
chain.Dispose();
}
serverCertificate.Dispose();
}
}
}
private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult)
{
WinHttpTraceHelper.TraceAsyncError("OnRequestError", asyncResult);
Debug.Assert(state != null, "OnRequestError: state is null");
Debug.Assert((unchecked((int)asyncResult.dwError) != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER &&
unchecked((int)asyncResult.dwError) != unchecked((int)0x80090321)), // SEC_E_BUFFER_TOO_SMALL
$"Unexpected async error in WinHttpRequestCallback: {unchecked((int)asyncResult.dwError)}, WinHttp API: {unchecked((uint)asyncResult.dwResult.ToInt32())}");
Exception innerException = WinHttpException.CreateExceptionUsingError(unchecked((int)asyncResult.dwError));
switch (unchecked((uint)asyncResult.dwResult.ToInt32()))
{
case Interop.WinHttp.API_SEND_REQUEST:
state.LifecycleAwaitable.SetException(innerException);
break;
case Interop.WinHttp.API_RECEIVE_RESPONSE:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST)
{
state.RetryRequest = true;
state.LifecycleAwaitable.SetResult(0);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED)
{
// WinHttp will automatically drop any client SSL certificates that we
// have pre-set into the request handle including the NULL certificate
// (which means we have no certs to send). For security reasons, we don't
// allow the certificate to be re-applied. But we need to tell WinHttp
// explicitly that we don't have any certificate to send.
Debug.Assert(state.RequestHandle != null, "OnRequestError: state.RequestHandle is null");
WinHttpHandler.SetNoClientCertificate(state.RequestHandle);
state.RetryRequest = true;
state.LifecycleAwaitable.SetResult(0);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
state.LifecycleAwaitable.SetCanceled(state.CancellationToken);
}
else
{
state.LifecycleAwaitable.SetException(innerException);
}
break;
case Interop.WinHttp.API_QUERY_DATA_AVAILABLE:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
Debug.WriteLine("RequestCallback: QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED");
state.LifecycleAwaitable.SetCanceled();
}
else
{
state.LifecycleAwaitable.SetException(
new IOException(SR.net_http_io_read, innerException));
}
break;
case Interop.WinHttp.API_READ_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
Debug.WriteLine("RequestCallback: API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.LifecycleAwaitable.SetCanceled();
}
else
{
state.LifecycleAwaitable.SetException(new IOException(SR.net_http_io_read, innerException));
}
break;
case Interop.WinHttp.API_WRITE_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's WriteAsync() call into the TrySetCanceled().
Debug.WriteLine("RequestCallback: API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.TcsInternalWriteDataToRequestStream.TrySetCanceled();
}
else
{
state.TcsInternalWriteDataToRequestStream.TrySetException(
new IOException(SR.net_http_io_write, innerException));
}
break;
default:
Debug.Fail(
"OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.",
"Error code: " + asyncResult.dwError + " (" + innerException.Message + ")");
break;
}
}
}
}
| |
// 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;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Threading.Tasks.Tests
{
public class TaskFactoryTests
{
#region Test Methods
// Exercise functionality of TaskFactory and TaskFactory<TResult>
[Fact]
public static void RunTaskFactoryTests()
{
TaskScheduler tm = TaskScheduler.Default;
TaskCreationOptions tco = TaskCreationOptions.LongRunning;
TaskFactory tf;
TaskFactory<int> tfi;
tf = new TaskFactory();
ExerciseTaskFactory(tf, TaskScheduler.Current, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None);
CancellationTokenSource cancellationSrc = new CancellationTokenSource();
tf = new TaskFactory(cancellationSrc.Token);
var task = tf.StartNew(() => { });
task.Wait();
// Exercising TF(scheduler)
tf = new TaskFactory(tm);
ExerciseTaskFactory(tf, tm, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None);
//Exercising TF(TCrO, TCoO)
tf = new TaskFactory(tco, TaskContinuationOptions.None);
ExerciseTaskFactory(tf, TaskScheduler.Current, tco, CancellationToken.None, TaskContinuationOptions.None);
// Exercising TF(scheduler, TCrO, TCoO)"
tf = new TaskFactory(CancellationToken.None, tco, TaskContinuationOptions.None, tm);
ExerciseTaskFactory(tf, tm, tco, CancellationToken.None, TaskContinuationOptions.None);
//TaskFactory<TResult> tests
// Exercising TF<int>()
tfi = new TaskFactory<int>();
ExerciseTaskFactoryInt(tfi, TaskScheduler.Current, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None);
//Test constructor that accepts cancellationToken
// Exercising TF<int>(cancellationToken) with a noncancelled token
cancellationSrc = new CancellationTokenSource();
tfi = new TaskFactory<int>(cancellationSrc.Token);
task = tfi.StartNew(() => 0);
task.Wait();
// Exercising TF<int>(scheduler)
tfi = new TaskFactory<int>(tm);
ExerciseTaskFactoryInt(tfi, tm, TaskCreationOptions.None, CancellationToken.None, TaskContinuationOptions.None);
// Exercising TF<int>(TCrO, TCoO)
tfi = new TaskFactory<int>(tco, TaskContinuationOptions.None);
ExerciseTaskFactoryInt(tfi, TaskScheduler.Current, tco, CancellationToken.None, TaskContinuationOptions.None);
// Exercising TF<int>(scheduler, TCrO, TCoO)
tfi = new TaskFactory<int>(CancellationToken.None, tco, TaskContinuationOptions.None, tm);
ExerciseTaskFactoryInt(tfi, tm, tco, CancellationToken.None, TaskContinuationOptions.None);
}
// Exercise functionality of TaskFactory and TaskFactory<TResult>
[Fact]
public static void RunTaskFactoryTests_Cancellation_Negative()
{
CancellationTokenSource cancellationSrc = new CancellationTokenSource();
//Test constructor that accepts cancellationToken
cancellationSrc.Cancel();
TaskFactory tf = new TaskFactory(cancellationSrc.Token);
var cancelledTask = tf.StartNew(() => { });
EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait());
// Exercising TF<int>(cancellationToken) with a cancelled token
cancellationSrc.Cancel();
TaskFactory<int> tfi = new TaskFactory<int>(cancellationSrc.Token);
cancelledTask = tfi.StartNew(() => 0);
EnsureTaskCanceledExceptionThrown(() => cancelledTask.Wait());
}
[Fact]
public static void RunTaskFactoryExceptionTests()
{
TaskFactory tf = new TaskFactory();
// Checking top-level TF exception handling.
Assert.Throws<ArgumentOutOfRangeException>(
() => tf = new TaskFactory((TaskCreationOptions)0x40000000, TaskContinuationOptions.None));
Assert.Throws<ArgumentOutOfRangeException>(
() => tf = new TaskFactory((TaskCreationOptions)0x100, TaskContinuationOptions.None));
Assert.Throws<ArgumentOutOfRangeException>(
() => tf = new TaskFactory(TaskCreationOptions.None, (TaskContinuationOptions)0x40000000));
Assert.Throws<ArgumentOutOfRangeException>(
() => tf = new TaskFactory(TaskCreationOptions.None, TaskContinuationOptions.NotOnFaulted));
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync(null, (obj) => { }, TaskCreationOptions.None));
// testing exceptions in null endMethods
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<int>(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<int>(new myAsyncResult((obj) => { }, null), null, TaskCreationOptions.None, null));
TaskFactory<int> tfi = new TaskFactory<int>();
// Checking top-level TF<int> exception handling.
Assert.Throws<ArgumentOutOfRangeException>(
() => tfi = new TaskFactory<int>((TaskCreationOptions)0x40000000, TaskContinuationOptions.None));
Assert.Throws<ArgumentOutOfRangeException>(
() => tfi = new TaskFactory<int>((TaskCreationOptions)0x100, TaskContinuationOptions.None));
Assert.Throws<ArgumentOutOfRangeException>(
() => tfi = new TaskFactory<int>(TaskCreationOptions.None, (TaskContinuationOptions)0x40000000));
Assert.Throws<ArgumentOutOfRangeException>(
() => tfi = new TaskFactory<int>(TaskCreationOptions.None, TaskContinuationOptions.NotOnFaulted));
}
[Fact]
public static void RunTaskFactoryFromAsyncExceptionTests()
{
// Checking TF special FromAsync exception handling."
FakeAsyncClass fac = new FakeAsyncClass();
TaskFactory tf;
tf = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => tf.FromAsync(fac.StartWrite, fac.EndWrite, null /* state */));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", null /* state */));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", 2, null /* state */));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(
() => tf.FromAsync(fac.StartWrite, fac.EndWrite, "abc", 0, 2, null /* state */));
// testing exceptions in null endMethods or begin method
//0 parameter
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string>(fac.StartWrite, null, (Object)null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string>(null, fac.EndRead, (Object)null, TaskCreationOptions.None));
//1 parameter
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string, int>(fac.StartWrite, null, "arg1", (Object)null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string, string>(null, fac.EndRead, "arg1", (Object)null, TaskCreationOptions.None));
//2 parameters
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string, int, int>(fac.StartWrite, null, "arg1", 1, (Object)null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string, string, string>(null, fac.EndRead, "arg1", "arg2", (Object)null, TaskCreationOptions.None));
//3 parameters
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string, int, int, int>(fac.StartWrite, null, "arg1", 1, 2, (Object)null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tf.FromAsync<string, string, string, string>(null, fac.EndRead, "arg1", "arg2", "arg3", (Object)null, TaskCreationOptions.None));
// Checking TF<string> special FromAsync exception handling.
TaskFactory<string> tfs = new TaskFactory<string>(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
char[] charbuf = new char[128];
// Test that we throw on bad default task options
Assert.Throws<ArgumentOutOfRangeException>(
() => { tfs.FromAsync(fac.StartRead, fac.EndRead, null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, charbuf, null); });
Assert.Throws<ArgumentOutOfRangeException>(
() => { tfs.FromAsync(fac.StartRead, fac.EndRead, 64, charbuf, 0, null); });
// Test that we throw on null endMethod
Assert.Throws<ArgumentNullException>(
() => { tfs.FromAsync(fac.StartRead, null, null); });
Assert.Throws<ArgumentNullException>(
() => { tfs.FromAsync(fac.StartRead, null, 64, null); });
Assert.Throws<ArgumentNullException>(
() => { tfs.FromAsync(fac.StartRead, null, 64, charbuf, null); });
Assert.Throws<ArgumentNullException>(
() => { tfs.FromAsync(fac.StartRead, null, 64, charbuf, 0, null); });
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync(null, (obj) => "", TaskCreationOptions.None));
//test null begin or end methods with various overloads
//0 parameter
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync(fac.StartWrite, null, null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync(null, fac.EndRead, null, TaskCreationOptions.None));
//1 parameter
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync<string>(fac.StartWrite, null, "arg1", null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync<string>(null, fac.EndRead, "arg1", null, TaskCreationOptions.None));
//2 parameters
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync<string, int>(fac.StartWrite, null, "arg1", 2, null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync<string, int>(null, fac.EndRead, "arg1", 2, null, TaskCreationOptions.None));
//3 parameters
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync<string, int, int>(fac.StartWrite, null, "arg1", 2, 3, null, TaskCreationOptions.None));
Assert.ThrowsAsync<ArgumentNullException>(
() => tfs.FromAsync<string, int, int>(null, fac.EndRead, "arg1", 2, 3, null, TaskCreationOptions.None));
}
#endregion
#region Helper Methods
// Utility method for RunTaskFactoryTests().
private static void ExerciseTaskFactory(TaskFactory tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault)
{
TaskScheduler myTM = TaskScheduler.Default;
TaskCreationOptions myTCO = TaskCreationOptions.LongRunning;
TaskScheduler tmObserved = null;
Task t;
Task<int> f;
//
// Helper delegates to make the code below a lot shorter
//
Action init = delegate { tmObserved = null; };
Action void_delegate = delegate
{
tmObserved = TaskScheduler.Current;
};
Action<object> voidState_delegate = delegate (object o)
{
tmObserved = TaskScheduler.Current;
};
Func<int> int_delegate = delegate
{
tmObserved = TaskScheduler.Current;
return 10;
};
Func<object, int> intState_delegate = delegate (object o)
{
tmObserved = TaskScheduler.Current;
return 10;
};
//check Factory properties
Assert.Equal(tf.CreationOptions, tcoDefault);
if (tf.Scheduler != null)
{
Assert.Equal(tmDefault, tf.Scheduler);
}
Assert.Equal(tokenDefault, tf.CancellationToken);
Assert.Equal(continuationDefault, tf.ContinuationOptions);
//
// StartNew(action)
//
init();
t = tf.StartNew(void_delegate);
t.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(t.CreationOptions, tcoDefault);
//
// StartNew(action, TCO)
//
init();
t = tf.StartNew(void_delegate, myTCO);
t.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(t.CreationOptions, myTCO);
//
// StartNew(action, CT, TCO, scheduler)
//
init();
t = tf.StartNew(void_delegate, CancellationToken.None, myTCO, myTM);
t.Wait();
Assert.Equal(tmObserved, myTM);
Assert.Equal(t.CreationOptions, myTCO);
//
// StartNew(action<object>, object)
//
init();
t = tf.StartNew(voidState_delegate, 100);
t.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(t.CreationOptions, tcoDefault);
//
// StartNew(action<object>, object, TCO)
//
init();
t = tf.StartNew(voidState_delegate, 100, myTCO);
t.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(t.CreationOptions, myTCO);
//
// StartNew(action<object>, object, CT, TCO, scheduler)
//
init();
t = tf.StartNew(voidState_delegate, 100, CancellationToken.None, myTCO, myTM);
t.Wait();
Assert.Equal(tmObserved, myTM);
Assert.Equal(t.CreationOptions, myTCO);
//
// StartNew(func)
//
init();
f = tf.StartNew(int_delegate);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, tcoDefault);
//
// StartNew(func, token)
//
init();
f = tf.StartNew(int_delegate, tokenDefault);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, tcoDefault);
//
// StartNew(func, options)
//
init();
f = tf.StartNew(int_delegate, myTCO);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, myTCO);
//
// StartNew(func, CT, options, scheduler)
//
init();
f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM);
f.Wait();
Assert.Equal(tmObserved, myTM);
Assert.Equal(f.CreationOptions, myTCO);
//
// StartNew(func<object>, object)
//
init();
f = tf.StartNew(intState_delegate, 100);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, tcoDefault);
//
// StartNew(func<object>, object, token)
//
init();
f = tf.StartNew(intState_delegate, 100, tokenDefault);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, tcoDefault);
//
// StartNew(func<object>, object, options)
//
init();
f = tf.StartNew(intState_delegate, 100, myTCO);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, myTCO);
//
// StartNew(func<object>, object, CT, options, scheduler)
//
init();
f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM);
f.Wait();
Assert.Equal(tmObserved, myTM);
Assert.Equal(f.CreationOptions, myTCO);
}
// Utility method for RunTaskFactoryTests().
private static void ExerciseTaskFactoryInt(TaskFactory<int> tf, TaskScheduler tmDefault, TaskCreationOptions tcoDefault, CancellationToken tokenDefault, TaskContinuationOptions continuationDefault)
{
TaskScheduler myTM = TaskScheduler.Default;
TaskCreationOptions myTCO = TaskCreationOptions.LongRunning;
TaskScheduler tmObserved = null;
Task<int> f;
// Helper delegates to make the code shorter.
Action init = delegate { tmObserved = null; };
Func<int> int_delegate = delegate
{
tmObserved = TaskScheduler.Current;
return 10;
};
Func<object, int> intState_delegate = delegate (object o)
{
tmObserved = TaskScheduler.Current;
return 10;
};
//check Factory properties
Assert.Equal(tf.CreationOptions, tcoDefault);
if (tf.Scheduler != null)
{
Assert.Equal(tmDefault, tf.Scheduler);
}
Assert.Equal(tokenDefault, tf.CancellationToken);
Assert.Equal(continuationDefault, tf.ContinuationOptions);
//
// StartNew(func)
//
init();
f = tf.StartNew(int_delegate);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, tcoDefault);
//
// StartNew(func, options)
//
init();
f = tf.StartNew(int_delegate, myTCO);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, myTCO);
//
// StartNew(func, CT, options, scheduler)
//
init();
f = tf.StartNew(int_delegate, CancellationToken.None, myTCO, myTM);
f.Wait();
Assert.Equal(tmObserved, myTM);
Assert.Equal(f.CreationOptions, myTCO);
//
// StartNew(func<object>, object)
//
init();
f = tf.StartNew(intState_delegate, 100);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, tcoDefault);
//
// StartNew(func<object>, object, token)
//
init();
f = tf.StartNew(intState_delegate, 100, tokenDefault);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, tcoDefault);
//
// StartNew(func<object>, object, options)
//
init();
f = tf.StartNew(intState_delegate, 100, myTCO);
f.Wait();
Assert.Equal(tmObserved, tmDefault);
Assert.Equal(f.CreationOptions, myTCO);
//
// StartNew(func<object>, object, CT, options, scheduler)
//
init();
f = tf.StartNew(intState_delegate, 100, CancellationToken.None, myTCO, myTM);
f.Wait();
Assert.Equal(tmObserved, myTM);
Assert.Equal(f.CreationOptions, myTCO);
}
// Ensures that the specified action throws a AggregateException wrapping a TaskCanceledException
private static void EnsureTaskCanceledExceptionThrown(Action action)
{
AggregateException ae = Assert.Throws<AggregateException>(action);
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
}
// This class is used in testing Factory tests.
private class FakeAsyncClass
{
private List<char> _list = new List<char>();
public override string ToString()
{
StringBuilder sb = new StringBuilder();
lock (_list)
{
for (int i = 0; i < _list.Count; i++) sb.Append(_list[i]);
}
return sb.ToString();
}
// Silly use of Write, but I wanted to test no-argument StartXXX handling.
public IAsyncResult StartWrite(AsyncCallback cb, object o)
{
return StartWrite("", 0, 0, cb, o);
}
public IAsyncResult StartWrite(string s, AsyncCallback cb, object o)
{
return StartWrite(s, 0, s.Length, cb, o);
}
public IAsyncResult StartWrite(string s, int length, AsyncCallback cb, object o)
{
return StartWrite(s, 0, length, cb, o);
}
public IAsyncResult StartWrite(string s, int offset, int length, AsyncCallback cb, object o)
{
myAsyncResult mar = new myAsyncResult(cb, o);
// Allow for exception throwing to test our handling of that.
if (s == null) throw new ArgumentNullException(nameof(s));
Task t = Task.Factory.StartNew(delegate
{
try
{
lock (_list)
{
for (int i = 0; i < length; i++) _list.Add(s[i + offset]);
}
mar.Signal();
}
catch (Exception e) { mar.Signal(e); }
});
return mar;
}
public void EndWrite(IAsyncResult iar)
{
myAsyncResult mar = iar as myAsyncResult;
mar.Wait();
if (mar.IsFaulted) throw (mar.Exception);
}
public IAsyncResult StartRead(AsyncCallback cb, object o)
{
return StartRead(128 /*=maxbytes*/, null, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, AsyncCallback cb, object o)
{
return StartRead(maxBytes, null, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, char[] buf, AsyncCallback cb, object o)
{
return StartRead(maxBytes, buf, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, char[] buf, int offset, AsyncCallback cb, object o)
{
myAsyncResult mar = new myAsyncResult(cb, o);
// Allow for exception throwing to test our handling of that.
if (maxBytes == -1) throw new ArgumentException(nameof(maxBytes));
Task t = Task.Factory.StartNew(delegate
{
StringBuilder sb = new StringBuilder();
int bytesRead = 0;
try
{
lock (_list)
{
while ((_list.Count > 0) && (bytesRead < maxBytes))
{
sb.Append(_list[0]);
if (buf != null) { buf[offset] = _list[0]; offset++; }
_list.RemoveAt(0);
bytesRead++;
}
}
mar.SignalState(sb.ToString());
}
catch (Exception e) { mar.Signal(e); }
});
return mar;
}
public string EndRead(IAsyncResult iar)
{
myAsyncResult mar = iar as myAsyncResult;
if (mar.IsFaulted) throw (mar.Exception);
return (string)mar.AsyncState;
}
public void ResetStateTo(string s)
{
_list.Clear();
for (int i = 0; i < s.Length; i++) _list.Add(s[i]);
}
}
// This is an internal class used for a concrete IAsyncResult in the APM Factory tests.
private class myAsyncResult : IAsyncResult
{
private volatile int _isCompleted;
private ManualResetEvent _asyncWaitHandle;
private AsyncCallback _callback;
private object _asyncState;
private Exception _exception;
public myAsyncResult(AsyncCallback cb, object o)
{
_isCompleted = 0;
_asyncWaitHandle = new ManualResetEvent(false);
_callback = cb;
_asyncState = o;
_exception = null;
}
public bool IsCompleted
{
get { return (_isCompleted == 1); }
}
public bool CompletedSynchronously
{
get { return false; }
}
public WaitHandle AsyncWaitHandle
{
get { return _asyncWaitHandle; }
}
public object AsyncState
{
get { return _asyncState; }
}
public void Signal()
{
_isCompleted = 1;
_asyncWaitHandle.Set();
if (_callback != null) _callback(this);
}
public void Signal(Exception e)
{
_exception = e;
Signal();
}
public void SignalState(object o)
{
_asyncState = o;
Signal();
}
public void Wait()
{
_asyncWaitHandle.WaitOne();
if (_exception != null) throw (_exception);
}
public bool IsFaulted
{
get { return ((_isCompleted == 1) && (_exception != null)); }
}
public Exception Exception
{
get { return _exception; }
}
}
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Microsoft.Xrm.Sdk;
namespace PowerShellLibrary.Crm.CmdletProviders
{
[Microsoft.Xrm.Sdk.Client.EntityLogicalName("sdkmessage")]
[GeneratedCode("CrmSvcUtil", "7.1.0001.3108")]
[DataContract]
public class SdkMessage : Entity, INotifyPropertyChanging, INotifyPropertyChanged
{
public const string EntityLogicalName = "sdkmessage";
public const int EntityTypeCode = 4606;
[AttributeLogicalName("autotransact")]
public bool? AutoTransact
{
get
{
return this.GetAttributeValue<bool?>("autotransact");
}
set
{
this.OnPropertyChanging("AutoTransact");
this.SetAttributeValue("autotransact", (object) value);
this.OnPropertyChanged("AutoTransact");
}
}
[AttributeLogicalName("availability")]
public int? Availability
{
get
{
return this.GetAttributeValue<int?>("availability");
}
set
{
this.OnPropertyChanging("Availability");
this.SetAttributeValue("availability", (object) value);
this.OnPropertyChanged("Availability");
}
}
[AttributeLogicalName("categoryname")]
public string CategoryName
{
get
{
return this.GetAttributeValue<string>("categoryname");
}
set
{
this.OnPropertyChanging("CategoryName");
this.SetAttributeValue("categoryname", (object) value);
this.OnPropertyChanged("CategoryName");
}
}
[AttributeLogicalName("createdby")]
public EntityReference CreatedBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdby");
}
}
[AttributeLogicalName("createdon")]
public DateTime? CreatedOn
{
get
{
return this.GetAttributeValue<DateTime?>("createdon");
}
}
[AttributeLogicalName("createdonbehalfby")]
public EntityReference CreatedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdonbehalfby");
}
}
[AttributeLogicalName("customizationlevel")]
public int? CustomizationLevel
{
get
{
return this.GetAttributeValue<int?>("customizationlevel");
}
}
[AttributeLogicalName("expand")]
public bool? Expand
{
get
{
return this.GetAttributeValue<bool?>("expand");
}
set
{
this.OnPropertyChanging("Expand");
this.SetAttributeValue("expand", (object) value);
this.OnPropertyChanged("Expand");
}
}
[AttributeLogicalName("isactive")]
public bool? IsActive
{
get
{
return this.GetAttributeValue<bool?>("isactive");
}
set
{
this.OnPropertyChanging("IsActive");
this.SetAttributeValue("isactive", (object) value);
this.OnPropertyChanged("IsActive");
}
}
[AttributeLogicalName("isprivate")]
public bool? IsPrivate
{
get
{
return this.GetAttributeValue<bool?>("isprivate");
}
set
{
this.OnPropertyChanging("IsPrivate");
this.SetAttributeValue("isprivate", (object) value);
this.OnPropertyChanged("IsPrivate");
}
}
[AttributeLogicalName("isreadonly")]
public bool? IsReadOnly
{
get
{
return this.GetAttributeValue<bool?>("isreadonly");
}
set
{
this.OnPropertyChanging("IsReadOnly");
this.SetAttributeValue("isreadonly", (object) value);
this.OnPropertyChanged("IsReadOnly");
}
}
[AttributeLogicalName("isvalidforexecuteasync")]
public bool? IsValidForExecuteAsync
{
get
{
return this.GetAttributeValue<bool?>("isvalidforexecuteasync");
}
}
[AttributeLogicalName("modifiedby")]
public EntityReference ModifiedBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedby");
}
}
[AttributeLogicalName("modifiedon")]
public DateTime? ModifiedOn
{
get
{
return this.GetAttributeValue<DateTime?>("modifiedon");
}
}
[AttributeLogicalName("modifiedonbehalfby")]
public EntityReference ModifiedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedonbehalfby");
}
}
[AttributeLogicalName("name")]
public string Name
{
get
{
return this.GetAttributeValue<string>("name");
}
set
{
this.OnPropertyChanging("Name");
this.SetAttributeValue("name", (object) value);
this.OnPropertyChanged("Name");
}
}
[AttributeLogicalName("organizationid")]
public EntityReference OrganizationId
{
get
{
return this.GetAttributeValue<EntityReference>("organizationid");
}
}
[AttributeLogicalName("sdkmessageid")]
public Guid? SdkMessageId
{
get
{
return this.GetAttributeValue<Guid?>("sdkmessageid");
}
set
{
this.OnPropertyChanging("SdkMessageId");
this.SetAttributeValue("sdkmessageid", (object) value);
if (value.HasValue)
base.Id = value.Value;
else
base.Id = Guid.Empty;
this.OnPropertyChanged("SdkMessageId");
}
}
[AttributeLogicalName("sdkmessageid")]
public override Guid Id
{
get
{
return base.Id;
}
set
{
this.SdkMessageId = new Guid?(value);
}
}
[AttributeLogicalName("sdkmessageidunique")]
public Guid? SdkMessageIdUnique
{
get
{
return this.GetAttributeValue<Guid?>("sdkmessageidunique");
}
}
[AttributeLogicalName("template")]
public bool? Template
{
get
{
return this.GetAttributeValue<bool?>("template");
}
set
{
this.OnPropertyChanging("Template");
this.SetAttributeValue("template", (object) value);
this.OnPropertyChanged("Template");
}
}
[AttributeLogicalName("throttlesettings")]
public string ThrottleSettings
{
get
{
return this.GetAttributeValue<string>("throttlesettings");
}
}
[AttributeLogicalName("versionnumber")]
public long? VersionNumber
{
get
{
return this.GetAttributeValue<long?>("versionnumber");
}
}
[AttributeLogicalName("workflowsdkstepenabled")]
public bool? WorkflowSdkStepEnabled
{
get
{
return this.GetAttributeValue<bool?>("workflowsdkstepenabled");
}
}
[RelationshipSchemaName("message_sdkmessagepair")]
public IEnumerable<SdkMessagePair> message_sdkmessagepair
{
get
{
return this.GetRelatedEntities<SdkMessagePair>("message_sdkmessagepair", new EntityRole?());
}
set
{
this.OnPropertyChanging("message_sdkmessagepair");
this.SetRelatedEntities<SdkMessagePair>("message_sdkmessagepair", new EntityRole?(), value);
this.OnPropertyChanged("message_sdkmessagepair");
}
}
[RelationshipSchemaName("sdkmessageid_sdkmessagefilter")]
public IEnumerable<SdkMessageFilter> sdkmessageid_sdkmessagefilter
{
get
{
return this.GetRelatedEntities<SdkMessageFilter>("sdkmessageid_sdkmessagefilter", new EntityRole?());
}
set
{
this.OnPropertyChanging("sdkmessageid_sdkmessagefilter");
this.SetRelatedEntities<SdkMessageFilter>("sdkmessageid_sdkmessagefilter", new EntityRole?(), value);
this.OnPropertyChanged("sdkmessageid_sdkmessagefilter");
}
}
[RelationshipSchemaName("sdkmessageid_sdkmessageprocessingstep")]
public IEnumerable<SdkMessageProcessingStep> sdkmessageid_sdkmessageprocessingstep
{
get
{
return this.GetRelatedEntities<SdkMessageProcessingStep>("sdkmessageid_sdkmessageprocessingstep", new EntityRole?());
}
set
{
this.OnPropertyChanging("sdkmessageid_sdkmessageprocessingstep");
this.SetRelatedEntities<SdkMessageProcessingStep>("sdkmessageid_sdkmessageprocessingstep", new EntityRole?(), value);
this.OnPropertyChanged("sdkmessageid_sdkmessageprocessingstep");
}
}
[RelationshipSchemaName("sdkmessageid_workflow_dependency")]
public IEnumerable<WorkflowDependency> sdkmessageid_workflow_dependency
{
get
{
return this.GetRelatedEntities<WorkflowDependency>("sdkmessageid_workflow_dependency", new EntityRole?());
}
set
{
this.OnPropertyChanging("sdkmessageid_workflow_dependency");
this.SetRelatedEntities<WorkflowDependency>("sdkmessageid_workflow_dependency", new EntityRole?(), value);
this.OnPropertyChanged("sdkmessageid_workflow_dependency");
}
}
[RelationshipSchemaName("createdby_sdkmessage")]
[AttributeLogicalName("createdby")]
public SystemUser createdby_sdkmessage
{
get
{
return this.GetRelatedEntity<SystemUser>("createdby_sdkmessage", new EntityRole?());
}
}
[AttributeLogicalName("createdonbehalfby")]
[RelationshipSchemaName("lk_sdkmessage_createdonbehalfby")]
public SystemUser lk_sdkmessage_createdonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_sdkmessage_createdonbehalfby", new EntityRole?());
}
}
[AttributeLogicalName("modifiedonbehalfby")]
[RelationshipSchemaName("lk_sdkmessage_modifiedonbehalfby")]
public SystemUser lk_sdkmessage_modifiedonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_sdkmessage_modifiedonbehalfby", new EntityRole?());
}
}
[AttributeLogicalName("modifiedby")]
[RelationshipSchemaName("modifiedby_sdkmessage")]
public SystemUser modifiedby_sdkmessage
{
get
{
return this.GetRelatedEntity<SystemUser>("modifiedby_sdkmessage", new EntityRole?());
}
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
public SdkMessage()
: base("sdkmessage")
{
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged == null)
return;
this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanging(string propertyName)
{
if (this.PropertyChanging == null)
return;
this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName));
}
}
}
| |
//
// Authors:
// Alan McGovern [email protected]
// Ben Motmans <[email protected]>
// Lucas Ontivero [email protected]
//
// Copyright (C) 2006 Alan McGovern
// Copyright (C) 2007 Ben Motmans
// Copyright (C) 2014 Lucas Ontivero
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Open.Nat
{
/// <summary>
/// Represents a NAT device and provides access to the operation set that allows
/// open (forward) ports, close ports and get the externa (visible) IP address.
/// </summary>
public abstract class NatDevice
{
/// <summary>
/// A local endpoint of NAT device.
/// </summary>
public abstract IPEndPoint HostEndPoint { get; }
/// <summary>
/// A local IP address of client.
/// </summary>
public abstract IPAddress LocalAddress { get; }
private readonly HashSet<Mapping> _openedMapping = new HashSet<Mapping>();
protected DateTime LastSeen { get; private set; }
internal void Touch()
{
LastSeen = DateTime.Now;
}
/// <summary>
/// Creates the port map asynchronous.
/// </summary>
/// <param name="mapping">The <see cref="Mapping">Mapping</see> entry.</param>
/// <example>
/// device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1700, 1600));
/// </example>
/// <exception cref="MappingException">MappingException</exception>
public abstract Task CreatePortMapAsync(Mapping mapping);
/// <summary>
/// Deletes a mapped port asynchronous.
/// </summary>
/// <param name="mapping">The <see cref="Mapping">Mapping</see> entry.</param>
/// <example>
/// device.DeletePortMapAsync(new Mapping(Protocol.Tcp, 1700, 1600));
/// </example>
/// <exception cref="MappingException">MappingException-class</exception>
public abstract Task DeletePortMapAsync(Mapping mapping);
/// <summary>
/// Gets all mappings asynchronous.
/// </summary>
/// <returns>
/// The list of all forwarded ports
/// </returns>
/// <example>
/// var mappings = await device.GetAllMappingsAsync();
/// foreach(var mapping in mappings)
/// {
/// Console.WriteLine(mapping)
/// }
/// </example>
/// <exception cref="MappingException">MappingException</exception>
public abstract Task<IEnumerable<Mapping>> GetAllMappingsAsync();
/// <summary>
/// Gets the external (visible) IP address asynchronous. This is the NAT device IP address
/// </summary>
/// <returns>
/// The public IP addrees
/// </returns>
/// <example>
/// Console.WriteLine("My public IP is: {0}", await device.GetExternalIPAsync());
/// </example>
/// <exception cref="MappingException">MappingException</exception>
public abstract Task<IPAddress> GetExternalIPAsync();
/// <summary>
/// Gets the specified mapping asynchronous.
/// </summary>
/// <param name="protocol">The protocol.</param>
/// <param name="port">The port.</param>
/// <returns>
/// The matching mapping
/// </returns>
public abstract Task<Mapping> GetSpecificMappingAsync(Protocol protocol, int port);
protected void RegisterMapping(Mapping mapping)
{
_openedMapping.Remove(mapping);
_openedMapping.Add(mapping);
}
protected void UnregisterMapping(Mapping mapping)
{
_openedMapping.RemoveWhere(x => x.Equals(mapping));
}
internal void ReleaseMapping(IEnumerable<Mapping> mappings)
{
var maparr = mappings.ToArray();
var mapCount = maparr.Length;
NatDiscoverer.TraceSource.LogInfo("{0} ports to close", mapCount);
for (var i = 0; i < mapCount; i++)
{
var mapping = _openedMapping.ElementAt(i);
try
{
DeletePortMapAsync(mapping);
NatDiscoverer.TraceSource.LogInfo(mapping + " port successfully closed");
}
catch (Exception)
{
NatDiscoverer.TraceSource.LogError(mapping + " port couldn't be close");
}
}
}
internal void ReleaseAll()
{
ReleaseMapping(_openedMapping);
}
internal void ReleaseSessionMappings()
{
var mappings = from m in _openedMapping
where m.LifetimeType == MappingLifetime.Session
select m;
ReleaseMapping(mappings);
}
#if NET35
internal Task RenewMappings()
{
Task task = null;
var mappings = _openedMapping.Where(x => x.ShoundRenew());
foreach (var mapping in mappings.ToArray())
{
var m = mapping;
task = task == null ? RenewMapping(m) : task.ContinueWith(t => RenewMapping(m)).Unwrap();
}
return task;
}
#else
internal async Task RenewMappings()
{
var mappings = _openedMapping.Where(x => x.ShoundRenew());
foreach (var mapping in mappings.ToArray())
{
var m = mapping;
await RenewMapping(m);
}
}
#endif
#if NET35
private Task RenewMapping(Mapping mapping)
{
var renewMapping = new Mapping(mapping);
renewMapping.Expiration = DateTime.UtcNow.AddSeconds(mapping.Lifetime);
NatDiscoverer.TraceSource.LogInfo("Renewing mapping {0}", renewMapping);
return CreatePortMapAsync(renewMapping)
.ContinueWith(task =>
{
if (task.IsFaulted)
{
NatDiscoverer.TraceSource.LogWarn("Renew {0} failed", mapping);
}
else
{
NatDiscoverer.TraceSource.LogInfo("Next renew scheduled at: {0}",
renewMapping.Expiration.ToLocalTime().TimeOfDay);
}
});
}
#else
private async Task RenewMapping(Mapping mapping)
{
var renewMapping = new Mapping(mapping);
try
{
renewMapping.Expiration = DateTime.UtcNow.AddSeconds(mapping.Lifetime);
NatDiscoverer.TraceSource.LogInfo("Renewing mapping {0}", renewMapping);
await CreatePortMapAsync(renewMapping);
NatDiscoverer.TraceSource.LogInfo("Next renew scheduled at: {0}",
renewMapping.Expiration.ToLocalTime().TimeOfDay);
}
catch (Exception)
{
NatDiscoverer.TraceSource.LogWarn("Renew {0} failed", mapping);
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace PassLib
{
//--------------------------------------------------------------------------------
/// <summary>
/// Helper for saving persitant data to the registry or a ini-File
/// </summary>
//--------------------------------------------------------------------------------
internal class PlProfile
{
[DllImport("kernel32.dll")]
static extern bool WritePrivateProfileString(string lpAppName,
string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32.dll")]
static extern uint GetPrivateProfileString(string lpAppName,
string lpKeyName, string lpDefault, StringBuilder lpReturnedString,
uint nSize, string lpFileName);
[DllImport("kernel32.dll")]
static extern uint GetPrivateProfileInt(string lpAppName, string lpKeyName,
int nDefault, string lpFileName);
static private string m_Name; // Registryname oder Profilpfad
static private ProfileType m_Type;
static internal ProfileType Type{get{return m_Type;}}
internal enum ProfileType { Unknown, IniFile, Registry };
//********************************************************************************
/// <summary>
/// Defines the path of the profile in the registry or as file
/// </summary>
/// <param name="path">RegistryKey "Company name\Application" or path of the file</param>
/// <param name="type">Registry or File</param>
/// <returns></returns>
/// <created>UPh,21.09.2006</created>
/// <changed>UPh,21.09.2006</changed>
//********************************************************************************
internal static void SetProfileName(string path, ProfileType type)
{
m_Type = type;
if (type == ProfileType.Registry)
{
m_Name = "Software\\" + path;
}
else if (type == ProfileType.IniFile)
{
m_Name = path;
}
else
{
throw new ArgumentException("Invalid ProfileType. Only Registry and File is valid.");
}
}
//********************************************************************************
/// <summary>
/// Writes a string to the Profile
/// </summary>
/// <param name="section">Name of the section</param>
/// <param name="entry">Name of the entry</param>
/// <param name="value">String to write</param>
/// <returns></returns>
/// <created>UPh,21.09.2006</created>
/// <changed>UPh,21.09.2006</changed>
//********************************************************************************
internal static void WriteString(string section, string entry, string value)
{
if (m_Name == "")
return;
switch (m_Type)
{
case ProfileType.Registry:
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(m_Name + "\\" + section);
key.SetValue(entry, value);
break;
}
case ProfileType.IniFile:
{
WritePrivateProfileString(section, entry, value, m_Name);
break;
}
default:
{
throw new Exception("Don't know where to write profile data to. Call PlProfile.SetProfileName().");
}
}
}
//********************************************************************************
/// <summary>
/// Returns a string from the profile
/// </summary>
/// <param name="section">Name of the section</param>
/// <param name="entry">Name of the entry</param>
/// <param name="def">Default string</param>
/// <returns></returns>
/// <created>UPh,21.09.2006</created>
/// <changed>UPh,21.09.2006</changed>
//********************************************************************************
internal static string GetString(string section, string entry, string def)
{
string rts = def;
switch (m_Type)
{
case ProfileType.Registry:
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(m_Name + "\\" + section);
if (key != null)
{
object o = key.GetValue(entry);
if (o != null)
rts = o.ToString();
key.Close();
}
break;
}
case ProfileType.IniFile:
{
StringBuilder sb = new StringBuilder();
sb.Capacity = 1024;
GetPrivateProfileString(section, entry, def, sb, 1024, m_Name);
rts = sb.ToString();
break;
}
default:
{
throw new Exception("Don't know where to read profile data from. Call PlProfile.SetProfileName().");
}
}
return rts;
}
//********************************************************************************
/// <summary>
/// Returns a string from the profile
/// </summary>
/// <param name="section">Name of the section</param>
/// <param name="entry">Name of the entry</param>
/// <returns>String, that has been read, "" on error</returns>
/// <created>UPh,21.09.2006</created>
/// <changed>UPh,21.09.2006</changed>
//********************************************************************************
internal static string GetString(string section, string entry)
{
return GetString(section, entry, "");
}
//********************************************************************************
/// <summary>
/// Writes an integer value to the profile
/// </summary>
/// <param name="section">Name of the section</param>
/// <param name="entry">Name of the entry</param>
/// <param name="value">Value to write</param>
/// <returns></returns>
/// <created>UPh,21.09.2006</created>
/// <changed>UPh,21.09.2006</changed>
//********************************************************************************
internal static void WriteInt(string section, string entry, int value)
{
if (m_Name == "")
return;
switch (m_Type)
{
case ProfileType.Registry:
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(m_Name + "\\" + section);
key.SetValue(entry, value);
key.Close();
break;
}
case ProfileType.IniFile:
{
WritePrivateProfileString(section, entry, value.ToString(), m_Name);
break;
}
default:
{
throw new Exception("Don't know where to write profile data to. Call PlProfile.SetProfileName().");
}
}
}
//********************************************************************************
/// <summary>
/// Returns an integer value from the profile
/// </summary>
/// <param name="section">Name of the section</param>
/// <param name="entry">Name of the entry</param>
/// <param name="def">Default value</param>
/// <returns>Integer value. Default value on error.</returns>
/// <created>UPh,21.09.2006</created>
/// <changed>UPh,21.09.2006</changed>
//********************************************************************************
internal static int GetInt(string section, string entry, int def)
{
int rts = def;
switch (m_Type)
{
case ProfileType.Registry:
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(m_Name + "\\" + section);
if (key != null)
{
object o = key.GetValue(entry);
if (o != null)
rts = Int32.Parse(o.ToString());
key.Close();
}
break;
}
case ProfileType.IniFile:
{
rts = (int) GetPrivateProfileInt(section, entry, def, m_Name);
break;
}
default:
{
throw new Exception("Don't know where to read profile data from. Call PlProfile.SetProfileName().");
}
}
return rts;
}
//********************************************************************************
/// <summary>
/// Returns an integer value from the profile
/// </summary>
/// <param name="section">Name of the section</param>
/// <param name="entry">Name of the entry</param>
/// <returns>Integer value. 0 on error.</returns>
/// <created>UPh,21.09.2006</created>
/// <changed>UPh,21.09.2006</changed>
//********************************************************************************
internal static int GetInt(string section, string entry)
{
return GetInt(section, entry, 0);
}
}
}
| |
// 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.Threading;
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Reflection.Runtime.General;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.Metadata.NativeFormat;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.TypeSystem.NativeFormat;
using Debug = System.Diagnostics.Debug;
namespace Internal.Runtime.TypeLoader
{
internal class Callbacks : TypeLoaderCallbacks
{
public override bool TryGetConstructedGenericTypeForComponents(RuntimeTypeHandle genericTypeDefinitionHandle, RuntimeTypeHandle[] genericTypeArgumentHandles, out RuntimeTypeHandle runtimeTypeHandle)
{
return TypeLoaderEnvironment.Instance.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle);
}
public override int GetThreadStaticsSizeForDynamicType(int index, out int numTlsCells)
{
return TypeLoaderEnvironment.Instance.TryGetThreadStaticsSizeForDynamicType(index, out numTlsCells);
}
public override IntPtr GenericLookupFromContextAndSignature(IntPtr context, IntPtr signature, out IntPtr auxResult)
{
return TypeLoaderEnvironment.Instance.GenericLookupFromContextAndSignature(context, signature, out auxResult);
}
public override bool GetRuntimeMethodHandleComponents(RuntimeMethodHandle runtimeMethodHandle, out RuntimeTypeHandle declaringTypeHandle, out MethodNameAndSignature nameAndSignature, out RuntimeTypeHandle[] genericMethodArgs)
{
return TypeLoaderEnvironment.Instance.TryGetRuntimeMethodHandleComponents(runtimeMethodHandle, out declaringTypeHandle, out nameAndSignature, out genericMethodArgs);
}
public override bool CompareMethodSignatures(RuntimeSignature signature1, RuntimeSignature signature2)
{
return TypeLoaderEnvironment.Instance.CompareMethodSignatures(signature1, signature2);
}
public override IntPtr TryGetDefaultConstructorForType(RuntimeTypeHandle runtimeTypeHandle)
{
return TypeLoaderEnvironment.Instance.TryGetDefaultConstructorForType(runtimeTypeHandle);
}
public override IntPtr GetDelegateThunk(Delegate delegateObject, int thunkKind)
{
return CallConverterThunk.GetDelegateThunk(delegateObject, thunkKind);
}
public override bool TryGetGenericVirtualTargetForTypeAndSlot(RuntimeTypeHandle targetHandle, ref RuntimeTypeHandle declaringType, RuntimeTypeHandle[] genericArguments, ref string methodName, ref RuntimeSignature methodSignature, out IntPtr methodPointer, out IntPtr dictionaryPointer, out bool slotUpdated)
{
return TypeLoaderEnvironment.Instance.TryGetGenericVirtualTargetForTypeAndSlot(targetHandle, ref declaringType, genericArguments, ref methodName, ref methodSignature, out methodPointer, out dictionaryPointer, out slotUpdated);
}
public override bool GetRuntimeFieldHandleComponents(RuntimeFieldHandle runtimeFieldHandle, out RuntimeTypeHandle declaringTypeHandle, out string fieldName)
{
return TypeLoaderEnvironment.Instance.TryGetRuntimeFieldHandleComponents(runtimeFieldHandle, out declaringTypeHandle, out fieldName);
}
public override IntPtr ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(IntPtr unboxingFunctionPointer, RuntimeTypeHandle declaringType)
{
return TypeLoaderEnvironment.ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(unboxingFunctionPointer, declaringType);
}
public override bool TryGetPointerTypeForTargetType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle pointerTypeHandle)
{
return TypeLoaderEnvironment.Instance.TryGetPointerTypeForTargetType(pointeeTypeHandle, out pointerTypeHandle);
}
public override bool TryGetArrayTypeForElementType(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle)
{
return TypeLoaderEnvironment.Instance.TryGetArrayTypeForElementType(elementTypeHandle, isMdArray, rank, out arrayTypeHandle);
}
public override IntPtr UpdateFloatingDictionary(IntPtr context, IntPtr dictionaryPtr)
{
return TypeLoaderEnvironment.Instance.UpdateFloatingDictionary(context, dictionaryPtr);
}
/// <summary>
/// Register a new runtime-allocated code thunk in the diagnostic stream.
/// </summary>
/// <param name="thunkAddress">Address of thunk to register</param>
public override void RegisterThunk(IntPtr thunkAddress)
{
SerializedDebugData.RegisterTailCallThunk(thunkAddress);
}
}
public static class RuntimeSignatureExtensions
{
public static IntPtr NativeLayoutSignature(this RuntimeSignature signature)
{
if (!signature.IsNativeLayoutSignature)
Environment.FailFast("Not a valid native layout signature");
NativeReader reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(signature);
return reader.OffsetToAddress(signature.NativeLayoutOffset);
}
}
public sealed partial class TypeLoaderEnvironment
{
[ThreadStatic]
private static bool t_isReentrant;
public static TypeLoaderEnvironment Instance { get; private set; }
/// <summary>
/// List of loaded binary modules is typically used to locate / process various metadata blobs
/// and other per-module information.
/// </summary>
public readonly ModuleList ModuleList;
// Cache the NativeReader in each module to avoid looking up the NativeLayoutInfo blob each
// time we call GetNativeLayoutInfoReader(). The dictionary is a thread static variable to ensure
// thread safety. Using ThreadStatic instead of a lock is ok as long as the NativeReader class is
// small enough in size (which is the case today).
[ThreadStatic]
private static LowLevelDictionary<TypeManagerHandle, NativeReader> t_moduleNativeReaders;
// Eager initialization called from LibraryInitializer for the assembly.
internal static void Initialize()
{
Instance = new TypeLoaderEnvironment();
RuntimeAugments.InitializeLookups(new Callbacks());
NoStaticsData = (IntPtr)1;
}
public TypeLoaderEnvironment()
{
ModuleList = new ModuleList();
}
// To keep the synchronization simple, we execute all type loading under a global lock
private Lock _typeLoaderLock = new Lock();
public void VerifyTypeLoaderLockHeld()
{
if (!_typeLoaderLock.IsAcquired)
Environment.FailFast("TypeLoaderLock not held");
}
public void RunUnderTypeLoaderLock(Action action)
{
using (LockHolder.Hold(_typeLoaderLock))
{
action();
}
}
public IntPtr GenericLookupFromContextAndSignature(IntPtr context, IntPtr signature, out IntPtr auxResult)
{
IntPtr result;
using (LockHolder.Hold(_typeLoaderLock))
{
try
{
if (t_isReentrant)
Environment.FailFast("Reentrant lazy generic lookup");
t_isReentrant = true;
result = TypeBuilder.BuildGenericLookupTarget(context, signature, out auxResult);
t_isReentrant = false;
}
catch
{
// Catch and rethrow any exceptions instead of using finally block. Otherwise, filters that are run during
// the first pass of exception unwind may hit the re-entrancy fail fast above.
// TODO: Convert this to filter for better diagnostics once we switch to Roslyn
t_isReentrant = false;
throw;
}
}
return result;
}
private bool EnsureTypeHandleForType(TypeDesc type)
{
if (type.RuntimeTypeHandle.IsNull())
{
using (LockHolder.Hold(_typeLoaderLock))
{
// Now that we hold the lock, we may find that existing types can now find
// their associated RuntimeTypeHandle. Flush the type builder states as a way
// to force the reresolution of RuntimeTypeHandles which couldn't be found before.
type.Context.FlushTypeBuilderStates();
try
{
new TypeBuilder().BuildType(type);
}
catch (TypeBuilder.MissingTemplateException)
{
return false;
}
}
}
// Returned type has to have a valid type handle value
Debug.Assert(!type.RuntimeTypeHandle.IsNull());
return !type.RuntimeTypeHandle.IsNull();
}
internal TypeDesc GetConstructedTypeFromParserAndNativeLayoutContext(ref NativeParser parser, NativeLayoutInfoLoadContext nativeLayoutContext)
{
TypeDesc parsedType = nativeLayoutContext.GetType(ref parser);
if (parsedType == null)
return null;
if (!EnsureTypeHandleForType(parsedType))
return null;
return parsedType;
}
//
// Parse a native layout signature pointed to by "signature" in the executable image, optionally using
// "typeArgs" and "methodArgs" for generic type parameter substitution. The first field in "signature"
// must be an encoded type but any data beyond that is user-defined and returned in "remainingSignature"
//
internal bool GetTypeFromSignatureAndContext(RuntimeSignature signature, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType, out RuntimeSignature remainingSignature)
{
NativeReader reader = GetNativeLayoutInfoReader(signature);
NativeParser parser = new NativeParser(reader, signature.NativeLayoutOffset);
bool result = GetTypeFromSignatureAndContext(ref parser, new TypeManagerHandle(signature.ModuleHandle), typeArgs, methodArgs, out createdType);
remainingSignature = RuntimeSignature.CreateFromNativeLayoutSignature(signature, parser.Offset);
return result;
}
internal bool GetTypeFromSignatureAndContext(ref NativeParser parser, TypeManagerHandle moduleHandle, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType)
{
createdType = default(RuntimeTypeHandle);
TypeSystemContext context = TypeSystemContextFactory.Create();
TypeDesc parsedType = TryParseNativeSignatureWorker(context, moduleHandle, ref parser, typeArgs, methodArgs, false) as TypeDesc;
if (parsedType == null)
return false;
if (!EnsureTypeHandleForType(parsedType))
return false;
createdType = parsedType.RuntimeTypeHandle;
TypeSystemContextFactory.Recycle(context);
return true;
}
//
// Parse a native layout signature pointed to by "signature" in the executable image, optionally using
// "typeArgs" and "methodArgs" for generic type parameter substitution. The first field in "signature"
// must be an encoded method but any data beyond that is user-defined and returned in "remainingSignature"
//
public bool GetMethodFromSignatureAndContext(RuntimeSignature signature, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType, out MethodNameAndSignature nameAndSignature, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles, out RuntimeSignature remainingSignature)
{
NativeReader reader = GetNativeLayoutInfoReader(signature);
NativeParser parser = new NativeParser(reader, signature.NativeLayoutOffset);
bool result = GetMethodFromSignatureAndContext(ref parser, new TypeManagerHandle(signature.ModuleHandle), typeArgs, methodArgs, out createdType, out nameAndSignature, out genericMethodTypeArgumentHandles);
remainingSignature = RuntimeSignature.CreateFromNativeLayoutSignature(signature, parser.Offset);
return result;
}
internal bool GetMethodFromSignatureAndContext(ref NativeParser parser, TypeManagerHandle moduleHandle, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs, out RuntimeTypeHandle createdType, out MethodNameAndSignature nameAndSignature, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles)
{
createdType = default(RuntimeTypeHandle);
nameAndSignature = null;
genericMethodTypeArgumentHandles = null;
TypeSystemContext context = TypeSystemContextFactory.Create();
MethodDesc parsedMethod = TryParseNativeSignatureWorker(context, moduleHandle, ref parser, typeArgs, methodArgs, true) as MethodDesc;
if (parsedMethod == null)
return false;
if (!EnsureTypeHandleForType(parsedMethod.OwningType))
return false;
createdType = parsedMethod.OwningType.RuntimeTypeHandle;
nameAndSignature = parsedMethod.NameAndSignature;
if (!parsedMethod.IsMethodDefinition && parsedMethod.Instantiation.Length > 0)
{
genericMethodTypeArgumentHandles = new RuntimeTypeHandle[parsedMethod.Instantiation.Length];
for (int i = 0; i < parsedMethod.Instantiation.Length; ++i)
{
if (!EnsureTypeHandleForType(parsedMethod.Instantiation[i]))
return false;
genericMethodTypeArgumentHandles[i] = parsedMethod.Instantiation[i].RuntimeTypeHandle;
}
}
TypeSystemContextFactory.Recycle(context);
return true;
}
//
// Returns the native layout info reader
//
internal unsafe NativeReader GetNativeLayoutInfoReader(NativeFormatModuleInfo module)
{
return GetNativeLayoutInfoReader(module.Handle);
}
//
// Returns the native layout info reader
//
internal unsafe NativeReader GetNativeLayoutInfoReader(RuntimeSignature signature)
{
Debug.Assert(signature.IsNativeLayoutSignature);
return GetNativeLayoutInfoReader(new TypeManagerHandle(signature.ModuleHandle));
}
//
// Returns the native layout info reader
//
internal unsafe NativeReader GetNativeLayoutInfoReader(TypeManagerHandle moduleHandle)
{
Debug.Assert(!moduleHandle.IsNull);
if (t_moduleNativeReaders == null)
t_moduleNativeReaders = new LowLevelDictionary<TypeManagerHandle, NativeReader>();
NativeReader result = null;
if (t_moduleNativeReaders.TryGetValue(moduleHandle, out result))
return result;
byte* pBlob;
uint cbBlob;
if (RuntimeAugments.FindBlob(moduleHandle, (int)ReflectionMapBlob.NativeLayoutInfo, new IntPtr(&pBlob), new IntPtr(&cbBlob)))
result = new NativeReader(pBlob, cbBlob);
t_moduleNativeReaders.Add(moduleHandle, result);
return result;
}
private static RuntimeTypeHandle[] GetTypeSequence(ref ExternalReferencesTable extRefs, ref NativeParser parser)
{
uint count = parser.GetUnsigned();
RuntimeTypeHandle[] result = new RuntimeTypeHandle[count];
for (uint i = 0; i < count; i++)
result[i] = extRefs.GetRuntimeTypeHandleFromIndex(parser.GetUnsigned());
return result;
}
private static RuntimeTypeHandle[] TypeDescsToRuntimeHandles(Instantiation types)
{
var result = new RuntimeTypeHandle[types.Length];
for (int i = 0; i < types.Length; i++)
result[i] = types[i].RuntimeTypeHandle;
return result;
}
public bool TryGetConstructedGenericTypeForComponents(RuntimeTypeHandle genericTypeDefinitionHandle, RuntimeTypeHandle[] genericTypeArgumentHandles, out RuntimeTypeHandle runtimeTypeHandle)
{
if (TryLookupConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle))
return true;
using (LockHolder.Hold(_typeLoaderLock))
{
return TypeBuilder.TryBuildGenericType(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle);
}
}
// Get an array RuntimeTypeHandle given an element's RuntimeTypeHandle and rank. Pass false for isMdArray, and rank == -1 for SzArrays
public bool TryGetArrayTypeForElementType(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle)
{
if (TryGetArrayTypeForElementType_LookupOnly(elementTypeHandle, isMdArray, rank, out arrayTypeHandle))
{
return true;
}
using (LockHolder.Hold(_typeLoaderLock))
{
if (isMdArray && (rank < MDArray.MinRank) && (rank > MDArray.MaxRank))
{
arrayTypeHandle = default(RuntimeTypeHandle);
return false;
}
if (TypeSystemContext.GetArrayTypesCache(isMdArray, rank).TryGetValue(elementTypeHandle, out arrayTypeHandle))
return true;
return TypeBuilder.TryBuildArrayType(elementTypeHandle, isMdArray, rank, out arrayTypeHandle);
}
}
// Looks up an array RuntimeTypeHandle given an element's RuntimeTypeHandle and rank. A rank of -1 indicates SzArray
internal bool TryGetArrayTypeForElementType_LookupOnly(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle)
{
if (isMdArray && (rank < MDArray.MinRank) && (rank > MDArray.MaxRank))
{
arrayTypeHandle = default(RuntimeTypeHandle);
return false;
}
if (TypeSystemContext.GetArrayTypesCache(isMdArray, rank).TryGetValue(elementTypeHandle, out arrayTypeHandle))
return true;
if (!isMdArray &&
!RuntimeAugments.IsDynamicType(elementTypeHandle) &&
TryGetArrayTypeForNonDynamicElementType(elementTypeHandle, out arrayTypeHandle))
{
TypeSystemContext.GetArrayTypesCache(isMdArray, rank).AddOrGetExisting(arrayTypeHandle);
return true;
}
return false;
}
public bool TryGetPointerTypeForTargetType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle pointerTypeHandle)
{
// There are no lookups for pointers in static modules. All pointer EETypes will be created at this level.
// It's possible to have multiple pointer EETypes representing the same pointer type with the same element type
// The caching of pointer types is done at the reflection layer (in the RuntimeTypeUnifier) and
// here in the TypeSystemContext layer
if (TypeSystemContext.PointerTypesCache.TryGetValue(pointeeTypeHandle, out pointerTypeHandle))
return true;
using (LockHolder.Hold(_typeLoaderLock))
{
return TypeBuilder.TryBuildPointerType(pointeeTypeHandle, out pointerTypeHandle);
}
}
public bool TryGetByRefTypeForTargetType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle byRefTypeHandle)
{
// There are no lookups for ByRefs in static modules. All ByRef EETypes will be created at this level.
// It's possible to have multiple ByRef EETypes representing the same ByRef type with the same element type
// The caching of ByRef types is done at the reflection layer (in the RuntimeTypeUnifier) and
// here in the TypeSystemContext layer
if (TypeSystemContext.ByRefTypesCache.TryGetValue(pointeeTypeHandle, out byRefTypeHandle))
return true;
using (LockHolder.Hold(_typeLoaderLock))
{
return TypeBuilder.TryBuildByRefType(pointeeTypeHandle, out byRefTypeHandle);
}
}
public int GetCanonicalHashCode(RuntimeTypeHandle typeHandle, CanonicalFormKind kind)
{
TypeSystemContext context = TypeSystemContextFactory.Create();
TypeDesc type = context.ResolveRuntimeTypeHandle(typeHandle);
int hashCode = type.ConvertToCanonForm(kind).GetHashCode();
TypeSystemContextFactory.Recycle(context);
return hashCode;
}
private object TryParseNativeSignatureWorker(TypeSystemContext typeSystemContext, TypeManagerHandle moduleHandle, ref NativeParser parser, RuntimeTypeHandle[] typeGenericArgumentHandles, RuntimeTypeHandle[] methodGenericArgumentHandles, bool isMethodSignature)
{
Instantiation typeGenericArguments = typeSystemContext.ResolveRuntimeTypeHandles(typeGenericArgumentHandles ?? Array.Empty<RuntimeTypeHandle>());
Instantiation methodGenericArguments = typeSystemContext.ResolveRuntimeTypeHandles(methodGenericArgumentHandles ?? Array.Empty<RuntimeTypeHandle>());
NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext();
nativeLayoutContext._module = ModuleList.GetModuleInfoByHandle(moduleHandle);
nativeLayoutContext._typeSystemContext = typeSystemContext;
nativeLayoutContext._typeArgumentHandles = typeGenericArguments;
nativeLayoutContext._methodArgumentHandles = methodGenericArguments;
if (isMethodSignature)
return nativeLayoutContext.GetMethod(ref parser);
else
return nativeLayoutContext.GetType(ref parser);
}
public bool TryGetGenericMethodDictionaryForComponents(RuntimeTypeHandle declaringTypeHandle, RuntimeTypeHandle[] genericMethodArgHandles, MethodNameAndSignature nameAndSignature, out IntPtr methodDictionary)
{
if (TryLookupGenericMethodDictionaryForComponents(declaringTypeHandle, nameAndSignature, genericMethodArgHandles, out methodDictionary))
return true;
using (LockHolder.Hold(_typeLoaderLock))
{
return TypeBuilder.TryBuildGenericMethod(declaringTypeHandle, genericMethodArgHandles, nameAndSignature, out methodDictionary);
}
}
public bool TryGetFieldOffset(RuntimeTypeHandle declaringTypeHandle, uint fieldOrdinal, out int fieldOffset)
{
fieldOffset = int.MinValue;
// No use going further for non-generic types... TypeLoader doesn't have offset answers for non-generic types!
if (!declaringTypeHandle.IsGenericType())
return false;
using (LockHolder.Hold(_typeLoaderLock))
{
return TypeBuilder.TryGetFieldOffset(declaringTypeHandle, fieldOrdinal, out fieldOffset);
}
}
public unsafe IntPtr UpdateFloatingDictionary(IntPtr context, IntPtr dictionaryPtr)
{
IntPtr newFloatingDictionary;
bool isNewlyAllocatedDictionary;
bool isTypeContext = context != dictionaryPtr;
if (isTypeContext)
{
// Look for the exact base type that owns the dictionary. We may be having
// a virtual method run on a derived type and the generic lookup are performed
// on the base type's dictionary.
EEType* pEEType = (EEType*)context.ToPointer();
context = (IntPtr)EETypeCreator.GetBaseEETypeForDictionaryPtr(pEEType, dictionaryPtr);
}
using (LockHolder.Hold(_typeLoaderLock))
{
// Check if some other thread already allocated a floating dictionary and updated the fixed portion
if(*(IntPtr*)dictionaryPtr != IntPtr.Zero)
return *(IntPtr*)dictionaryPtr;
try
{
if (t_isReentrant)
Environment.FailFast("Reentrant update to floating dictionary");
t_isReentrant = true;
newFloatingDictionary = TypeBuilder.TryBuildFloatingDictionary(context, isTypeContext, dictionaryPtr, out isNewlyAllocatedDictionary);
t_isReentrant = false;
}
catch
{
// Catch and rethrow any exceptions instead of using finally block. Otherwise, filters that are run during
// the first pass of exception unwind may hit the re-entrancy fail fast above.
// TODO: Convert this to filter for better diagnostics once we switch to Roslyn
t_isReentrant = false;
throw;
}
}
if (newFloatingDictionary == IntPtr.Zero)
{
Environment.FailFast("Unable to update floating dictionary");
return IntPtr.Zero;
}
// The pointer to the floating dictionary is the first slot of the fixed dictionary.
if (Interlocked.CompareExchange(ref *(IntPtr*)dictionaryPtr, newFloatingDictionary, IntPtr.Zero) != IntPtr.Zero)
{
// Some other thread beat us and updated the pointer to the floating dictionary.
// Free the one allocated by the current thread
if (isNewlyAllocatedDictionary)
MemoryHelpers.FreeMemory(newFloatingDictionary);
}
return *(IntPtr*)dictionaryPtr;
}
public bool CanInstantiationsShareCode(RuntimeTypeHandle[] genericArgHandles1, RuntimeTypeHandle[] genericArgHandles2, CanonicalFormKind kind)
{
if (genericArgHandles1.Length != genericArgHandles2.Length)
return false;
bool match = true;
TypeSystemContext context = TypeSystemContextFactory.Create();
for (int i = 0; i < genericArgHandles1.Length; i++)
{
TypeDesc genericArg1 = context.ResolveRuntimeTypeHandle(genericArgHandles1[i]);
TypeDesc genericArg2 = context.ResolveRuntimeTypeHandle(genericArgHandles2[i]);
if (context.ConvertToCanon(genericArg1, kind) != context.ConvertToCanon(genericArg2, kind))
{
match = false;
break;
}
}
TypeSystemContextFactory.Recycle(context);
return match;
}
public bool ConversionToCanonFormIsAChange(RuntimeTypeHandle[] genericArgHandles, CanonicalFormKind kind)
{
// Todo: support for universal canon type?
TypeSystemContext context = TypeSystemContextFactory.Create();
Instantiation genericArgs = context.ResolveRuntimeTypeHandles(genericArgHandles);
bool result;
context.ConvertInstantiationToCanonForm(genericArgs, kind, out result);
TypeSystemContextFactory.Recycle(context);
return result;
}
// get the generics hash table and external references table for a module
// TODO multi-file: consider whether we want to cache this info
private unsafe bool GetHashtableFromBlob(NativeFormatModuleInfo module, ReflectionMapBlob blobId, out NativeHashtable hashtable, out ExternalReferencesTable externalReferencesLookup)
{
byte* pBlob;
uint cbBlob;
hashtable = default(NativeHashtable);
externalReferencesLookup = default(ExternalReferencesTable);
if (!module.TryFindBlob(blobId, out pBlob, out cbBlob))
return false;
NativeReader reader = new NativeReader(pBlob, cbBlob);
NativeParser parser = new NativeParser(reader, 0);
hashtable = new NativeHashtable(parser);
return externalReferencesLookup.InitializeNativeReferences(module);
}
public static unsafe void GetFieldAlignmentAndSize(RuntimeTypeHandle fieldType, out int alignment, out int size)
{
EEType* typePtr = fieldType.ToEETypePtr();
if (typePtr->IsValueType)
{
size = (int)typePtr->ValueTypeSize;
}
else
{
size = IntPtr.Size;
}
alignment = (int)typePtr->FieldAlignmentRequirement;
}
[StructLayout(LayoutKind.Sequential)]
private struct UnboxingAndInstantiatingStubMapEntry
{
public uint StubMethodRva;
public uint MethodRva;
}
public static unsafe bool TryGetTargetOfUnboxingAndInstantiatingStub(IntPtr maybeInstantiatingAndUnboxingStub, out IntPtr targetMethod)
{
targetMethod = RuntimeAugments.GetTargetOfUnboxingAndInstantiatingStub(maybeInstantiatingAndUnboxingStub);
if (targetMethod != IntPtr.Zero)
{
return true;
}
// TODO: The rest of the code in this function is specific to ProjectN only. When we kill the binder, get rid of this
// linear search code (the only API that should be used for the lookup is the one above)
// Get module
IntPtr associatedModule = RuntimeAugments.GetOSModuleFromPointer(maybeInstantiatingAndUnboxingStub);
if (associatedModule == IntPtr.Zero)
{
return false;
}
// Module having a type manager means we are not in ProjectN mode. Bail out earlier.
foreach (TypeManagerHandle handle in ModuleList.Enumerate())
{
if (handle.OsModuleBase == associatedModule && handle.IsTypeManager)
{
return false;
}
}
// Get UnboxingAndInstantiatingTable
UnboxingAndInstantiatingStubMapEntry* pBlob;
uint cbBlob;
if (!RuntimeAugments.FindBlob(new TypeManagerHandle(associatedModule), (int)ReflectionMapBlob.UnboxingAndInstantiatingStubMap, (IntPtr)(&pBlob), (IntPtr)(&cbBlob)))
{
return false;
}
uint cStubs = cbBlob / (uint)sizeof(UnboxingAndInstantiatingStubMapEntry);
for (uint i = 0; i < cStubs; ++i)
{
if (RvaToFunctionPointer(new TypeManagerHandle(associatedModule), pBlob[i].StubMethodRva) == maybeInstantiatingAndUnboxingStub)
{
// We found a match, create pointer from RVA and move on.
targetMethod = RvaToFunctionPointer(new TypeManagerHandle(associatedModule), pBlob[i].MethodRva);
return true;
}
}
// Stub not found.
return false;
}
public bool TryComputeHasInstantiationDeterminedSize(RuntimeTypeHandle typeHandle, out bool hasInstantiationDeterminedSize)
{
TypeSystemContext context = TypeSystemContextFactory.Create();
bool success = TryComputeHasInstantiationDeterminedSize(typeHandle, context, out hasInstantiationDeterminedSize);
TypeSystemContextFactory.Recycle(context);
return success;
}
public bool TryComputeHasInstantiationDeterminedSize(RuntimeTypeHandle typeHandle, TypeSystemContext context, out bool hasInstantiationDeterminedSize)
{
Debug.Assert(RuntimeAugments.IsGenericType(typeHandle) || RuntimeAugments.IsGenericTypeDefinition(typeHandle));
DefType type = (DefType)context.ResolveRuntimeTypeHandle(typeHandle);
return TryComputeHasInstantiationDeterminedSize(type, out hasInstantiationDeterminedSize);
}
internal bool TryComputeHasInstantiationDeterminedSize(DefType type, out bool hasInstantiationDeterminedSize)
{
Debug.Assert(type.HasInstantiation);
NativeLayoutInfoLoadContext loadContextUniversal;
NativeLayoutInfo universalLayoutInfo;
NativeParser parser = type.GetOrCreateTypeBuilderState().GetParserForUniversalNativeLayoutInfo(out loadContextUniversal, out universalLayoutInfo);
if (parser.IsNull)
{
hasInstantiationDeterminedSize = false;
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
MetadataType typeDefinition = type.GetTypeDefinition() as MetadataType;
if (typeDefinition != null)
{
TypeDesc [] universalCanonInstantiation = new TypeDesc[type.Instantiation.Length];
TypeSystemContext context = type.Context;
TypeDesc universalCanonType = context.UniversalCanonType;
for (int i = 0 ; i < universalCanonInstantiation.Length; i++)
universalCanonInstantiation[i] = universalCanonType;
DefType universalCanonForm = typeDefinition.MakeInstantiatedType(universalCanonInstantiation);
hasInstantiationDeterminedSize = universalCanonForm.InstanceFieldSize.IsIndeterminate;
return true;
}
#endif
return false;
}
int? flags = (int?)parser.GetUnsignedForBagElementKind(BagElementKind.TypeFlags);
hasInstantiationDeterminedSize = flags.HasValue ?
(((NativeFormat.TypeFlags)flags) & NativeFormat.TypeFlags.HasInstantiationDeterminedSize) != 0 :
false;
return true;
}
public bool TryResolveSingleMetadataFixup(ModuleInfo module, int metadataToken, MetadataFixupKind fixupKind, out IntPtr fixupResolution)
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
using (LockHolder.Hold(_typeLoaderLock))
{
try
{
return TypeBuilder.TryResolveSingleMetadataFixup((NativeFormatModuleInfo)module, metadataToken, fixupKind, out fixupResolution);
}
catch (Exception ex)
{
Environment.FailFast("Failed to resolve metadata token " +
((uint)metadataToken).LowLevelToString() + ": " + ex.Message);
#else
Environment.FailFast("Failed to resolve metadata token " +
((uint)metadataToken).LowLevelToString());
#endif
fixupResolution = IntPtr.Zero;
return false;
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
}
}
#endif
}
public bool TryDispatchMethodOnTarget(NativeFormatModuleInfo module, int metadataToken, RuntimeTypeHandle targetInstanceType, out IntPtr methodAddress)
{
using (LockHolder.Hold(_typeLoaderLock))
{
return TryDispatchMethodOnTarget_Inner(
module,
metadataToken,
targetInstanceType,
out methodAddress);
}
}
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
internal DispatchCellInfo ConvertDispatchCellInfo(NativeFormatModuleInfo module, DispatchCellInfo cellInfo)
{
using (LockHolder.Hold(_typeLoaderLock))
{
return ConvertDispatchCellInfo_Inner(
module,
cellInfo);
}
}
#endif
internal bool TryResolveTypeSlotDispatch(IntPtr targetTypeAsIntPtr, IntPtr interfaceTypeAsIntPtr, ushort slot, out IntPtr methodAddress)
{
using (LockHolder.Hold(_typeLoaderLock))
{
return TryResolveTypeSlotDispatch_Inner(targetTypeAsIntPtr, interfaceTypeAsIntPtr, slot, out methodAddress);
}
}
public unsafe bool TryGetOrCreateNamedTypeForMetadata(
QTypeDefinition qTypeDefinition,
out RuntimeTypeHandle runtimeTypeHandle)
{
if (TryGetNamedTypeForMetadata(qTypeDefinition, out runtimeTypeHandle))
{
return true;
}
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
using (LockHolder.Hold(_typeLoaderLock))
{
IntPtr runtimeTypeHandleAsIntPtr;
TypeBuilder.ResolveSingleTypeDefinition(qTypeDefinition, out runtimeTypeHandleAsIntPtr);
runtimeTypeHandle = *(RuntimeTypeHandle*)&runtimeTypeHandleAsIntPtr;
return true;
}
#else
return false;
#endif
}
public static IntPtr ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(IntPtr unboxingFunctionPointer, RuntimeTypeHandle declaringType)
{
if (FunctionPointerOps.IsGenericMethodPointer(unboxingFunctionPointer))
{
// Handle shared generic methods
unsafe
{
GenericMethodDescriptor* functionPointerDescriptor = FunctionPointerOps.ConvertToGenericDescriptor(unboxingFunctionPointer);
IntPtr nonUnboxingTarget = RuntimeAugments.GetCodeTarget(functionPointerDescriptor->MethodFunctionPointer);
Debug.Assert(nonUnboxingTarget != functionPointerDescriptor->MethodFunctionPointer);
Debug.Assert(nonUnboxingTarget == RuntimeAugments.GetCodeTarget(nonUnboxingTarget));
return FunctionPointerOps.GetGenericMethodFunctionPointer(nonUnboxingTarget, functionPointerDescriptor->InstantiationArgument);
}
}
// GetCodeTarget will look through simple unboxing stubs (ones that consist of adjusting the this pointer and then
// jumping to the target.
IntPtr exactTarget = RuntimeAugments.GetCodeTarget(unboxingFunctionPointer);
if (RuntimeAugments.IsGenericType(declaringType))
{
IntPtr fatFunctionPointerTarget;
// This check looks for unboxing and instantiating stubs generated via the compiler backend
if (TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(exactTarget, out fatFunctionPointerTarget))
{
// If this is an unboxing and instantiating stub, use seperate table, find target, and create fat function pointer
exactTarget = FunctionPointerOps.GetGenericMethodFunctionPointer(fatFunctionPointerTarget,
declaringType.ToIntPtr());
}
else
{
IntPtr newExactTarget;
// This check looks for unboxing and instantiating stubs generated dynamically as thunks in the calling convention converter
if (CallConverterThunk.TryGetNonUnboxingFunctionPointerFromUnboxingAndInstantiatingStub(exactTarget,
declaringType, out newExactTarget))
{
// CallingConventionConverter determined non-unboxing stub
exactTarget = newExactTarget;
}
else
{
// Target method was a method on a generic, but it wasn't a shared generic, and thus none of the above
// complex unboxing stub digging logic was necessary. Do nothing, and use exactTarget as discovered
// from GetCodeTarget
}
}
}
return exactTarget;
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript
{
using Microsoft.JScript.Vsa;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Permissions;
public sealed class Eval : AST
{
private AST operand;
private AST unsafeOption;
private FunctionScope enclosingFunctionScope;
internal Eval(Context context, AST operand, AST unsafeOption)
: base(context)
{
this.operand = operand;
this.unsafeOption = unsafeOption;
ScriptObject enclosingScope = Globals.ScopeStack.Peek();
((IActivationObject)enclosingScope).GetGlobalScope().evilScript = true;
if (enclosingScope is ActivationObject)
((ActivationObject)enclosingScope).isKnownAtCompileTime = this.Engine.doFast;
if (enclosingScope is FunctionScope)
{
this.enclosingFunctionScope = (FunctionScope)enclosingScope;
this.enclosingFunctionScope.mustSaveStackLocals = true;
ScriptObject scope = (ScriptObject)this.enclosingFunctionScope.GetParent();
while (scope != null)
{
FunctionScope fscope = scope as FunctionScope;
if (fscope != null)
{
fscope.mustSaveStackLocals = true;
fscope.closuresMightEscape = true;
}
scope = (ScriptObject)scope.GetParent();
}
}
else
this.enclosingFunctionScope = null;
}
internal override void CheckIfOKToUseInSuperConstructorCall()
{
this.context.HandleError(JSError.NotAllowedInSuperConstructorCall);
}
internal override Object Evaluate()
{
if (VsaEngine.executeForJSEE)
throw new JScriptException(JSError.NonSupportedInDebugger);
Object v = this.operand.Evaluate();
Object u = null;
if (this.unsafeOption != null)
u = this.unsafeOption.Evaluate();
Globals.CallContextStack.Push(new CallContext(this.context, null, new Object[] { v, u }));
try
{
try
{
return JScriptEvaluate(v, u, this.Engine);
}
catch (JScriptException e)
{
if (e.context == null)
{
e.context = this.context;
}
throw e;
}
catch (Exception e)
{
throw new JScriptException(e, this.context);
}
catch
{
throw new JScriptException(JSError.NonClsException, this.context);
}
}
finally
{
Globals.CallContextStack.Pop();
}
}
public static Object JScriptEvaluate(Object source, VsaEngine engine)
{
if (Convert.GetTypeCode(source) != TypeCode.String)
return source;
return Eval.DoEvaluate(source, engine, true);
}
public static Object JScriptEvaluate(Object source, Object unsafeOption, VsaEngine engine)
{
if (Convert.GetTypeCode(source) != TypeCode.String)
return source;
bool isUnsafe = false;
if (Convert.GetTypeCode(unsafeOption) == TypeCode.String)
{
if (((IConvertible)unsafeOption).ToString() == "unsafe")
isUnsafe = true;
}
return Eval.DoEvaluate(source, engine, isUnsafe);
}
private static Object DoEvaluate(Object source, VsaEngine engine, bool isUnsafe)
{
if (engine.doFast)
engine.PushScriptObject(new BlockScope(engine.ScriptObjectStackTop()));
try
{
Context context = new Context(new DocumentContext("eval code", engine), ((IConvertible)source).ToString());
JSParser p = new JSParser(context);
if (!isUnsafe)
new SecurityPermission(SecurityPermissionFlag.Execution).PermitOnly();
return ((Completion)p.ParseEvalBody().PartiallyEvaluate().Evaluate()).value;
}
finally
{
if (engine.doFast)
engine.PopScriptObject();
}
}
internal override AST PartiallyEvaluate()
{
VsaEngine engine = this.Engine;
ScriptObject scope = Globals.ScopeStack.Peek();
ClassScope cscope = ClassScope.ScopeOfClassMemberInitializer(scope);
if (null != cscope)
{
if (cscope.inStaticInitializerCode)
cscope.staticInitializerUsesEval = true;
else
cscope.instanceInitializerUsesEval = true;
}
if (engine.doFast)
engine.PushScriptObject(new BlockScope(scope));
else
{
while (scope is WithObject || scope is BlockScope)
{
if (scope is BlockScope)
((BlockScope)scope).isKnownAtCompileTime = false;
scope = scope.GetParent();
}
}
try
{
this.operand = this.operand.PartiallyEvaluate();
if (this.unsafeOption != null)
this.unsafeOption = this.unsafeOption.PartiallyEvaluate();
if (this.enclosingFunctionScope != null && this.enclosingFunctionScope.owner == null)
this.context.HandleError(JSError.NotYetImplemented);
return this;
}
finally
{
if (engine.doFast)
this.Engine.PopScriptObject();
}
}
internal override void TranslateToIL(ILGenerator il, Type rtype)
{
if (this.enclosingFunctionScope != null && this.enclosingFunctionScope.owner != null)
this.enclosingFunctionScope.owner.TranslateToILToSaveLocals(il);
this.operand.TranslateToIL(il, Typeob.Object);
MethodInfo evaluateMethod = null;
ConstantWrapper cw = this.unsafeOption as ConstantWrapper;
if (cw != null)
{
string s = cw.value as string;
if (s != null && s == "unsafe")
evaluateMethod = CompilerGlobals.jScriptEvaluateMethod1;
}
if (evaluateMethod == null)
{
evaluateMethod = CompilerGlobals.jScriptEvaluateMethod2;
if (this.unsafeOption == null)
il.Emit(OpCodes.Ldnull);
else
this.unsafeOption.TranslateToIL(il, Typeob.Object);
}
this.EmitILToLoadEngine(il);
il.Emit(OpCodes.Call, evaluateMethod);
Convert.Emit(this, il, Typeob.Object, rtype);
if (this.enclosingFunctionScope != null && this.enclosingFunctionScope.owner != null)
this.enclosingFunctionScope.owner.TranslateToILToRestoreLocals(il);
}
internal override void TranslateToILInitializer(ILGenerator il)
{
this.operand.TranslateToILInitializer(il);
if (this.unsafeOption != null)
this.unsafeOption.TranslateToILInitializer(il);
}
}
}
| |
#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.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// gpr_timespec from grpc/support/time.h
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct Timespec
{
const long NanosPerSecond = 1000 * 1000 * 1000;
const long NanosPerTick = 100;
const long TicksPerSecond = NanosPerSecond / NanosPerTick;
static readonly NativeMethods Native = NativeMethods.Get();
static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
public Timespec(long tv_sec, int tv_nsec) : this(tv_sec, tv_nsec, ClockType.Realtime)
{
}
public Timespec(long tv_sec, int tv_nsec, ClockType clock_type)
{
this.tv_sec = tv_sec;
this.tv_nsec = tv_nsec;
this.clock_type = clock_type;
}
private long tv_sec;
private int tv_nsec;
private ClockType clock_type;
/// <summary>
/// Timespec a long time in the future.
/// </summary>
public static Timespec InfFuture
{
get
{
return new Timespec(long.MaxValue, 0, ClockType.Realtime);
}
}
/// <summary>
/// Timespec a long time in the past.
/// </summary>
public static Timespec InfPast
{
get
{
return new Timespec(long.MinValue, 0, ClockType.Realtime);
}
}
/// <summary>
/// Return Timespec representing the current time.
/// </summary>
public static Timespec Now
{
get
{
return Native.gprsharp_now(ClockType.Realtime);
}
}
/// <summary>
/// Seconds since unix epoch.
/// </summary>
public long TimevalSeconds
{
get
{
return tv_sec;
}
}
/// <summary>
/// The nanoseconds part of timeval.
/// </summary>
public int TimevalNanos
{
get
{
return tv_nsec;
}
}
/// <summary>
/// Converts the timespec to desired clock type.
/// </summary>
public Timespec ToClockType(ClockType targetClock)
{
return Native.gprsharp_convert_clock_type(this, targetClock);
}
/// <summary>
/// Converts Timespec to DateTime.
/// Timespec needs to be of type GPRClockType.Realtime and needs to represent a legal value.
/// DateTime has lower resolution (100ns), so rounding can occurs.
/// Value are always rounded up to the nearest DateTime value in the future.
///
/// For Timespec.InfFuture or if timespec is after the largest representable DateTime, DateTime.MaxValue is returned.
/// For Timespec.InfPast or if timespec is before the lowest representable DateTime, DateTime.MinValue is returned.
///
/// Unless DateTime.MaxValue or DateTime.MinValue is returned, the resulting DateTime is always in UTC
/// (DateTimeKind.Utc)
/// </summary>
public DateTime ToDateTime()
{
GrpcPreconditions.CheckState(tv_nsec >= 0 && tv_nsec < NanosPerSecond);
GrpcPreconditions.CheckState(clock_type == ClockType.Realtime);
// fast path for InfFuture
if (this.Equals(InfFuture))
{
return DateTime.MaxValue;
}
// fast path for InfPast
if (this.Equals(InfPast))
{
return DateTime.MinValue;
}
try
{
// convert nanos to ticks, round up to the nearest tick
long ticksFromNanos = tv_nsec / NanosPerTick + ((tv_nsec % NanosPerTick != 0) ? 1 : 0);
long ticksTotal = checked(tv_sec * TicksPerSecond + ticksFromNanos);
return UnixEpoch.AddTicks(ticksTotal);
}
catch (OverflowException)
{
// ticks out of long range
return tv_sec > 0 ? DateTime.MaxValue : DateTime.MinValue;
}
catch (ArgumentOutOfRangeException)
{
// resulting date time would be larger than MaxValue
return tv_sec > 0 ? DateTime.MaxValue : DateTime.MinValue;
}
}
/// <summary>
/// Creates DateTime to Timespec.
/// DateTime has to be in UTC (DateTimeKind.Utc) unless it's DateTime.MaxValue or DateTime.MinValue.
/// For DateTime.MaxValue of date time after the largest representable Timespec, Timespec.InfFuture is returned.
/// For DateTime.MinValue of date time before the lowest representable Timespec, Timespec.InfPast is returned.
/// </summary>
/// <returns>The date time.</returns>
/// <param name="dateTime">Date time.</param>
public static Timespec FromDateTime(DateTime dateTime)
{
if (dateTime == DateTime.MaxValue)
{
return Timespec.InfFuture;
}
if (dateTime == DateTime.MinValue)
{
return Timespec.InfPast;
}
GrpcPreconditions.CheckArgument(dateTime.Kind == DateTimeKind.Utc, "dateTime needs of kind DateTimeKind.Utc or be equal to DateTime.MaxValue or DateTime.MinValue.");
try
{
TimeSpan timeSpan = dateTime - UnixEpoch;
long ticks = timeSpan.Ticks;
long seconds = ticks / TicksPerSecond;
int nanos = (int)((ticks % TicksPerSecond) * NanosPerTick);
if (nanos < 0)
{
// correct the result based on C# modulo semantics for negative dividend
seconds--;
nanos += (int)NanosPerSecond;
}
return new Timespec(seconds, nanos);
}
catch (ArgumentOutOfRangeException)
{
return dateTime > UnixEpoch ? Timespec.InfFuture : Timespec.InfPast;
}
}
/// <summary>
/// Gets current timestamp using <c>GPRClockType.Precise</c>.
/// Only available internally because core needs to be compiled with
/// GRPC_TIMERS_RDTSC support for this to use RDTSC.
/// </summary>
internal static Timespec PreciseNow
{
get
{
return Native.gprsharp_now(ClockType.Precise);
}
}
// for tests only
internal static int NativeSize
{
get
{
return Native.gprsharp_sizeof_timespec();
}
}
// for tests only
internal static Timespec NativeInfFuture
{
get
{
return Native.gprsharp_inf_future(ClockType.Realtime);
}
}
// for tests only
public static Timespec NativeInfPast
{
get
{
return Native.gprsharp_inf_past(ClockType.Realtime);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Aspose.Cells.Common.Config;
using Aspose.Cells.Common.Controllers;
using Aspose.Cells.Common.Models;
using Aspose.Cells.Common.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Aspose.Cells.Search.Controllers
{
public class SearchApiController : CellsApiControllerBase
{
private const string AppName = "Search";
public SearchApiController(IStorageService storage, IConfiguration configuration, ILogger<SearchApiController> logger) : base(storage, configuration, logger)
{
}
[HttpPost]
public async Task<Response> Search(string query)
{
var sessionId = Guid.NewGuid().ToString();
try
{
var taskUpload = UploadWorkbooks(sessionId, AppName);
taskUpload.Wait(Configuration.MillisecondsTimeout);
if (!taskUpload.IsCompleted)
{
Logger.LogError("{AppName} UploadWorkBooks=>{SessionId}=>{ProcessingTimeout}",
AppName, sessionId, Configuration.ProcessingTimeout);
throw new TimeoutException(Configuration.ProcessingTimeout);
}
var docs = taskUpload.Result;
if (docs == null)
return PasswordProtectedResponse;
if (docs.Length == 0 || docs.Length > MaximumUploadFiles)
return MaximumFileLimitsResponse;
SetDefaultOptions(docs);
Opts.AppName = "Search";
Opts.MethodName = "Search";
Opts.ZipFileName = "SearchResults files";
Opts.FolderName = sessionId;
Opts.OutputType = ".xlsx";
Opts.ResultFileName = "SearchResults.txt";
Opts.CreateZip = false;
await Storage.UpdateStatus(Common.Models.Response.Process(Opts.FolderName, Opts.ResultFileName));
var stopWatch = new Stopwatch();
stopWatch.Start();
Logger.LogWarning("AppName = {AppName} | Filename = {Filename} | Start",
AppName, string.Join(",", docs.Select(t => t.FileName)));
var taskProcessCellsBlock = ProcessCellsBlock(docs, query);
taskProcessCellsBlock.Wait(Configuration.MillisecondsTimeout);
if (!taskProcessCellsBlock.IsCompleted)
{
Logger.LogError("{AppName} ProcessCellsBlock=>{SessionId}=>{ProcessingTimeout}",
AppName, sessionId, Configuration.ProcessingTimeout);
throw new TimeoutException(Configuration.ProcessingTimeout);
}
stopWatch.Stop();
Logger.LogWarning("AppName = {AppName} | Filename = {Filename} | Cost Seconds = {Seconds}s",
AppName, string.Join(",", docs.Select(t => t.FileName)), stopWatch.Elapsed.TotalSeconds);
if (!taskProcessCellsBlock.IsFaulted && taskProcessCellsBlock.Exception == null)
return taskProcessCellsBlock.Result;
return Common.Models.Response.Error(Opts.FolderName, Opts.ResultFileName, taskProcessCellsBlock.Exception?.Message ?? "500");
}
catch (Exception e)
{
var exception = e.InnerException ?? e;
var statusCode = 500;
if (exception is CellsException {Code: ExceptionType.IncorrectPassword})
{
statusCode = 403;
}
if (exception is CellsException {Code: ExceptionType.FileFormat})
{
statusCode = 415;
}
Logger.LogError("AppName = {AppName} | Method = {Method} | Message = {Message} | Query = {Query}",
AppName, "Search", exception.Message, query);
return new Response
{
StatusCode = statusCode,
Status = exception.Message,
FolderName = sessionId,
Text = AppName
};
}
}
private async Task<Response> ProcessCellsBlock(DocumentInfo[] docs, string query)
{
var streams = new Dictionary<string, Stream>();
var (_, outFilePath) = BeforeAction();
var catchException = false;
var exception = new Exception();
foreach (var doc in docs)
{
try
{
var dictionary = await SearchQuery(doc, query);
foreach (var (key, value) in dictionary)
{
if (streams.ContainsKey(key)) continue;
streams.Add(key, value);
}
}
catch (Exception e)
{
catchException = true;
foreach (var (_, stream) in streams)
{
stream.Close();
}
await UploadErrorFiles(docs, AppName);
exception = e.InnerException ?? e;
break;
}
}
if (!catchException)
return await AfterAction(outFilePath, streams);
if (exception is KeyNotFoundException)
{
var response = Common.Models.Response.NoSearchResults(Opts.FolderName, Opts.ResultFileName);
await Storage.UpdateStatus(response);
return response;
}
await Storage.UpdateStatus(Common.Models.Response.Error(Opts.FolderName, Opts.ResultFileName, exception.Message));
throw exception;
}
public async Task<Dictionary<string, Stream>> SearchQuery(DocumentInfo doc, string query)
{
var streams = new Dictionary<string, Stream>();
var interruptMonitor = new InterruptMonitor();
var thread = new Thread(InterruptMonitor);
try
{
Opts.FileName = doc.FileName;
Opts.FolderName = doc.FolderName;
// Load the input Excel file.
thread.Start(new object[] {interruptMonitor, Configuration.MillisecondsTimeout, Opts.FileName});
var wb = await GetWorkbook(interruptMonitor);
// Specify the find options.
// var opts = new FindOptions {LookAtType = LookAtType.Contains, LookInType = LookInType.Values};
var found = new StringBuilder();
found.AppendLine("Searched Text: " + query);
found.AppendLine("===========================================");
found.AppendLine();
// Check if found nothing
var mFoundNothing = true;
Cell cell = null;
foreach (var ws in wb.Worksheets)
{
found.AppendLine("Sheet Name: " + ws.Name);
found.AppendLine();
do
{
cell = ws.Cells.Find(query, cell);
if (cell == null)
break;
mFoundNothing = false;
found.AppendLine("Cell Name: " + cell.Name);
found.AppendLine("Cell Value: " + cell.StringValue);
found.AppendLine();
} while (true);
found.AppendLine("===========================================");
found.AppendLine();
}
if (mFoundNothing)
{
throw new KeyNotFoundException();
}
var memoryStream = new MemoryStream();
var requestWriter = new StreamWriter(memoryStream);
await requestWriter.WriteAsync(found.ToString());
await requestWriter.FlushAsync();
streams.Add(Opts.ResultFileName, memoryStream);
return streams;
}
finally
{
thread.Interrupt();
}
}
}
}
| |
//
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
// REMAINS UNCHANGED.
//
// Email: [email protected]
//
// Copyright (C) 2002-2003 Idael Cardoso.
//
using System;
using System.Runtime.InteropServices;
namespace Felix516.cdTools.Lib
{
/// <summary>
/// Wrapper class for Win32 functions and structures needed to handle CD.
/// </summary>
internal class Win32Functions
{
public enum DriveTypes:uint
{
DRIVE_UNKNOWN = 0,
DRIVE_NO_ROOT_DIR,
DRIVE_REMOVABLE,
DRIVE_FIXED,
DRIVE_REMOTE,
DRIVE_CDROM,
DRIVE_RAMDISK
};
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
public extern static DriveTypes GetDriveType(string drive);
//DesiredAccess values
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint GENERIC_EXECUTE = 0x20000000;
public const uint GENERIC_ALL = 0x10000000;
//Share constants
public const uint FILE_SHARE_READ = 0x00000001;
public const uint FILE_SHARE_WRITE = 0x00000002;
public const uint FILE_SHARE_DELETE = 0x00000004;
//CreationDisposition constants
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
public const uint OPEN_ALWAYS = 4;
public const uint TRUNCATE_EXISTING = 5;
/// <summary>
/// Win32 CreateFile function, look for complete information at Platform SDK
/// </summary>
/// <param name="FileName">In order to read CD data FileName must be "\\.\\D:" where D is the CDROM drive letter</param>
/// <param name="DesiredAccess">Must be GENERIC_READ for CDROMs others access flags are not important in this case</param>
/// <param name="ShareMode">O means exlusive access, FILE_SHARE_READ allow open the CDROM</param>
/// <param name="lpSecurityAttributes">See Platform SDK documentation for details. NULL pointer could be enough</param>
/// <param name="CreationDisposition">Must be OPEN_EXISTING for CDROM drives</param>
/// <param name="dwFlagsAndAttributes">0 in fine for this case</param>
/// <param name="hTemplateFile">NULL handle in this case</param>
/// <returns>INVALID_HANDLE_VALUE on error or the handle to file if success</returns>
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError=true)]
public extern static IntPtr CreateFile(string FileName, uint DesiredAccess,
uint ShareMode, IntPtr lpSecurityAttributes,
uint CreationDisposition, uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
/// <summary>
/// The CloseHandle function closes an open object handle.
/// </summary>
/// <param name="hObject">Handle to an open object.</param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.</returns>
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError=true)]
public extern static int CloseHandle(IntPtr hObject);
public const uint IOCTL_CDROM_READ_TOC = 0x00024000;
public const uint IOCTL_STORAGE_CHECK_VERIFY = 0x002D4800;
public const uint IOCTL_CDROM_RAW_READ = 0x0002403E;
public const uint IOCTL_STORAGE_MEDIA_REMOVAL = 0x002D4804;
public const uint IOCTL_STORAGE_EJECT_MEDIA = 0x002D4808;
public const uint IOCTL_STORAGE_LOAD_MEDIA = 0x002D480C;
/// <summary>
/// Most general form of DeviceIoControl Win32 function
/// </summary>
/// <param name="hDevice">Handle of device opened with CreateFile, <see cref="Win32Functions.CreateFile"/></param>
/// <param name="IoControlCode">Code of DeviceIoControl operation</param>
/// <param name="lpInBuffer">Pointer to a buffer that contains the data required to perform the operation.</param>
/// <param name="InBufferSize">Size of the buffer pointed to by lpInBuffer, in bytes.</param>
/// <param name="lpOutBuffer">Pointer to a buffer that receives the operation's output data.</param>
/// <param name="nOutBufferSize">Size of the buffer pointed to by lpOutBuffer, in bytes.</param>
/// <param name="lpBytesReturned">Receives the size, in bytes, of the data stored into the buffer pointed to by lpOutBuffer. </param>
/// <param name="lpOverlapped">Pointer to an OVERLAPPED structure. Discarded for this case</param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.</returns>
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError=true)]
public extern static int DeviceIoControl(IntPtr hDevice, uint IoControlCode,
IntPtr lpInBuffer, uint InBufferSize,
IntPtr lpOutBuffer, uint nOutBufferSize,
ref uint lpBytesReturned,
IntPtr lpOverlapped);
[ StructLayout( LayoutKind.Sequential )]
public struct TRACK_DATA
{
public byte Reserved;
private byte BitMapped;
public byte Control
{
get
{
return (byte)(BitMapped & 0x0F);
}
set
{
BitMapped = (byte)((BitMapped & 0xF0) | (value & (byte)0x0F));
}
}
public byte Adr
{
get
{
return (byte)((BitMapped & (byte)0xF0) >> 4);
}
set
{
BitMapped = (byte)((BitMapped & (byte)0x0F) | (value << 4));
}
}
public byte TrackNumber;
public byte Reserved1;
/// <summary>
/// Don't use array to avoid array creation
/// </summary>
public byte Address_0;
public byte Address_1;
public byte Address_2;
public byte Address_3;
};
public const int MAXIMUM_NUMBER_TRACKS = 100;
[ StructLayout( LayoutKind.Sequential )]
public class TrackDataList
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=MAXIMUM_NUMBER_TRACKS*8)]
private byte[] Data;
public TRACK_DATA this [int Index]
{
get
{
if ( (Index < 0) | (Index >= MAXIMUM_NUMBER_TRACKS))
{
throw new IndexOutOfRangeException();
}
TRACK_DATA res;
GCHandle handle = GCHandle.Alloc(Data, GCHandleType.Pinned);
try
{
IntPtr buffer = handle.AddrOfPinnedObject();
buffer = (IntPtr)(buffer.ToInt32() + (Index*Marshal.SizeOf(typeof(TRACK_DATA))));
res = (TRACK_DATA)Marshal.PtrToStructure(buffer, typeof(TRACK_DATA));
}
finally
{
handle.Free();
}
return res;
}
}
public TrackDataList()
{
Data = new byte[MAXIMUM_NUMBER_TRACKS*Marshal.SizeOf(typeof(TRACK_DATA))];
}
}
[StructLayout( LayoutKind.Sequential )]
public class CDROM_TOC
{
public ushort Length;
public byte FirstTrack = 0;
public byte LastTrack = 0;
public TrackDataList TrackData;
public CDROM_TOC()
{
TrackData = new TrackDataList();
Length = (ushort)Marshal.SizeOf(this);
}
}
[ StructLayout( LayoutKind.Sequential )]
public class PREVENT_MEDIA_REMOVAL
{
public byte PreventMediaRemoval = 0;
}
public enum TRACK_MODE_TYPE { YellowMode2, XAForm2, CDDA }
[ StructLayout( LayoutKind.Sequential )]
public class RAW_READ_INFO
{
public long DiskOffset = 0;
public uint SectorCount = 0;
public TRACK_MODE_TYPE TrackMode = TRACK_MODE_TYPE.CDDA;
}
/// <summary>
/// Overload version of DeviceIOControl to read the TOC (Table of contents)
/// </summary>
/// <param name="hDevice">Handle of device opened with CreateFile, <see cref="Win32Functions.CreateFile"/></param>
/// <param name="IoControlCode">Must be IOCTL_CDROM_READ_TOC for this overload version</param>
/// <param name="InBuffer">Must be <code>IntPtr.Zero</code> for this overload version </param>
/// <param name="InBufferSize">Must be 0 for this overload version</param>
/// <param name="OutTOC">TOC object that receive the CDROM TOC</param>
/// <param name="OutBufferSize">Must be <code>(UInt32)Marshal.SizeOf(CDROM_TOC)</code> for this overload version</param>
/// <param name="BytesReturned">Receives the size, in bytes, of the data stored into OutTOC</param>
/// <param name="Overlapped">Pointer to an OVERLAPPED structure. Discarded for this case</param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.</returns>
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError=true)]
public extern static int DeviceIoControl(IntPtr hDevice, uint IoControlCode,
IntPtr InBuffer, uint InBufferSize,
[Out] CDROM_TOC OutTOC, uint OutBufferSize,
ref uint BytesReturned,
IntPtr Overlapped);
/// <summary>
/// Overload version of DeviceIOControl to lock/unlock the CD
/// </summary>
/// <param name="hDevice">Handle of device opened with CreateFile, <see cref="Win32Functions.CreateFile"/></param>
/// <param name="IoControlCode">Must be IOCTL_STORAGE_MEDIA_REMOVAL for this overload version</param>
/// <param name="InMediaRemoval">Set the lock/unlock state</param>
/// <param name="InBufferSize">Must be <code>(UInt32)Marshal.SizeOf(PREVENT_MEDIA_REMOVAL)</code> for this overload version</param>
/// <param name="OutBuffer">Must be <code>IntPtr.Zero</code> for this overload version </param>
/// <param name="OutBufferSize">Must be 0 for this overload version</param>
/// <param name="BytesReturned">A "dummy" varible in this case</param>
/// <param name="Overlapped">Pointer to an OVERLAPPED structure. Discarded for this case</param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.</returns>
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError=true)]
public extern static int DeviceIoControl(IntPtr hDevice, uint IoControlCode,
[In] PREVENT_MEDIA_REMOVAL InMediaRemoval, uint InBufferSize,
IntPtr OutBuffer, uint OutBufferSize,
ref uint BytesReturned,
IntPtr Overlapped);
/// <summary>
/// Overload version of DeviceIOControl to read digital data
/// </summary>
/// <param name="hDevice">Handle of device opened with CreateFile, <see cref="Win32Functions.CreateFile" /></param>
/// <param name="IoControlCode">Must be IOCTL_CDROM_RAW_READ for this overload version</param>
/// <param name="rri">RAW_READ_INFO structure</param>
/// <param name="InBufferSize">Size of RAW_READ_INFO structure</param>
/// <param name="OutBuffer">Buffer that will receive the data to be read</param>
/// <param name="OutBufferSize">Size of the buffer</param>
/// <param name="BytesReturned">Receives the size, in bytes, of the data stored into OutBuffer</param>
/// <param name="Overlapped">Pointer to an OVERLAPPED structure. Discarded for this case</param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.</returns>
[System.Runtime.InteropServices.DllImport("Kernel32.dll", SetLastError=true)]
public extern static int DeviceIoControl(IntPtr hDevice, uint IoControlCode,
[In] RAW_READ_INFO rri, uint InBufferSize,
[In, Out] byte[] OutBuffer, uint OutBufferSize,
ref uint BytesReturned,
IntPtr Overlapped);
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HashCodeCombiner.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* HashCodeCombiner class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Util {
using System.Text;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Web.Security.Cryptography;
/*
* Class used to combine several hashcodes into a single hashcode
*/
internal class HashCodeCombiner {
private long _combinedHash;
internal HashCodeCombiner() {
// Start with a seed (obtained from String.GetHashCode implementation)
_combinedHash = 5381;
}
internal HashCodeCombiner(long initialCombinedHash) {
_combinedHash = initialCombinedHash;
}
internal static int CombineHashCodes(int h1, int h2) {
return ((h1 << 5) + h1) ^ h2;
}
internal static int CombineHashCodes(int h1, int h2, int h3) {
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {
return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static string GetDirectoryHash(VirtualPath virtualDir) {
HashCodeCombiner hashCodeCombiner = new HashCodeCombiner();
hashCodeCombiner.AddDirectory(virtualDir.MapPathInternal());
return hashCodeCombiner.CombinedHashString;
}
internal void AddArray(string[] a) {
if (a != null) {
int n = a.Length;
for (int i = 0; i < n; i++) {
AddObject(a[i]);
}
}
}
internal void AddInt(int n) {
_combinedHash = ((_combinedHash << 5) + _combinedHash) ^ n;
Debug.Trace("HashCodeCombiner", "Adding " + n.ToString("x") + " --> " + _combinedHash.ToString("x"));
}
internal void AddObject(int n) {
AddInt(n);
}
internal void AddObject(byte b) {
AddInt(b.GetHashCode());
}
internal void AddObject(long l) {
AddInt(l.GetHashCode());
}
internal void AddObject(bool b) {
AddInt(b.GetHashCode());
}
internal void AddObject(string s) {
if (s != null)
AddInt(StringUtil.GetStringHashCode(s));
}
internal void AddObject(Type t) {
if (t != null)
AddObject(System.Web.UI.Util.GetAssemblyQualifiedTypeName(t));
}
internal void AddObject(object o) {
if (o != null)
AddInt(o.GetHashCode());
}
internal void AddCaseInsensitiveString(string s) {
if (s != null)
AddInt(StringUtil.GetNonRandomizedHashCode(s, ignoreCase:true));
}
internal void AddDateTime(DateTime dt) {
Debug.Trace("HashCodeCombiner", "Ticks: " + dt.Ticks.ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "Hashcode: " + dt.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
AddInt(dt.GetHashCode());
}
private void AddFileSize(long fileSize) {
Debug.Trace("HashCodeCombiner", "file size: " + fileSize.ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "Hashcode: " + fileSize.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
AddInt(fileSize.GetHashCode());
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This call site is trusted.")]
private void AddFileVersionInfo(FileVersionInfo fileVersionInfo) {
Debug.Trace("HashCodeCombiner", "FileMajorPart: " + fileVersionInfo.FileMajorPart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "FileMinorPart: " + fileVersionInfo.FileMinorPart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "FileBuildPart: " + fileVersionInfo.FileBuildPart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
Debug.Trace("HashCodeCombiner", "FilePrivatePart: " + fileVersionInfo.FilePrivatePart.GetHashCode().ToString("x", CultureInfo.InvariantCulture));
AddInt(fileVersionInfo.FileMajorPart.GetHashCode());
AddInt(fileVersionInfo.FileMinorPart.GetHashCode());
AddInt(fileVersionInfo.FileBuildPart.GetHashCode());
AddInt(fileVersionInfo.FilePrivatePart.GetHashCode());
}
private void AddFileContentHashKey(string fileContentHashKey) {
AddInt(StringUtil.GetNonRandomizedHashCode(fileContentHashKey));
}
internal void AddFileContentHash(string fileName) {
// Convert file content to hash bytes
byte[] fileContentBytes = File.ReadAllBytes(fileName);
byte[] fileContentHashBytes = CryptoUtil.ComputeSHA256Hash(fileContentBytes);
// Convert byte[] to hex string representation
StringBuilder sbFileContentHashBytes = new StringBuilder();
for (int index = 0; index < fileContentHashBytes.Length; index++) {
sbFileContentHashBytes.Append(fileContentHashBytes[index].ToString("X2", CultureInfo.InvariantCulture));
}
AddFileContentHashKey(sbFileContentHashBytes.ToString());
}
internal void AddFile(string fileName) {
Debug.Trace("HashCodeCombiner", "AddFile: " + fileName);
if (!FileUtil.FileExists(fileName)) {
// Review: Should we change the dependency model to take directory into account?
if (FileUtil.DirectoryExists(fileName)) {
// Add as a directory dependency if it's a directory.
AddDirectory(fileName);
return;
}
Debug.Trace("HashCodeCombiner", "Could not find target " + fileName);
return;
}
AddExistingFile(fileName);
}
// Same as AddFile, but only called for a file which is known to exist
private void AddExistingFile(string fileName) {
Debug.Trace("HashCodeCombiner", "AddExistingFile: " + fileName);
AddInt(StringUtil.GetStringHashCode(fileName));
FileInfo file = new FileInfo(fileName);
if (!AppSettings.PortableCompilationOutput) {
AddDateTime(file.CreationTimeUtc);
}
AddDateTime(file.LastWriteTimeUtc);
AddFileSize(file.Length);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This call site is trusted.")]
internal void AddExistingFileVersion(string fileName) {
Debug.Trace("HashCodeCombiner", "AddExistingFileVersion: " + fileName);
AddInt(StringUtil.GetStringHashCode(fileName));
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(fileName);
AddFileVersionInfo(fileVersionInfo);
}
internal void AddDirectory(string directoryName) {
DirectoryInfo directory = new DirectoryInfo(directoryName);
if (!directory.Exists) {
return;
}
AddObject(directoryName);
// Go through all the files in the directory
foreach (FileData fileData in FileEnumerator.Create(directoryName)) {
if (fileData.IsDirectory)
AddDirectory(fileData.FullName);
else
AddExistingFile(fileData.FullName);
}
if (!AppSettings.PortableCompilationOutput) {
AddDateTime(directory.CreationTimeUtc);
AddDateTime(directory.LastWriteTimeUtc);
}
}
// Same as AddDirectory, but only look at files that don't have a culture
internal void AddResourcesDirectory(string directoryName) {
DirectoryInfo directory = new DirectoryInfo(directoryName);
if (!directory.Exists) {
return;
}
AddObject(directoryName);
// Go through all the files in the directory
foreach (FileData fileData in FileEnumerator.Create(directoryName)) {
if (fileData.IsDirectory)
AddResourcesDirectory(fileData.FullName);
else {
// Ignore the file if it has a culture, since only neutral files
// need to re-trigger compilation (VSWhidbey 359029)
string fullPath = fileData.FullName;
if (System.Web.UI.Util.GetCultureName(fullPath) == null) {
AddExistingFile(fullPath);
}
}
}
if (!AppSettings.PortableCompilationOutput) {
AddDateTime(directory.CreationTimeUtc);
}
}
internal long CombinedHash { get { return _combinedHash; } }
internal int CombinedHash32 { get { return _combinedHash.GetHashCode(); } }
internal string CombinedHashString {
get {
return _combinedHash.ToString("x", CultureInfo.InvariantCulture);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class TestApp
{
private static byte test_0_0(byte num, AA init, AA zero)
{
return init.q;
}
private static byte test_0_1(byte num, AA init, AA zero)
{
zero.q = num;
return zero.q;
}
private static byte test_0_2(byte num, AA init, AA zero)
{
return (byte)(init.q + zero.q);
}
private static byte test_0_3(byte num, AA init, AA zero)
{
return (byte)checked(init.q - zero.q);
}
private static byte test_0_4(byte num, AA init, AA zero)
{
zero.q += num; return zero.q;
}
private static byte test_0_5(byte num, AA init, AA zero)
{
zero.q += init.q; return zero.q;
}
private static byte test_0_6(byte num, AA init, AA zero)
{
if (init.q == num)
return 100;
else
return zero.q;
}
private static byte test_0_7(byte num, AA init, AA zero)
{
return (byte)(init.q < num + 1 ? 100 : -1);
}
private static byte test_0_8(byte num, AA init, AA zero)
{
return (byte)((init.q > zero.q ? 1 : 0) + 99);
}
private static byte test_0_9(byte num, AA init, AA zero)
{
return (byte)((init.q ^ zero.q) | num);
}
private static byte test_0_10(byte num, AA init, AA zero)
{
zero.q |= init.q;
return (byte)(zero.q & num);
}
private static byte test_0_11(byte num, AA init, AA zero)
{
return (byte)(init.q >> zero.q);
}
private static byte test_0_12(byte num, AA init, AA zero)
{
return AA.a_init[init.q].q;
}
private static byte test_0_13(byte num, AA init, AA zero)
{
return AA.aa_init[num - 100, (init.q | 1) - 2, 1 + zero.q].q;
}
private static byte test_0_14(byte num, AA init, AA zero)
{
object bb = init.q;
return (byte)bb;
}
private static byte test_0_15(byte num, AA init, AA zero)
{
double dbl = init.q;
return (byte)dbl;
}
private static byte test_0_16(byte num, AA init, AA zero)
{
return AA.call_target(init.q);
}
private static byte test_0_17(byte num, AA init, AA zero)
{
return AA.call_target_ref(ref init.q);
}
private static byte test_1_0(byte num, ref AA r_init, ref AA r_zero)
{
return r_init.q;
}
private static byte test_1_1(byte num, ref AA r_init, ref AA r_zero)
{
r_zero.q = num;
return r_zero.q;
}
private static byte test_1_2(byte num, ref AA r_init, ref AA r_zero)
{
return (byte)(r_init.q + r_zero.q);
}
private static byte test_1_3(byte num, ref AA r_init, ref AA r_zero)
{
return (byte)checked(r_init.q - r_zero.q);
}
private static byte test_1_4(byte num, ref AA r_init, ref AA r_zero)
{
r_zero.q += num; return r_zero.q;
}
private static byte test_1_5(byte num, ref AA r_init, ref AA r_zero)
{
r_zero.q += r_init.q; return r_zero.q;
}
private static byte test_1_6(byte num, ref AA r_init, ref AA r_zero)
{
if (r_init.q == num)
return 100;
else
return r_zero.q;
}
private static byte test_1_7(byte num, ref AA r_init, ref AA r_zero)
{
return (byte)(r_init.q < num + 1 ? 100 : -1);
}
private static byte test_1_8(byte num, ref AA r_init, ref AA r_zero)
{
return (byte)((r_init.q > r_zero.q ? 1 : 0) + 99);
}
private static byte test_1_9(byte num, ref AA r_init, ref AA r_zero)
{
return (byte)((r_init.q ^ r_zero.q) | num);
}
private static byte test_1_10(byte num, ref AA r_init, ref AA r_zero)
{
r_zero.q |= r_init.q;
return (byte)(r_zero.q & num);
}
private static byte test_1_11(byte num, ref AA r_init, ref AA r_zero)
{
return (byte)(r_init.q >> r_zero.q);
}
private static byte test_1_12(byte num, ref AA r_init, ref AA r_zero)
{
return AA.a_init[r_init.q].q;
}
private static byte test_1_13(byte num, ref AA r_init, ref AA r_zero)
{
return AA.aa_init[num - 100, (r_init.q | 1) - 2, 1 + r_zero.q].q;
}
private static byte test_1_14(byte num, ref AA r_init, ref AA r_zero)
{
object bb = r_init.q;
return (byte)bb;
}
private static byte test_1_15(byte num, ref AA r_init, ref AA r_zero)
{
double dbl = r_init.q;
return (byte)dbl;
}
private static byte test_1_16(byte num, ref AA r_init, ref AA r_zero)
{
return AA.call_target(r_init.q);
}
private static byte test_1_17(byte num, ref AA r_init, ref AA r_zero)
{
return AA.call_target_ref(ref r_init.q);
}
private static byte test_2_0(byte num)
{
return AA.a_init[num].q;
}
private static byte test_2_1(byte num)
{
AA.a_zero[num].q = num;
return AA.a_zero[num].q;
}
private static byte test_2_2(byte num)
{
return (byte)(AA.a_init[num].q + AA.a_zero[num].q);
}
private static byte test_2_3(byte num)
{
return (byte)checked(AA.a_init[num].q - AA.a_zero[num].q);
}
private static byte test_2_4(byte num)
{
AA.a_zero[num].q += num; return AA.a_zero[num].q;
}
private static byte test_2_5(byte num)
{
AA.a_zero[num].q += AA.a_init[num].q; return AA.a_zero[num].q;
}
private static byte test_2_6(byte num)
{
if (AA.a_init[num].q == num)
return 100;
else
return AA.a_zero[num].q;
}
private static byte test_2_7(byte num)
{
return (byte)(AA.a_init[num].q < num + 1 ? 100 : -1);
}
private static byte test_2_8(byte num)
{
return (byte)((AA.a_init[num].q > AA.a_zero[num].q ? 1 : 0) + 99);
}
private static byte test_2_9(byte num)
{
return (byte)((AA.a_init[num].q ^ AA.a_zero[num].q) | num);
}
private static byte test_2_10(byte num)
{
AA.a_zero[num].q |= AA.a_init[num].q;
return (byte)(AA.a_zero[num].q & num);
}
private static byte test_2_11(byte num)
{
return (byte)(AA.a_init[num].q >> AA.a_zero[num].q);
}
private static byte test_2_12(byte num)
{
return AA.a_init[AA.a_init[num].q].q;
}
private static byte test_2_13(byte num)
{
return AA.aa_init[num - 100, (AA.a_init[num].q | 1) - 2, 1 + AA.a_zero[num].q].q;
}
private static byte test_2_14(byte num)
{
object bb = AA.a_init[num].q;
return (byte)bb;
}
private static byte test_2_15(byte num)
{
double dbl = AA.a_init[num].q;
return (byte)dbl;
}
private static byte test_2_16(byte num)
{
return AA.call_target(AA.a_init[num].q);
}
private static byte test_2_17(byte num)
{
return AA.call_target_ref(ref AA.a_init[num].q);
}
private static byte test_3_0(byte num)
{
return AA.aa_init[0, num - 1, num / 100].q;
}
private static byte test_3_1(byte num)
{
AA.aa_zero[0, num - 1, num / 100].q = num;
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static byte test_3_2(byte num)
{
return (byte)(AA.aa_init[0, num - 1, num / 100].q + AA.aa_zero[0, num - 1, num / 100].q);
}
private static byte test_3_3(byte num)
{
return (byte)checked(AA.aa_init[0, num - 1, num / 100].q - AA.aa_zero[0, num - 1, num / 100].q);
}
private static byte test_3_4(byte num)
{
AA.aa_zero[0, num - 1, num / 100].q += num; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static byte test_3_5(byte num)
{
AA.aa_zero[0, num - 1, num / 100].q += AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q;
}
private static byte test_3_6(byte num)
{
if (AA.aa_init[0, num - 1, num / 100].q == num)
return 100;
else
return AA.aa_zero[0, num - 1, num / 100].q;
}
private static byte test_3_7(byte num)
{
return (byte)(AA.aa_init[0, num - 1, num / 100].q < num + 1 ? 100 : -1);
}
private static byte test_3_8(byte num)
{
return (byte)((AA.aa_init[0, num - 1, num / 100].q > AA.aa_zero[0, num - 1, num / 100].q ? 1 : 0) + 99);
}
private static byte test_3_9(byte num)
{
return (byte)((AA.aa_init[0, num - 1, num / 100].q ^ AA.aa_zero[0, num - 1, num / 100].q) | num);
}
private static byte test_3_10(byte num)
{
AA.aa_zero[0, num - 1, num / 100].q |= AA.aa_init[0, num - 1, num / 100].q;
return (byte)(AA.aa_zero[0, num - 1, num / 100].q & num);
}
private static byte test_3_11(byte num)
{
return (byte)(AA.aa_init[0, num - 1, num / 100].q >> AA.aa_zero[0, num - 1, num / 100].q);
}
private static byte test_3_12(byte num)
{
return AA.a_init[AA.aa_init[0, num - 1, num / 100].q].q;
}
private static byte test_3_13(byte num)
{
return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q].q;
}
private static byte test_3_14(byte num)
{
object bb = AA.aa_init[0, num - 1, num / 100].q;
return (byte)bb;
}
private static byte test_3_15(byte num)
{
double dbl = AA.aa_init[0, num - 1, num / 100].q;
return (byte)dbl;
}
private static byte test_3_16(byte num)
{
return AA.call_target(AA.aa_init[0, num - 1, num / 100].q);
}
private static byte test_3_17(byte num)
{
return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q);
}
private static byte test_4_0(byte num)
{
return BB.f_init.q;
}
private static byte test_4_1(byte num)
{
BB.f_zero.q = num;
return BB.f_zero.q;
}
private static byte test_4_2(byte num)
{
return (byte)(BB.f_init.q + BB.f_zero.q);
}
private static byte test_4_3(byte num)
{
return (byte)checked(BB.f_init.q - BB.f_zero.q);
}
private static byte test_4_4(byte num)
{
BB.f_zero.q += num; return BB.f_zero.q;
}
private static byte test_4_5(byte num)
{
BB.f_zero.q += BB.f_init.q; return BB.f_zero.q;
}
private static byte test_4_6(byte num)
{
if (BB.f_init.q == num)
return 100;
else
return BB.f_zero.q;
}
private static byte test_4_7(byte num)
{
return (byte)(BB.f_init.q < num + 1 ? 100 : -1);
}
private static byte test_4_8(byte num)
{
return (byte)((BB.f_init.q > BB.f_zero.q ? 1 : 0) + 99);
}
private static byte test_4_9(byte num)
{
return (byte)((BB.f_init.q ^ BB.f_zero.q) | num);
}
private static byte test_4_10(byte num)
{
BB.f_zero.q |= BB.f_init.q;
return (byte)(BB.f_zero.q & num);
}
private static byte test_4_11(byte num)
{
return (byte)(BB.f_init.q >> BB.f_zero.q);
}
private static byte test_4_12(byte num)
{
return AA.a_init[BB.f_init.q].q;
}
private static byte test_4_13(byte num)
{
return AA.aa_init[num - 100, (BB.f_init.q | 1) - 2, 1 + BB.f_zero.q].q;
}
private static byte test_4_14(byte num)
{
object bb = BB.f_init.q;
return (byte)bb;
}
private static byte test_4_15(byte num)
{
double dbl = BB.f_init.q;
return (byte)dbl;
}
private static byte test_4_16(byte num)
{
return AA.call_target(BB.f_init.q);
}
private static byte test_4_17(byte num)
{
return AA.call_target_ref(ref BB.f_init.q);
}
private static byte test_5_0(byte num)
{
return ((AA)AA.b_init).q;
}
private static byte test_6_0(byte num, TypedReference tr_init)
{
return __refvalue(tr_init, AA).q;
}
private static unsafe int Main()
{
AA.reset();
if (test_0_0(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_0() failed.");
return 101;
}
AA.verify_all(); AA.reset();
if (test_0_1(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_1() failed.");
return 102;
}
AA.verify_all(); AA.reset();
if (test_0_2(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_2() failed.");
return 103;
}
AA.verify_all(); AA.reset();
if (test_0_3(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_3() failed.");
return 104;
}
AA.verify_all(); AA.reset();
if (test_0_4(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_4() failed.");
return 105;
}
AA.verify_all(); AA.reset();
if (test_0_5(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_5() failed.");
return 106;
}
AA.verify_all(); AA.reset();
if (test_0_6(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_6() failed.");
return 107;
}
AA.verify_all(); AA.reset();
if (test_0_7(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_7() failed.");
return 108;
}
AA.verify_all(); AA.reset();
if (test_0_8(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_8() failed.");
return 109;
}
AA.verify_all(); AA.reset();
if (test_0_9(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_9() failed.");
return 110;
}
AA.verify_all(); AA.reset();
if (test_0_10(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_10() failed.");
return 111;
}
AA.verify_all(); AA.reset();
if (test_0_11(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_11() failed.");
return 112;
}
AA.verify_all(); AA.reset();
if (test_0_12(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_12() failed.");
return 113;
}
AA.verify_all(); AA.reset();
if (test_0_13(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_13() failed.");
return 114;
}
AA.verify_all(); AA.reset();
if (test_0_14(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_14() failed.");
return 115;
}
AA.verify_all(); AA.reset();
if (test_0_15(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_15() failed.");
return 116;
}
AA.verify_all(); AA.reset();
if (test_0_16(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_16() failed.");
return 117;
}
AA.verify_all(); AA.reset();
if (test_0_17(100, new AA(100), new AA(0)) != 100)
{
Console.WriteLine("test_0_17() failed.");
return 118;
}
AA.verify_all(); AA.reset();
if (test_1_0(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_0() failed.");
return 119;
}
AA.verify_all(); AA.reset();
if (test_1_1(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_1() failed.");
return 120;
}
AA.verify_all(); AA.reset();
if (test_1_2(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_2() failed.");
return 121;
}
AA.verify_all(); AA.reset();
if (test_1_3(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_3() failed.");
return 122;
}
AA.verify_all(); AA.reset();
if (test_1_4(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_4() failed.");
return 123;
}
AA.verify_all(); AA.reset();
if (test_1_5(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_5() failed.");
return 124;
}
AA.verify_all(); AA.reset();
if (test_1_6(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_6() failed.");
return 125;
}
AA.verify_all(); AA.reset();
if (test_1_7(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_7() failed.");
return 126;
}
AA.verify_all(); AA.reset();
if (test_1_8(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_8() failed.");
return 127;
}
AA.verify_all(); AA.reset();
if (test_1_9(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_9() failed.");
return 128;
}
AA.verify_all(); AA.reset();
if (test_1_10(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_10() failed.");
return 129;
}
AA.verify_all(); AA.reset();
if (test_1_11(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_11() failed.");
return 130;
}
AA.verify_all(); AA.reset();
if (test_1_12(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_12() failed.");
return 131;
}
AA.verify_all(); AA.reset();
if (test_1_13(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_13() failed.");
return 132;
}
AA.verify_all(); AA.reset();
if (test_1_14(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_14() failed.");
return 133;
}
AA.verify_all(); AA.reset();
if (test_1_15(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_15() failed.");
return 134;
}
AA.verify_all(); AA.reset();
if (test_1_16(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_16() failed.");
return 135;
}
AA.verify_all(); AA.reset();
if (test_1_17(100, ref AA._init, ref AA._zero) != 100)
{
Console.WriteLine("test_1_17() failed.");
return 136;
}
AA.verify_all(); AA.reset();
if (test_2_0(100) != 100)
{
Console.WriteLine("test_2_0() failed.");
return 137;
}
AA.verify_all(); AA.reset();
if (test_2_1(100) != 100)
{
Console.WriteLine("test_2_1() failed.");
return 138;
}
AA.verify_all(); AA.reset();
if (test_2_2(100) != 100)
{
Console.WriteLine("test_2_2() failed.");
return 139;
}
AA.verify_all(); AA.reset();
if (test_2_3(100) != 100)
{
Console.WriteLine("test_2_3() failed.");
return 140;
}
AA.verify_all(); AA.reset();
if (test_2_4(100) != 100)
{
Console.WriteLine("test_2_4() failed.");
return 141;
}
AA.verify_all(); AA.reset();
if (test_2_5(100) != 100)
{
Console.WriteLine("test_2_5() failed.");
return 142;
}
AA.verify_all(); AA.reset();
if (test_2_6(100) != 100)
{
Console.WriteLine("test_2_6() failed.");
return 143;
}
AA.verify_all(); AA.reset();
if (test_2_7(100) != 100)
{
Console.WriteLine("test_2_7() failed.");
return 144;
}
AA.verify_all(); AA.reset();
if (test_2_8(100) != 100)
{
Console.WriteLine("test_2_8() failed.");
return 145;
}
AA.verify_all(); AA.reset();
if (test_2_9(100) != 100)
{
Console.WriteLine("test_2_9() failed.");
return 146;
}
AA.verify_all(); AA.reset();
if (test_2_10(100) != 100)
{
Console.WriteLine("test_2_10() failed.");
return 147;
}
AA.verify_all(); AA.reset();
if (test_2_11(100) != 100)
{
Console.WriteLine("test_2_11() failed.");
return 148;
}
AA.verify_all(); AA.reset();
if (test_2_12(100) != 100)
{
Console.WriteLine("test_2_12() failed.");
return 149;
}
AA.verify_all(); AA.reset();
if (test_2_13(100) != 100)
{
Console.WriteLine("test_2_13() failed.");
return 150;
}
AA.verify_all(); AA.reset();
if (test_2_14(100) != 100)
{
Console.WriteLine("test_2_14() failed.");
return 151;
}
AA.verify_all(); AA.reset();
if (test_2_15(100) != 100)
{
Console.WriteLine("test_2_15() failed.");
return 152;
}
AA.verify_all(); AA.reset();
if (test_2_16(100) != 100)
{
Console.WriteLine("test_2_16() failed.");
return 153;
}
AA.verify_all(); AA.reset();
if (test_2_17(100) != 100)
{
Console.WriteLine("test_2_17() failed.");
return 154;
}
AA.verify_all(); AA.reset();
if (test_3_0(100) != 100)
{
Console.WriteLine("test_3_0() failed.");
return 155;
}
AA.verify_all(); AA.reset();
if (test_3_1(100) != 100)
{
Console.WriteLine("test_3_1() failed.");
return 156;
}
AA.verify_all(); AA.reset();
if (test_3_2(100) != 100)
{
Console.WriteLine("test_3_2() failed.");
return 157;
}
AA.verify_all(); AA.reset();
if (test_3_3(100) != 100)
{
Console.WriteLine("test_3_3() failed.");
return 158;
}
AA.verify_all(); AA.reset();
if (test_3_4(100) != 100)
{
Console.WriteLine("test_3_4() failed.");
return 159;
}
AA.verify_all(); AA.reset();
if (test_3_5(100) != 100)
{
Console.WriteLine("test_3_5() failed.");
return 160;
}
AA.verify_all(); AA.reset();
if (test_3_6(100) != 100)
{
Console.WriteLine("test_3_6() failed.");
return 161;
}
AA.verify_all(); AA.reset();
if (test_3_7(100) != 100)
{
Console.WriteLine("test_3_7() failed.");
return 162;
}
AA.verify_all(); AA.reset();
if (test_3_8(100) != 100)
{
Console.WriteLine("test_3_8() failed.");
return 163;
}
AA.verify_all(); AA.reset();
if (test_3_9(100) != 100)
{
Console.WriteLine("test_3_9() failed.");
return 164;
}
AA.verify_all(); AA.reset();
if (test_3_10(100) != 100)
{
Console.WriteLine("test_3_10() failed.");
return 165;
}
AA.verify_all(); AA.reset();
if (test_3_11(100) != 100)
{
Console.WriteLine("test_3_11() failed.");
return 166;
}
AA.verify_all(); AA.reset();
if (test_3_12(100) != 100)
{
Console.WriteLine("test_3_12() failed.");
return 167;
}
AA.verify_all(); AA.reset();
if (test_3_13(100) != 100)
{
Console.WriteLine("test_3_13() failed.");
return 168;
}
AA.verify_all(); AA.reset();
if (test_3_14(100) != 100)
{
Console.WriteLine("test_3_14() failed.");
return 169;
}
AA.verify_all(); AA.reset();
if (test_3_15(100) != 100)
{
Console.WriteLine("test_3_15() failed.");
return 170;
}
AA.verify_all(); AA.reset();
if (test_3_16(100) != 100)
{
Console.WriteLine("test_3_16() failed.");
return 171;
}
AA.verify_all(); AA.reset();
if (test_3_17(100) != 100)
{
Console.WriteLine("test_3_17() failed.");
return 172;
}
AA.verify_all(); AA.reset();
if (test_4_0(100) != 100)
{
Console.WriteLine("test_4_0() failed.");
return 173;
}
AA.verify_all(); AA.reset();
if (test_4_1(100) != 100)
{
Console.WriteLine("test_4_1() failed.");
return 174;
}
AA.verify_all(); AA.reset();
if (test_4_2(100) != 100)
{
Console.WriteLine("test_4_2() failed.");
return 175;
}
AA.verify_all(); AA.reset();
if (test_4_3(100) != 100)
{
Console.WriteLine("test_4_3() failed.");
return 176;
}
AA.verify_all(); AA.reset();
if (test_4_4(100) != 100)
{
Console.WriteLine("test_4_4() failed.");
return 177;
}
AA.verify_all(); AA.reset();
if (test_4_5(100) != 100)
{
Console.WriteLine("test_4_5() failed.");
return 178;
}
AA.verify_all(); AA.reset();
if (test_4_6(100) != 100)
{
Console.WriteLine("test_4_6() failed.");
return 179;
}
AA.verify_all(); AA.reset();
if (test_4_7(100) != 100)
{
Console.WriteLine("test_4_7() failed.");
return 180;
}
AA.verify_all(); AA.reset();
if (test_4_8(100) != 100)
{
Console.WriteLine("test_4_8() failed.");
return 181;
}
AA.verify_all(); AA.reset();
if (test_4_9(100) != 100)
{
Console.WriteLine("test_4_9() failed.");
return 182;
}
AA.verify_all(); AA.reset();
if (test_4_10(100) != 100)
{
Console.WriteLine("test_4_10() failed.");
return 183;
}
AA.verify_all(); AA.reset();
if (test_4_11(100) != 100)
{
Console.WriteLine("test_4_11() failed.");
return 184;
}
AA.verify_all(); AA.reset();
if (test_4_12(100) != 100)
{
Console.WriteLine("test_4_12() failed.");
return 185;
}
AA.verify_all(); AA.reset();
if (test_4_13(100) != 100)
{
Console.WriteLine("test_4_13() failed.");
return 186;
}
AA.verify_all(); AA.reset();
if (test_4_14(100) != 100)
{
Console.WriteLine("test_4_14() failed.");
return 187;
}
AA.verify_all(); AA.reset();
if (test_4_15(100) != 100)
{
Console.WriteLine("test_4_15() failed.");
return 188;
}
AA.verify_all(); AA.reset();
if (test_4_16(100) != 100)
{
Console.WriteLine("test_4_16() failed.");
return 189;
}
AA.verify_all(); AA.reset();
if (test_4_17(100) != 100)
{
Console.WriteLine("test_4_17() failed.");
return 190;
}
AA.verify_all(); AA.reset();
if (test_5_0(100) != 100)
{
Console.WriteLine("test_5_0() failed.");
return 191;
}
AA.verify_all(); AA.reset();
if (test_6_0(100, __makeref(AA._init)) != 100)
{
Console.WriteLine("test_6_0() failed.");
return 192;
}
AA.verify_all(); Console.WriteLine("All tests passed.");
return 100;
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.IO
{
public static class __Directory
{
public static IObservable<System.IO.DirectoryInfo> GetParent(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetParent(pathLambda));
}
public static IObservable<System.IO.DirectoryInfo> CreateDirectory(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.CreateDirectory(pathLambda));
}
public static IObservable<System.IO.DirectoryInfo> CreateDirectory(IObservable<System.String> path,
IObservable<System.Security.AccessControl.DirectorySecurity> directorySecurity)
{
return Observable.Zip(path, directorySecurity,
(pathLambda, directorySecurityLambda) =>
System.IO.Directory.CreateDirectory(pathLambda, directorySecurityLambda));
}
public static IObservable<System.Boolean> Exists(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.Exists(pathLambda));
}
public static IObservable<System.Reactive.Unit> SetCreationTime(IObservable<System.String> path,
IObservable<System.DateTime> creationTime)
{
return ObservableExt.ZipExecute(path, creationTime,
(pathLambda, creationTimeLambda) => System.IO.Directory.SetCreationTime(pathLambda, creationTimeLambda));
}
public static IObservable<System.Reactive.Unit> SetCreationTimeUtc(IObservable<System.String> path,
IObservable<System.DateTime> creationTimeUtc)
{
return ObservableExt.ZipExecute(path, creationTimeUtc,
(pathLambda, creationTimeUtcLambda) =>
System.IO.Directory.SetCreationTimeUtc(pathLambda, creationTimeUtcLambda));
}
public static IObservable<System.DateTime> GetCreationTime(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetCreationTime(pathLambda));
}
public static IObservable<System.DateTime> GetCreationTimeUtc(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetCreationTimeUtc(pathLambda));
}
public static IObservable<System.Reactive.Unit> SetLastWriteTime(IObservable<System.String> path,
IObservable<System.DateTime> lastWriteTime)
{
return ObservableExt.ZipExecute(path, lastWriteTime,
(pathLambda, lastWriteTimeLambda) =>
System.IO.Directory.SetLastWriteTime(pathLambda, lastWriteTimeLambda));
}
public static IObservable<System.Reactive.Unit> SetLastWriteTimeUtc(IObservable<System.String> path,
IObservable<System.DateTime> lastWriteTimeUtc)
{
return ObservableExt.ZipExecute(path, lastWriteTimeUtc,
(pathLambda, lastWriteTimeUtcLambda) =>
System.IO.Directory.SetLastWriteTimeUtc(pathLambda, lastWriteTimeUtcLambda));
}
public static IObservable<System.DateTime> GetLastWriteTime(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetLastWriteTime(pathLambda));
}
public static IObservable<System.DateTime> GetLastWriteTimeUtc(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetLastWriteTimeUtc(pathLambda));
}
public static IObservable<System.Reactive.Unit> SetLastAccessTime(IObservable<System.String> path,
IObservable<System.DateTime> lastAccessTime)
{
return ObservableExt.ZipExecute(path, lastAccessTime,
(pathLambda, lastAccessTimeLambda) =>
System.IO.Directory.SetLastAccessTime(pathLambda, lastAccessTimeLambda));
}
public static IObservable<System.Reactive.Unit> SetLastAccessTimeUtc(IObservable<System.String> path,
IObservable<System.DateTime> lastAccessTimeUtc)
{
return ObservableExt.ZipExecute(path, lastAccessTimeUtc,
(pathLambda, lastAccessTimeUtcLambda) =>
System.IO.Directory.SetLastAccessTimeUtc(pathLambda, lastAccessTimeUtcLambda));
}
public static IObservable<System.DateTime> GetLastAccessTime(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetLastAccessTime(pathLambda));
}
public static IObservable<System.DateTime> GetLastAccessTimeUtc(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetLastAccessTimeUtc(pathLambda));
}
public static IObservable<System.Security.AccessControl.DirectorySecurity> GetAccessControl(
IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetAccessControl(pathLambda));
}
public static IObservable<System.Security.AccessControl.DirectorySecurity> GetAccessControl(
IObservable<System.String> path,
IObservable<System.Security.AccessControl.AccessControlSections> includeSections)
{
return Observable.Zip(path, includeSections,
(pathLambda, includeSectionsLambda) =>
System.IO.Directory.GetAccessControl(pathLambda, includeSectionsLambda));
}
public static IObservable<System.Reactive.Unit> SetAccessControl(IObservable<System.String> path,
IObservable<System.Security.AccessControl.DirectorySecurity> directorySecurity)
{
return ObservableExt.ZipExecute(path, directorySecurity,
(pathLambda, directorySecurityLambda) =>
System.IO.Directory.SetAccessControl(pathLambda, directorySecurityLambda));
}
public static IObservable<System.String[]> GetFiles(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetFiles(pathLambda));
}
public static IObservable<System.String[]> GetFiles(IObservable<System.String> path,
IObservable<System.String> searchPattern)
{
return Observable.Zip(path, searchPattern,
(pathLambda, searchPatternLambda) => System.IO.Directory.GetFiles(pathLambda, searchPatternLambda));
}
public static IObservable<System.String[]> GetFiles(IObservable<System.String> path,
IObservable<System.String> searchPattern, IObservable<System.IO.SearchOption> searchOption)
{
return Observable.Zip(path, searchPattern, searchOption,
(pathLambda, searchPatternLambda, searchOptionLambda) =>
System.IO.Directory.GetFiles(pathLambda, searchPatternLambda, searchOptionLambda));
}
public static IObservable<System.String[]> GetDirectories(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetDirectories(pathLambda));
}
public static IObservable<System.String[]> GetDirectories(IObservable<System.String> path,
IObservable<System.String> searchPattern)
{
return Observable.Zip(path, searchPattern,
(pathLambda, searchPatternLambda) => System.IO.Directory.GetDirectories(pathLambda, searchPatternLambda));
}
public static IObservable<System.String[]> GetDirectories(IObservable<System.String> path,
IObservable<System.String> searchPattern, IObservable<System.IO.SearchOption> searchOption)
{
return Observable.Zip(path, searchPattern, searchOption,
(pathLambda, searchPatternLambda, searchOptionLambda) =>
System.IO.Directory.GetDirectories(pathLambda, searchPatternLambda, searchOptionLambda));
}
public static IObservable<System.String[]> GetFileSystemEntries(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetFileSystemEntries(pathLambda));
}
public static IObservable<System.String[]> GetFileSystemEntries(IObservable<System.String> path,
IObservable<System.String> searchPattern)
{
return Observable.Zip(path, searchPattern,
(pathLambda, searchPatternLambda) =>
System.IO.Directory.GetFileSystemEntries(pathLambda, searchPatternLambda));
}
public static IObservable<System.String[]> GetFileSystemEntries(IObservable<System.String> path,
IObservable<System.String> searchPattern, IObservable<System.IO.SearchOption> searchOption)
{
return Observable.Zip(path, searchPattern, searchOption,
(pathLambda, searchPatternLambda, searchOptionLambda) =>
System.IO.Directory.GetFileSystemEntries(pathLambda, searchPatternLambda, searchOptionLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateDirectories(
IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.EnumerateDirectories(pathLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateDirectories(
IObservable<System.String> path, IObservable<System.String> searchPattern)
{
return Observable.Zip(path, searchPattern,
(pathLambda, searchPatternLambda) =>
System.IO.Directory.EnumerateDirectories(pathLambda, searchPatternLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateDirectories(
IObservable<System.String> path, IObservable<System.String> searchPattern,
IObservable<System.IO.SearchOption> searchOption)
{
return Observable.Zip(path, searchPattern, searchOption,
(pathLambda, searchPatternLambda, searchOptionLambda) =>
System.IO.Directory.EnumerateDirectories(pathLambda, searchPatternLambda, searchOptionLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateFiles(
IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.EnumerateFiles(pathLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateFiles(
IObservable<System.String> path, IObservable<System.String> searchPattern)
{
return Observable.Zip(path, searchPattern,
(pathLambda, searchPatternLambda) => System.IO.Directory.EnumerateFiles(pathLambda, searchPatternLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateFiles(
IObservable<System.String> path, IObservable<System.String> searchPattern,
IObservable<System.IO.SearchOption> searchOption)
{
return Observable.Zip(path, searchPattern, searchOption,
(pathLambda, searchPatternLambda, searchOptionLambda) =>
System.IO.Directory.EnumerateFiles(pathLambda, searchPatternLambda, searchOptionLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateFileSystemEntries(
IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.EnumerateFileSystemEntries(pathLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateFileSystemEntries(
IObservable<System.String> path, IObservable<System.String> searchPattern)
{
return Observable.Zip(path, searchPattern,
(pathLambda, searchPatternLambda) =>
System.IO.Directory.EnumerateFileSystemEntries(pathLambda, searchPatternLambda));
}
public static IObservable<System.Collections.Generic.IEnumerable<System.String>> EnumerateFileSystemEntries(
IObservable<System.String> path, IObservable<System.String> searchPattern,
IObservable<System.IO.SearchOption> searchOption)
{
return Observable.Zip(path, searchPattern, searchOption,
(pathLambda, searchPatternLambda, searchOptionLambda) =>
System.IO.Directory.EnumerateFileSystemEntries(pathLambda, searchPatternLambda, searchOptionLambda));
}
public static IObservable<System.String[]> GetLogicalDrives()
{
return ObservableExt.Factory(() => System.IO.Directory.GetLogicalDrives());
}
public static IObservable<System.String> GetDirectoryRoot(IObservable<System.String> path)
{
return Observable.Select(path, (pathLambda) => System.IO.Directory.GetDirectoryRoot(pathLambda));
}
public static IObservable<System.String> GetCurrentDirectory()
{
return ObservableExt.Factory(() => System.IO.Directory.GetCurrentDirectory());
}
public static IObservable<System.Reactive.Unit> SetCurrentDirectory(IObservable<System.String> path)
{
return Observable.Do(path, (pathLambda) => System.IO.Directory.SetCurrentDirectory(pathLambda)).ToUnit();
}
public static IObservable<System.Reactive.Unit> Move(IObservable<System.String> sourceDirName,
IObservable<System.String> destDirName)
{
return ObservableExt.ZipExecute(sourceDirName, destDirName,
(sourceDirNameLambda, destDirNameLambda) =>
System.IO.Directory.Move(sourceDirNameLambda, destDirNameLambda));
}
public static IObservable<System.Reactive.Unit> Delete(IObservable<System.String> path)
{
return Observable.Do(path, (pathLambda) => System.IO.Directory.Delete(pathLambda)).ToUnit();
}
public static IObservable<System.Reactive.Unit> Delete(IObservable<System.String> path,
IObservable<System.Boolean> recursive)
{
return ObservableExt.ZipExecute(path, recursive,
(pathLambda, recursiveLambda) => System.IO.Directory.Delete(pathLambda, recursiveLambda));
}
}
}
| |
namespace Newq
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Attributes;
/// <summary>
/// Simulate tables in Sql.
/// </summary>
public class Table<T> : Table where T : class, new()
{
/// <summary>
/// Initializes a new instance of the <see cref="Table"/> class.
/// </summary>
public Table() : base(typeof(T))
{
}
}
/// <summary>
/// Simulate tables in Sql.
/// </summary>
public class Table : IEnumerable<Column>
{
/// <summary>
/// An dictionary used to get columns in the table.
/// </summary>
protected List<Column> columns;
/// <summary>
/// The primary key of current table.
/// </summary>
protected List<Column> primaryKey = new List<Column>();
/// <summary>
/// Initializes a new instance of the <see cref="Table"/> class.
/// </summary>
protected Table()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Table"/> class.
/// </summary>
/// <param name="type">Type of the corresponding class</param>
protected Table(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
columns = new List<Column>();
var tableAttributes = type.GetCustomAttributes(typeof(TableAttribute), false);
if (tableAttributes.Length > 0)
{
Name = ((TableAttribute)tableAttributes[0]).TableName;
}
else
{
Name = type.Name;
}
var defaultPK = "Id";
Column column = null;
object[] columnAttributes = null;
var keyProperties = type.GetProperties()
.Where(prop => prop.CanRead &&
prop.CanWrite &&
prop.PropertyType.Namespace == "System" &&
prop.CustomAttributes.Any(attr => attr.AttributeType == typeof(KeyAttribute)) &&
!prop.CustomAttributes.Any(attr => attr.AttributeType == typeof(ColumnIgnoreAttribute)));
foreach (var prop in keyProperties)
{
columnAttributes = prop.GetCustomAttributes(typeof(ColumnAttribute), false);
if (columnAttributes.Length > 0)
{
column = new Column(this, ((ColumnAttribute)columnAttributes[0]).ColumnName);
}
else
{
column = new Column(this, prop.Name);
}
columns.Add(column);
primaryKey.Add(column);
}
var properties = type.GetProperties()
.Where(prop => prop.CanRead &&
prop.CanWrite &&
prop.PropertyType.Namespace == "System" &&
!prop.CustomAttributes.Any(attr => attr.AttributeType == typeof(ColumnIgnoreAttribute)));
if (primaryKey.Count == 0 && properties.Any(p => p.Name == defaultPK))
{
column = new Column(this, defaultPK);
columns.Add(column);
}
properties = properties.Where(prop => {
var attrs = prop.GetCustomAttributes(typeof(ColumnAttribute), false);
if (attrs.Length > 0)
{
column = new Column(this, ((ColumnAttribute)columnAttributes[0]).ColumnName);
}
else
{
column = new Column(this, prop.Name);
}
return prop.Name != defaultPK &&
(attrs.Length == 0
? !primaryKey.Any(pk => pk.Name == prop.Name)
: !primaryKey.Any(pk => pk.Name == ((ColumnAttribute)columnAttributes[0]).ColumnName));
});
foreach (var prop in properties)
{
column = new Column(this, prop.Name);
columns.Add(column);
}
}
/// <summary>
/// Gets or sets <see cref="Name"/>.
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// Gets primary key of current table.
/// </summary>
public IReadOnlyList<Column> PrimaryKey
{
get { return primaryKey; }
}
/// <summary>
/// Gets <see cref="Column"/> by column name.
/// </summary>
/// <param name="columnName">name of the column</param>
/// <returns>an entity of column</returns>
public Column this[string columnName]
{
get { return columns.First(c => c.Name == columnName); }
}
/// <summary>
/// Gets <see cref="Column"/> by column name.
/// </summary>
/// <param name="columnName">name of the column</param>
/// <param name="exclude"></param>
/// <returns>an entity of column</returns>
public Column this[string columnName, Exclude exclude]
{
get
{
var column = this[columnName];
column.ExcludePattern = exclude;
return column;
}
}
/// <summary>
/// Gets <see cref="OrderByColumn"/> by column name and sort order.
/// </summary>
/// <param name="columnName">name of the column</param>
/// <param name="order"></param>
/// <returns>an entity of column</returns>
public OrderByColumn this[string columnName, SortOrder order]
{
get { return new OrderByColumn(this[columnName], order); }
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>Name of this with a pair of square brackets</returns>
public override string ToString()
{
return string.Format("[{0}]", Name);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerator<Column> GetEnumerator()
{
return columns.GetEnumerator();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Drawing
{
[SuppressUnmanagedCodeSecurity]
internal class UnsafeNativeMethods
{
[DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Auto)]
public static extern void CopyMemory(HandleRef destData, HandleRef srcData, int size);
[DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetDC", CharSet = CharSet.Auto)]
private static extern IntPtr IntGetDC(HandleRef hWnd);
public static IntPtr GetDC(HandleRef hWnd)
{
return System.Internal.HandleCollector.Add(IntGetDC(hWnd), SafeNativeMethods.CommonHandles.HDC);
}
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteDC", CharSet = CharSet.Auto)]
private static extern bool IntDeleteDC(HandleRef hDC);
public static bool DeleteDC(HandleRef hDC)
{
System.Internal.HandleCollector.Remove((IntPtr)hDC, SafeNativeMethods.CommonHandles.GDI);
return IntDeleteDC(hDC);
}
[DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = CharSet.Auto)]
private static extern int IntReleaseDC(HandleRef hWnd, HandleRef hDC);
public static int ReleaseDC(HandleRef hWnd, HandleRef hDC)
{
System.Internal.HandleCollector.Remove((IntPtr)hDC, SafeNativeMethods.CommonHandles.HDC);
return IntReleaseDC(hWnd, hDC);
}
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleDC", CharSet = CharSet.Auto)]
private static extern IntPtr IntCreateCompatibleDC(HandleRef hDC);
public static IntPtr CreateCompatibleDC(HandleRef hDC)
{
return System.Internal.HandleCollector.Add(IntCreateCompatibleDC(hDC), SafeNativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetStockObject(int nIndex);
[DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetSystemDefaultLCID();
[DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetSystemMetrics(int nIndex);
[DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
public static extern bool SystemParametersInfo(int uiAction, int uiParam, [In, Out] NativeMethods.NONCLIENTMETRICS pvParam, int fWinIni);
[DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
public static extern bool SystemParametersInfo(int uiAction, int uiParam, [In, Out] SafeNativeMethods.LOGFONT pvParam, int fWinIni);
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetDeviceCaps(HandleRef hDC, int nIndex);
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetObjectType(HandleRef hObject);
[ComImport]
[Guid("0000000C-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStream
{
int Read([In] IntPtr buf, [In] int len);
int Write([In] IntPtr buf, [In] int len);
[return: MarshalAs(UnmanagedType.I8)]
long Seek([In, MarshalAs(UnmanagedType.I8)] long dlibMove, [In] int dwOrigin);
void SetSize([In, MarshalAs(UnmanagedType.I8)] long libNewSize);
[return: MarshalAs(UnmanagedType.I8)]
long CopyTo([In, MarshalAs(UnmanagedType.Interface)] IStream pstm,
[In, MarshalAs(UnmanagedType.I8)] long cb,
[Out, MarshalAs(UnmanagedType.LPArray)] long[] pcbRead);
void Commit([In] int grfCommitFlags);
void Revert();
void LockRegion([In, MarshalAs(UnmanagedType.I8)] long libOffset,
[In, MarshalAs(UnmanagedType.I8)] long cb,
[In] int dwLockType);
void UnlockRegion([In, MarshalAs(UnmanagedType.I8)]long libOffset,
[In, MarshalAs(UnmanagedType.I8)] long cb,
[In] int dwLockType);
void Stat([In] IntPtr pStatstg, [In] int grfStatFlag);
[return: MarshalAs(UnmanagedType.Interface)]
IStream Clone();
}
internal class ComStreamFromDataStream : IStream
{
protected Stream dataStream;
// to support seeking ahead of the stream length...
private long _virtualPosition = -1;
internal ComStreamFromDataStream(Stream dataStream)
{
this.dataStream = dataStream ?? throw new ArgumentNullException("dataStream");
}
private void ActualizeVirtualPosition()
{
if (_virtualPosition == -1)
{
return;
}
if (_virtualPosition > dataStream.Length)
{
dataStream.SetLength(_virtualPosition);
}
dataStream.Position = _virtualPosition;
_virtualPosition = -1;
}
public virtual IStream Clone()
{
NotImplemented();
return null;
}
public virtual void Commit(int grfCommitFlags)
{
dataStream.Flush();
// Extend the length of the file if needed.
ActualizeVirtualPosition();
}
public virtual long CopyTo(IStream pstm, long cb, long[] pcbRead)
{
int bufsize = 4096; // one page
IntPtr buffer = Marshal.AllocHGlobal(bufsize);
if (buffer == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
long written = 0;
try
{
while (written < cb)
{
int toRead = bufsize;
if (written + toRead > cb)
{
toRead = (int)(cb - written);
}
int read = Read(buffer, toRead);
if (read == 0)
{
break;
}
if (pstm.Write(buffer, read) != read)
{
throw EFail("Wrote an incorrect number of bytes");
}
written += read;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
if (pcbRead != null && pcbRead.Length > 0)
{
pcbRead[0] = written;
}
return written;
}
public virtual void LockRegion(long libOffset, long cb, int dwLockType)
{
}
protected static ExternalException EFail(string msg)
{
throw new ExternalException(msg, SafeNativeMethods.E_FAIL);
}
protected static void NotImplemented()
{
throw new ExternalException(SR.Format(SR.NotImplemented), SafeNativeMethods.E_NOTIMPL);
}
public virtual int Read(IntPtr buf, int length)
{
byte[] buffer = new byte[length];
int count = Read(buffer, length);
Marshal.Copy(buffer, 0, buf, length);
return count;
}
public virtual int Read(byte[] buffer, int length)
{
ActualizeVirtualPosition();
return dataStream.Read(buffer, 0, length);
}
public virtual void Revert() => NotImplemented();
public virtual long Seek(long offset, int origin)
{
long pos = _virtualPosition;
if (_virtualPosition == -1)
{
pos = dataStream.Position;
}
long len = dataStream.Length;
switch (origin)
{
case SafeNativeMethods.StreamConsts.STREAM_SEEK_SET:
if (offset <= len)
{
dataStream.Position = offset;
_virtualPosition = -1;
}
else
{
_virtualPosition = offset;
}
break;
case SafeNativeMethods.StreamConsts.STREAM_SEEK_END:
if (offset <= 0)
{
dataStream.Position = len + offset;
_virtualPosition = -1;
}
else
{
_virtualPosition = len + offset;
}
break;
case SafeNativeMethods.StreamConsts.STREAM_SEEK_CUR:
if (offset + pos <= len)
{
dataStream.Position = pos + offset;
_virtualPosition = -1;
}
else
{
_virtualPosition = offset + pos;
}
break;
}
if (_virtualPosition != -1)
{
return _virtualPosition;
}
else
{
return dataStream.Position;
}
}
public virtual void SetSize(long value) => dataStream.SetLength(value);
/// <summary>
/// GpStream has a partial implementation, but it's so partial rather
/// restrict it to use with GDI+.
/// </summary>
public virtual void Stat(IntPtr pstatstg, int grfStatFlag) => NotImplemented();
public virtual void UnlockRegion(long libOffset, long cb, int dwLockType)
{
}
public virtual int Write(IntPtr buf, int length)
{
byte[] buffer = new byte[length];
Marshal.Copy(buf, buffer, 0, length);
return Write(buffer, length);
}
public virtual int Write(byte[] buffer, int length)
{
ActualizeVirtualPosition();
dataStream.Write(buffer, 0, length);
return length;
}
}
}
}
| |
namespace Devoldere.NetSpeedTray.Views
{
partial class FrmLegacy
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmLegacy));
this.lblSrLbl = new System.Windows.Forms.Label();
this.lblSrUp = new System.Windows.Forms.Label();
this.oTimer = new System.Windows.Forms.Timer(this.components);
this.lblDlLbl = new System.Windows.Forms.Label();
this.lblDl = new System.Windows.Forms.Label();
this.lblUl = new System.Windows.Forms.Label();
this.cbNotify = new System.Windows.Forms.CheckBox();
this.lblName = new System.Windows.Forms.Label();
this.oMenu = new System.Windows.Forms.MenuStrip();
this.menuFile = new System.Windows.Forms.ToolStripMenuItem();
this.menuReload = new System.Windows.Forms.ToolStripMenuItem();
this.menuExit = new System.Windows.Forms.ToolStripMenuItem();
this.menuAbout = new System.Windows.Forms.ToolStripMenuItem();
this.menuInterfaces = new System.Windows.Forms.ToolStripMenuItem();
this.oNotify = new System.Windows.Forms.NotifyIcon(this.components);
this.oContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.Exit = new System.Windows.Forms.ToolStripMenuItem();
this.lblSrDown = new System.Windows.Forms.Label();
this.lblSpeedLbl = new System.Windows.Forms.Label();
this.lblSpace = new System.Windows.Forms.Label();
this.lblUlLbl = new System.Windows.Forms.Label();
this.LblBytesLbl = new System.Windows.Forms.Label();
this.lblBytesUp = new System.Windows.Forms.Label();
this.lblBytesDown = new System.Windows.Forms.Label();
this.oMenu.SuspendLayout();
this.oContextMenu.SuspendLayout();
this.SuspendLayout();
//
// lblSrLbl
//
this.lblSrLbl.BackColor = System.Drawing.SystemColors.Info;
this.lblSrLbl.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblSrLbl.Location = new System.Drawing.Point(3, 98);
this.lblSrLbl.Name = "lblSrLbl";
this.lblSrLbl.Size = new System.Drawing.Size(44, 16);
this.lblSrLbl.TabIndex = 2;
this.lblSrLbl.Text = "Packets";
this.lblSrLbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblSrUp
//
this.lblSrUp.BackColor = System.Drawing.SystemColors.Info;
this.lblSrUp.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblSrUp.ForeColor = System.Drawing.Color.DarkGreen;
this.lblSrUp.Location = new System.Drawing.Point(48, 98);
this.lblSrUp.Name = "lblSrUp";
this.lblSrUp.Size = new System.Drawing.Size(80, 16);
this.lblSrUp.TabIndex = 4;
this.lblSrUp.Text = "0";
this.lblSrUp.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// oTimer
//
this.oTimer.Enabled = true;
this.oTimer.Interval = 1000;
this.oTimer.Tick += new System.EventHandler(this.tmrRefresh_Tick);
//
// lblDlLbl
//
this.lblDlLbl.BackColor = System.Drawing.SystemColors.Info;
this.lblDlLbl.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblDlLbl.ForeColor = System.Drawing.Color.DarkRed;
this.lblDlLbl.Location = new System.Drawing.Point(129, 81);
this.lblDlLbl.Name = "lblDlLbl";
this.lblDlLbl.Size = new System.Drawing.Size(80, 16);
this.lblDlLbl.TabIndex = 6;
this.lblDlLbl.Text = "Down";
this.lblDlLbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lblDl
//
this.lblDl.BackColor = System.Drawing.SystemColors.Info;
this.lblDl.Font = new System.Drawing.Font("Segoe UI Semibold", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblDl.ForeColor = System.Drawing.Color.DarkRed;
this.lblDl.Location = new System.Drawing.Point(129, 132);
this.lblDl.Name = "lblDl";
this.lblDl.Size = new System.Drawing.Size(80, 16);
this.lblDl.TabIndex = 8;
this.lblDl.Text = "0";
this.lblDl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// lblUl
//
this.lblUl.BackColor = System.Drawing.SystemColors.Info;
this.lblUl.Font = new System.Drawing.Font("Segoe UI Semibold", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblUl.ForeColor = System.Drawing.Color.DarkGreen;
this.lblUl.Location = new System.Drawing.Point(48, 132);
this.lblUl.Name = "lblUl";
this.lblUl.Size = new System.Drawing.Size(80, 16);
this.lblUl.TabIndex = 9;
this.lblUl.Text = "0";
this.lblUl.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// cbNotify
//
this.cbNotify.AutoSize = true;
this.cbNotify.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cbNotify.Location = new System.Drawing.Point(139, 2);
this.cbNotify.Margin = new System.Windows.Forms.Padding(2);
this.cbNotify.Name = "cbNotify";
this.cbNotify.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.cbNotify.Size = new System.Drawing.Size(59, 19);
this.cbNotify.TabIndex = 10;
this.cbNotify.Text = "Notify";
this.cbNotify.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.cbNotify.UseVisualStyleBackColor = true;
//
// lblName
//
this.lblName.BackColor = System.Drawing.SystemColors.Control;
this.lblName.Font = new System.Drawing.Font("Segoe UI", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblName.ForeColor = System.Drawing.Color.DimGray;
this.lblName.Location = new System.Drawing.Point(4, 23);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(205, 57);
this.lblName.TabIndex = 11;
this.lblName.Text = "Network";
this.lblName.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// oMenu
//
this.oMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuFile,
this.menuInterfaces});
this.oMenu.Location = new System.Drawing.Point(0, 0);
this.oMenu.Name = "oMenu";
this.oMenu.Padding = new System.Windows.Forms.Padding(4, 2, 0, 2);
this.oMenu.Size = new System.Drawing.Size(212, 24);
this.oMenu.TabIndex = 12;
this.oMenu.Text = "Menu";
//
// menuFile
//
this.menuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuReload,
this.menuExit,
this.menuAbout});
this.menuFile.Name = "menuFile";
this.menuFile.Size = new System.Drawing.Size(37, 20);
this.menuFile.Text = "File";
//
// menuReload
//
this.menuReload.Image = global::Devoldere.NetSpeedTray.Properties.Resources.Refresh;
this.menuReload.Name = "menuReload";
this.menuReload.Size = new System.Drawing.Size(110, 22);
this.menuReload.Text = "Reload";
this.menuReload.Click += new System.EventHandler(this.ReloadApp);
//
// menuExit
//
this.menuExit.Image = global::Devoldere.NetSpeedTray.Properties.Resources.Close;
this.menuExit.Name = "menuExit";
this.menuExit.Size = new System.Drawing.Size(110, 22);
this.menuExit.Text = "Exit";
this.menuExit.Click += new System.EventHandler(this.CloseApp);
//
// menuAbout
//
this.menuAbout.Image = global::Devoldere.NetSpeedTray.Properties.Resources._2bs;
this.menuAbout.Name = "menuAbout";
this.menuAbout.Size = new System.Drawing.Size(110, 22);
this.menuAbout.Text = "About";
this.menuAbout.Click += new System.EventHandler(this.AboutApp);
//
// menuInterfaces
//
this.menuInterfaces.Name = "menuInterfaces";
this.menuInterfaces.Size = new System.Drawing.Size(70, 20);
this.menuInterfaces.Text = "Interfaces";
//
// oNotify
//
this.oNotify.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
this.oNotify.BalloonTipTitle = "Devoldere NetSpeed";
this.oNotify.Icon = ((System.Drawing.Icon)(resources.GetObject("oNotify.Icon")));
this.oNotify.Text = "NetSpeedTray";
this.oNotify.Visible = true;
this.oNotify.MouseClick += new System.Windows.Forms.MouseEventHandler(this.notifyIcon_MouseClick);
//
// oContextMenu
//
this.oContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.Exit});
this.oContextMenu.Name = "contextMenuStrip1";
this.oContextMenu.Size = new System.Drawing.Size(163, 26);
//
// Exit
//
this.Exit.Name = "Exit";
this.Exit.Size = new System.Drawing.Size(162, 22);
this.Exit.Text = "contextMenuExit";
//
// lblSrDown
//
this.lblSrDown.BackColor = System.Drawing.SystemColors.Info;
this.lblSrDown.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblSrDown.ForeColor = System.Drawing.Color.DarkRed;
this.lblSrDown.Location = new System.Drawing.Point(129, 98);
this.lblSrDown.Name = "lblSrDown";
this.lblSrDown.Size = new System.Drawing.Size(80, 16);
this.lblSrDown.TabIndex = 13;
this.lblSrDown.Text = "0";
this.lblSrDown.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// lblSpeedLbl
//
this.lblSpeedLbl.BackColor = System.Drawing.SystemColors.Info;
this.lblSpeedLbl.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblSpeedLbl.Location = new System.Drawing.Point(3, 132);
this.lblSpeedLbl.Name = "lblSpeedLbl";
this.lblSpeedLbl.Size = new System.Drawing.Size(44, 16);
this.lblSpeedLbl.TabIndex = 14;
this.lblSpeedLbl.Text = "Speed";
this.lblSpeedLbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblSpace
//
this.lblSpace.BackColor = System.Drawing.SystemColors.Info;
this.lblSpace.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblSpace.Location = new System.Drawing.Point(3, 81);
this.lblSpace.Name = "lblSpace";
this.lblSpace.Size = new System.Drawing.Size(44, 16);
this.lblSpace.TabIndex = 15;
this.lblSpace.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// lblUlLbl
//
this.lblUlLbl.BackColor = System.Drawing.SystemColors.Info;
this.lblUlLbl.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblUlLbl.ForeColor = System.Drawing.Color.DarkGreen;
this.lblUlLbl.Location = new System.Drawing.Point(48, 81);
this.lblUlLbl.Name = "lblUlLbl";
this.lblUlLbl.Size = new System.Drawing.Size(80, 16);
this.lblUlLbl.TabIndex = 7;
this.lblUlLbl.Text = "Up";
this.lblUlLbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// LblBytesLbl
//
this.LblBytesLbl.BackColor = System.Drawing.SystemColors.Info;
this.LblBytesLbl.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LblBytesLbl.Location = new System.Drawing.Point(3, 115);
this.LblBytesLbl.Name = "LblBytesLbl";
this.LblBytesLbl.Size = new System.Drawing.Size(44, 16);
this.LblBytesLbl.TabIndex = 18;
this.LblBytesLbl.Text = "Bytes";
this.LblBytesLbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblBytesUp
//
this.lblBytesUp.BackColor = System.Drawing.SystemColors.Info;
this.lblBytesUp.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblBytesUp.ForeColor = System.Drawing.Color.DarkGreen;
this.lblBytesUp.Location = new System.Drawing.Point(48, 115);
this.lblBytesUp.Name = "lblBytesUp";
this.lblBytesUp.Size = new System.Drawing.Size(80, 16);
this.lblBytesUp.TabIndex = 17;
this.lblBytesUp.Text = "0";
this.lblBytesUp.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// lblBytesDown
//
this.lblBytesDown.BackColor = System.Drawing.SystemColors.Info;
this.lblBytesDown.Font = new System.Drawing.Font("Segoe UI Semibold", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblBytesDown.ForeColor = System.Drawing.Color.DarkRed;
this.lblBytesDown.Location = new System.Drawing.Point(129, 115);
this.lblBytesDown.Name = "lblBytesDown";
this.lblBytesDown.Size = new System.Drawing.Size(80, 16);
this.lblBytesDown.TabIndex = 16;
this.lblBytesDown.Text = "0";
this.lblBytesDown.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// FrmLegacy
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(212, 152);
this.Controls.Add(this.LblBytesLbl);
this.Controls.Add(this.lblBytesUp);
this.Controls.Add(this.lblBytesDown);
this.Controls.Add(this.lblSpace);
this.Controls.Add(this.lblSpeedLbl);
this.Controls.Add(this.lblSrDown);
this.Controls.Add(this.lblName);
this.Controls.Add(this.cbNotify);
this.Controls.Add(this.lblUl);
this.Controls.Add(this.lblDl);
this.Controls.Add(this.lblUlLbl);
this.Controls.Add(this.lblDlLbl);
this.Controls.Add(this.lblSrUp);
this.Controls.Add(this.lblSrLbl);
this.Controls.Add(this.oMenu);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = global::Devoldere.NetSpeedTray.Properties.Resources.scroll;
this.MainMenuStrip = this.oMenu;
this.MaximizeBox = false;
this.Name = "FrmLegacy";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Devoldere NetSpeed";
this.TopMost = true;
this.oMenu.ResumeLayout(false);
this.oMenu.PerformLayout();
this.oContextMenu.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblSrLbl;
private System.Windows.Forms.Label lblSrUp;
private System.Windows.Forms.Timer oTimer;
private System.Windows.Forms.Label lblDlLbl;
private System.Windows.Forms.Label lblDl;
private System.Windows.Forms.Label lblUl;
private System.Windows.Forms.CheckBox cbNotify;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.MenuStrip oMenu;
private System.Windows.Forms.ToolStripMenuItem menuFile;
private System.Windows.Forms.ToolStripMenuItem menuReload;
private System.Windows.Forms.ToolStripMenuItem menuInterfaces;
private System.Windows.Forms.ToolStripMenuItem menuExit;
private System.Windows.Forms.NotifyIcon oNotify;
private System.Windows.Forms.ContextMenuStrip oContextMenu;
private System.Windows.Forms.ToolStripMenuItem Exit;
private System.Windows.Forms.Label lblSrDown;
private System.Windows.Forms.Label lblSpeedLbl;
private System.Windows.Forms.Label lblSpace;
private System.Windows.Forms.Label lblUlLbl;
private System.Windows.Forms.Label LblBytesLbl;
private System.Windows.Forms.Label lblBytesUp;
private System.Windows.Forms.Label lblBytesDown;
private System.Windows.Forms.ToolStripMenuItem menuAbout;
}
}
| |
#if NET_45
using System.Collections.Generic;
#endif
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// A client for GitHub's Repositories API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/">Repositories API documentation</a> for more details.
/// </remarks>
public interface IRepositoriesClient
{
/// <summary>
/// Client for managing pull requests.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details
/// </remarks>
IPullRequestsClient PullRequest { get; }
/// <summary>
/// Client for managing commit comments in a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information.
/// </remarks>
IRepositoryCommentsClient RepositoryComments { get; }
/// <summary>
/// Creates a new repository for the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
/// </remarks>
/// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/> instance for the created repository.</returns>
Task<Repository> Create(NewRepository newRepository);
/// <summary>
/// Creates a new repository in the specified organization.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
/// </remarks>
/// <param name="organizationLogin">Login of the organization in which to create the repostiory</param>
/// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/> instance for the created repository</returns>
Task<Repository> Create(string organizationLogin, NewRepository newRepository);
/// <summary>
/// Deletes the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information.
/// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
Task Delete(string owner, string name);
/// <summary>
/// Gets the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/></returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
Task<Repository> Get(string owner, string name);
/// <summary>
/// Gets all repositories owned by the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForCurrent();
/// <summary>
/// Gets all repositories owned by the specified user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForUser(string login);
/// <summary>
/// Gets all repositories owned by the specified organization.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForOrg(string organization);
/// <summary>
/// Gets the preferred README for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/contents/#get-the-readme">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns></returns>
Task<Readme> GetReadme(string owner, string name);
/// <summary>
/// Gets the perferred README's HTML for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/contents/#get-the-readme">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns></returns>
Task<string> GetReadmeHtml(string owner, string name);
/// <summary>
/// A client for GitHub's Commit Status API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more
/// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a>
/// that announced this feature.
/// </remarks>
ICommitStatusClient CommitStatus { get; }
/// <summary>
/// A client for GitHub's Repo Collaborators.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details
/// </remarks>
IRepoCollaboratorsClient RepoCollaborators { get; }
/// <summary>
/// Client for GitHub's Repository Deployments API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/deployment/">Collaborators API documentation</a> for more details
/// </remarks>
IDeploymentsClient Deployment { get; }
/// <summary>
/// Client for GitHub's Repository Statistics API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details
///</remarks>
IStatisticsClient Statistics { get; }
/// <summary>
/// Client for GitHub's Repository Commits API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details
///</remarks>
IRepositoryCommitsClient Commits { get; }
/// <summary>
/// Gets all the branches for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns>
Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name);
/// <summary>
/// Gets all contributors for the specified repository. Does not include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<User>> GetAllContributors(string owner, string name);
/// <summary>
/// Gets all contributors for the specified repository. With the option to include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<User>> GetAllContributors(string owner, string name, bool includeAnonymous);
/// <summary>
/// Gets all languages for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All languages used in the repository and the number of bytes of each language.</returns>
Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(string owner, string name);
/// <summary>
/// Gets all teams for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns>
Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name);
/// <summary>
/// Gets all tags for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All of the repositorys tags.</returns>
Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name);
/// <summary>
/// Gets the specified branch.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="repositoryName">The name of the repository</param>
/// <param name="branchName">The name of the branch</param>
/// <returns>The specified <see cref="T:Octokit.Branch"/></returns>
Task<Branch> GetBranch(string owner, string repositoryName, string branchName);
/// <summary>
/// Updates the specified repository with the values given in <paramref name="update"/>
/// </summary>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="update">New values to update the repository with</param>
/// <returns>The updated <see cref="T:Octokit.Repository"/></returns>
Task<Repository> Edit(string owner, string name, RepositoryUpdate update);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class Vector3Tests
{
[Fact]
public void Vector3MarshalSizeTest()
{
Assert.Equal(12, Marshal.SizeOf<Vector3>());
Assert.Equal(12, Marshal.SizeOf<Vector3>(new Vector3()));
}
[Fact]
public void Vector3CopyToTest()
{
Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f);
float[] a = new float[4];
float[] b = new float[3];
Assert.Throws<ArgumentNullException>(() => v1.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length));
Assert.Throws<ArgumentException>(() => v1.CopyTo(a, a.Length - 2));
v1.CopyTo(a, 1);
v1.CopyTo(b);
Assert.Equal(0.0f, a[0]);
Assert.Equal(2.0f, a[1]);
Assert.Equal(3.0f, a[2]);
Assert.Equal(3.3f, a[3]);
Assert.Equal(2.0f, b[0]);
Assert.Equal(3.0f, b[1]);
Assert.Equal(3.3f, b[2]);
}
[Fact]
public void Vector3GetHashCodeTest()
{
Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f);
Vector3 v2 = new Vector3(4.5f, 6.5f, 7.5f);
Vector3 v3 = new Vector3(2.0f, 3.0f, 3.3f);
Vector3 v5 = new Vector3(3.0f, 2.0f, 3.3f);
Assert.True(v1.GetHashCode() == v1.GetHashCode());
Assert.False(v1.GetHashCode() == v5.GetHashCode());
Assert.True(v1.GetHashCode() == v3.GetHashCode());
Vector3 v4 = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 v6 = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 v7 = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 v8 = new Vector3(1.0f, 1.0f, 1.0f);
Vector3 v9 = new Vector3(1.0f, 1.0f, 0.0f);
Assert.False(v4.GetHashCode() == v6.GetHashCode());
Assert.False(v4.GetHashCode() == v7.GetHashCode());
Assert.False(v4.GetHashCode() == v8.GetHashCode());
Assert.False(v7.GetHashCode() == v6.GetHashCode());
Assert.False(v8.GetHashCode() == v6.GetHashCode());
Assert.True(v8.GetHashCode() == v7.GetHashCode());
Assert.False(v8.GetHashCode() == v9.GetHashCode());
Assert.False(v7.GetHashCode() == v9.GetHashCode());
}
[Fact]
public void Vector3ToStringTest()
{
string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
CultureInfo enUsCultureInfo = new CultureInfo("en-US");
Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f);
string v1str = v1.ToString();
string expectedv1 = string.Format(CultureInfo.CurrentCulture
, "<{1:G}{0} {2:G}{0} {3:G}>"
, separator, 2, 3, 3.3);
Assert.Equal(expectedv1, v1str);
string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture);
string expectedv1formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}{0} {3:c}>"
, separator, 2, 3, 3.3);
Assert.Equal(expectedv1formatted, v1strformatted);
string v2strformatted = v1.ToString("c", enUsCultureInfo);
string expectedv2formatted = string.Format(enUsCultureInfo
, "<{1:c}{0} {2:c}{0} {3:c}>"
, enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3, 3.3);
Assert.Equal(expectedv2formatted, v2strformatted);
string v3strformatted = v1.ToString("c");
string expectedv3formatted = string.Format(CultureInfo.CurrentCulture
, "<{1:c}{0} {2:c}{0} {3:c}>"
, separator, 2, 3, 3.3);
Assert.Equal(expectedv3formatted, v3strformatted);
}
// A test for Cross (Vector3f, Vector3f)
[Fact]
public void Vector3CrossTest()
{
Vector3 a = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 actual;
actual = Vector3.Cross(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value.");
}
// A test for Cross (Vector3f, Vector3f)
// Cross test of the same vector
[Fact]
public void Vector3CrossTest1()
{
Vector3 a = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 b = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Cross(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value.");
}
// A test for Distance (Vector3f, Vector3f)
[Fact]
public void Vector3DistanceTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = (float)System.Math.Sqrt(27);
float actual;
actual = Vector3.Distance(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Distance did not return the expected value.");
}
// A test for Distance (Vector3f, Vector3f)
// Distance from the same point
[Fact]
public void Vector3DistanceTest1()
{
Vector3 a = new Vector3(1.051f, 2.05f, 3.478f);
Vector3 b = new Vector3(new Vector2(1.051f, 0.0f), 1);
b.Y = 2.05f;
b.Z = 3.478f;
float actual = Vector3.Distance(a, b);
Assert.Equal(0.0f, actual);
}
// A test for DistanceSquared (Vector3f, Vector3f)
[Fact]
public void Vector3DistanceSquaredTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = 27.0f;
float actual;
actual = Vector3.DistanceSquared(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.DistanceSquared did not return the expected value.");
}
// A test for Dot (Vector3f, Vector3f)
[Fact]
public void Vector3DotTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = 32.0f;
float actual;
actual = Vector3.Dot(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Dot did not return the expected value.");
}
// A test for Dot (Vector3f, Vector3f)
// Dot test for perpendicular vector
[Fact]
public void Vector3DotTest1()
{
Vector3 a = new Vector3(1.55f, 1.55f, 1);
Vector3 b = new Vector3(2.5f, 3, 1.5f);
Vector3 c = Vector3.Cross(a, b);
float expected = 0.0f;
float actual1 = Vector3.Dot(a, c);
float actual2 = Vector3.Dot(b, c);
Assert.True(MathHelper.Equal(expected, actual1), "Vector3f.Dot did not return the expected value.");
Assert.True(MathHelper.Equal(expected, actual2), "Vector3f.Dot did not return the expected value.");
}
// A test for Length ()
[Fact]
public void Vector3LengthTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
float expected = (float)System.Math.Sqrt(14.0f);
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value.");
}
// A test for Length ()
// Length test where length is zero
[Fact]
public void Vector3LengthTest1()
{
Vector3 target = new Vector3();
float expected = 0.0f;
float actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value.");
}
// A test for LengthSquared ()
[Fact]
public void Vector3LengthSquaredTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
float expected = 14.0f;
float actual;
actual = target.LengthSquared();
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.LengthSquared did not return the expected value.");
}
// A test for Min (Vector3f, Vector3f)
[Fact]
public void Vector3MinTest()
{
Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f);
Vector3 b = new Vector3(2.0f, 1.0f, -1.0f);
Vector3 expected = new Vector3(-1.0f, 1.0f, -3.0f);
Vector3 actual;
actual = Vector3.Min(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Min did not return the expected value.");
}
// A test for Max (Vector3f, Vector3f)
[Fact]
public void Vector3MaxTest()
{
Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f);
Vector3 b = new Vector3(2.0f, 1.0f, -1.0f);
Vector3 expected = new Vector3(2.0f, 4.0f, -1.0f);
Vector3 actual;
actual = Vector3.Max(a, b);
Assert.True(MathHelper.Equal(expected, actual), "vector3.Max did not return the expected value.");
}
[Fact]
public void Vector3MinMaxCodeCoverageTest()
{
Vector3 min = Vector3.Zero;
Vector3 max = Vector3.One;
Vector3 actual;
// Min.
actual = Vector3.Min(min, max);
Assert.Equal(actual, min);
actual = Vector3.Min(max, min);
Assert.Equal(actual, min);
// Max.
actual = Vector3.Max(min, max);
Assert.Equal(actual, max);
actual = Vector3.Max(max, min);
Assert.Equal(actual, max);
}
// A test for Lerp (Vector3f, Vector3f, float)
[Fact]
public void Vector3LerpTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 0.5f;
Vector3 expected = new Vector3(2.5f, 3.5f, 4.5f);
Vector3 actual;
actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor zero
[Fact]
public void Vector3LerpTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 0.0f;
Vector3 expected = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor one
[Fact]
public void Vector3LerpTest2()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 1.0f;
Vector3 expected = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor > 1
[Fact]
public void Vector3LerpTest3()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 2.0f;
Vector3 expected = new Vector3(8.0f, 10.0f, 12.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test with factor < 0
[Fact]
public void Vector3LerpTest4()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = -2.0f;
Vector3 expected = new Vector3(-8.0f, -10.0f, -12.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3f, Vector3f, float)
// Lerp test from the same point
[Fact]
public void Vector3LerpTest5()
{
Vector3 a = new Vector3(1.68f, 2.34f, 5.43f);
Vector3 b = a;
float t = 0.18f;
Vector3 expected = new Vector3(1.68f, 2.34f, 5.43f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
[Fact]
public void Vector3ReflectTest()
{
Vector3 a = Vector3.Normalize(new Vector3(1.0f, 1.0f, 1.0f));
// Reflect on XZ plane.
Vector3 n = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(a.X, -a.Y, a.Z);
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
// Reflect on XY plane.
n = new Vector3(0.0f, 0.0f, 1.0f);
expected = new Vector3(a.X, a.Y, -a.Z);
actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
// Reflect on YZ plane.
n = new Vector3(1.0f, 0.0f, 0.0f);
expected = new Vector3(-a.X, a.Y, a.Z);
actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
// Reflection when normal and source are the same
[Fact]
public void Vector3ReflectTest1()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
n = Vector3.Normalize(n);
Vector3 a = n;
Vector3 expected = -n;
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
// Reflection when normal and source are negation
[Fact]
public void Vector3ReflectTest2()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
n = Vector3.Normalize(n);
Vector3 a = -n;
Vector3 expected = n;
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3f, Vector3f)
// Reflection when normal and source are perpendicular (a dot n = 0)
[Fact]
public void Vector3ReflectTest3()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
Vector3 temp = new Vector3(1.28f, 0.45f, 0.01f);
// find a perpendicular vector of n
Vector3 a = Vector3.Cross(temp, n);
Vector3 expected = a;
Vector3 actual = Vector3.Reflect(a, n);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value.");
}
// A test for Transform(Vector3f, Matrix4x4)
[Fact]
public void Vector3TransformTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector3 expected = new Vector3(12.191987f, 21.533493f, 32.616024f);
Vector3 actual;
actual = Vector3.Transform(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Clamp (Vector3f, Vector3f, Vector3f)
[Fact]
public void Vector3ClampTest()
{
Vector3 a = new Vector3(0.5f, 0.3f, 0.33f);
Vector3 min = new Vector3(0.0f, 0.1f, 0.13f);
Vector3 max = new Vector3(1.0f, 1.1f, 1.13f);
// Normal case.
// Case N1: specified value is in the range.
Vector3 expected = new Vector3(0.5f, 0.3f, 0.33f);
Vector3 actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Normal case.
// Case N2: specified value is bigger than max value.
a = new Vector3(2.0f, 3.0f, 4.0f);
expected = max;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Case N3: specified value is smaller than max value.
a = new Vector3(-2.0f, -3.0f, -4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Case N4: combination case.
a = new Vector3(-2.0f, 0.5f, 4.0f);
expected = new Vector3(min.X, a.Y, max.Z);
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// User specified min value is bigger than max value.
max = new Vector3(0.0f, 0.1f, 0.13f);
min = new Vector3(1.0f, 1.1f, 1.13f);
// Case W1: specified value is in the range.
a = new Vector3(0.5f, 0.3f, 0.33f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Normal case.
// Case W2: specified value is bigger than max and min value.
a = new Vector3(2.0f, 3.0f, 4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
// Case W3: specified value is smaller than min and max value.
a = new Vector3(-2.0f, -3.0f, -4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value.");
}
// A test for TransformNormal (Vector3f, Matrix4x4)
[Fact]
public void Vector3TransformNormalTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector3 expected = new Vector3(2.19198728f, 1.53349364f, 2.61602545f);
Vector3 actual;
actual = Vector3.TransformNormal(v, m);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.TransformNormal did not return the expected value.");
}
// A test for Transform (Vector3f, Quaternion)
[Fact]
public void Vector3TransformByQuaternionTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Vector3 expected = Vector3.Transform(v, m);
Vector3 actual = Vector3.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Transform (Vector3f, Quaternion)
// Transform vector3 with zero quaternion
[Fact]
public void Vector3TransformByQuaternionTest1()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Quaternion q = new Quaternion();
Vector3 expected = v;
Vector3 actual = Vector3.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Transform (Vector3f, Quaternion)
// Transform vector3 with identity quaternion
[Fact]
public void Vector3TransformByQuaternionTest2()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Quaternion q = Quaternion.Identity;
Vector3 expected = v;
Vector3 actual = Vector3.Transform(v, q);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value.");
}
// A test for Normalize (Vector3f)
[Fact]
public void Vector3NormalizeTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(
0.26726124191242438468455348087975f,
0.53452248382484876936910696175951f,
0.80178372573727315405366044263926f);
Vector3 actual;
actual = Vector3.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector3f)
// Normalize vector of length one
[Fact]
public void Vector3NormalizeTest1()
{
Vector3 a = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 expected = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value.");
}
// A test for Normalize (Vector3f)
// Normalize vector of length zero
[Fact]
public void Vector3NormalizeTest2()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Normalize(a);
Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z), "Vector3f.Normalize did not return the expected value.");
}
// A test for operator - (Vector3f)
[Fact]
public void Vector3UnaryNegationTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f);
Vector3 actual;
actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value.");
}
[Fact]
public void Vector3UnaryNegationTest1()
{
Vector3 a = -new Vector3(Single.NaN, Single.PositiveInfinity, Single.NegativeInfinity);
Vector3 b = -new Vector3(0.0f, 0.0f, 0.0f);
Assert.Equal(Single.NaN, a.X);
Assert.Equal(Single.NegativeInfinity, a.Y);
Assert.Equal(Single.PositiveInfinity, a.Z);
Assert.Equal(0.0f, b.X);
Assert.Equal(0.0f, b.Y);
Assert.Equal(0.0f, b.Z);
}
// A test for operator - (Vector3f, Vector3f)
[Fact]
public void Vector3SubtractionTest()
{
Vector3 a = new Vector3(4.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 5.0f, 7.0f);
Vector3 expected = new Vector3(3.0f, -3.0f, -4.0f);
Vector3 actual;
actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value.");
}
// A test for operator * (Vector3f, float)
[Fact]
public void Vector3MultiplyOperatorTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual;
actual = a * factor;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value.");
}
// A test for operator * (float, Vector3f)
[Fact]
public void Vector3MultiplyOperatorTest2()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
const float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual;
actual = factor * a;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value.");
}
// A test for operator * (Vector3f, Vector3f)
[Fact]
public void Vector3MultiplyOperatorTest3()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(4.0f, 10.0f, 18.0f);
Vector3 actual;
actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value.");
}
// A test for operator / (Vector3f, float)
[Fact]
public void Vector3DivisionTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float div = 2.0f;
Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f);
Vector3 actual;
actual = a / div;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value.");
}
// A test for operator / (Vector3f, Vector3f)
[Fact]
public void Vector3DivisionTest1()
{
Vector3 a = new Vector3(4.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(4.0f, 0.4f, 0.5f);
Vector3 actual;
actual = a / b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value.");
}
// A test for operator / (Vector3f, Vector3f)
// Divide by zero
[Fact]
public void Vector3DivisionTest2()
{
Vector3 a = new Vector3(-2.0f, 3.0f, float.MaxValue);
float div = 0.0f;
Vector3 actual = a / div;
Assert.True(float.IsNegativeInfinity(actual.X), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Y), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsPositiveInfinity(actual.Z), "Vector3f.operator / did not return the expected value.");
}
// A test for operator / (Vector3f, Vector3f)
// Divide by zero
[Fact]
public void Vector3DivisionTest3()
{
Vector3 a = new Vector3(0.047f, -3.0f, float.NegativeInfinity);
Vector3 b = new Vector3();
Vector3 actual = a / b;
Assert.True(float.IsPositiveInfinity(actual.X), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsNegativeInfinity(actual.Y), "Vector3f.operator / did not return the expected value.");
Assert.True(float.IsNegativeInfinity(actual.Z), "Vector3f.operator / did not return the expected value.");
}
// A test for operator + (Vector3f, Vector3f)
[Fact]
public void Vector3AdditionTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(5.0f, 7.0f, 9.0f);
Vector3 actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator + did not return the expected value.");
}
// A test for Vector3f (float, float, float)
[Fact]
public void Vector3ConstructorTest()
{
float x = 1.0f;
float y = 2.0f;
float z = 3.0f;
Vector3 target = new Vector3(x, y, z);
Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (x,y,z) did not return the expected value.");
}
// A test for Vector3f (Vector2f, float)
[Fact]
public void Vector3ConstructorTest1()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
Assert.True(MathHelper.Equal(target.X, a.X) && MathHelper.Equal(target.Y, a.Y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (Vector2f,z) did not return the expected value.");
}
// A test for Vector3f ()
// Constructor with no parameter
[Fact]
public void Vector3ConstructorTest3()
{
Vector3 a = new Vector3();
Assert.Equal(a.X, 0.0f);
Assert.Equal(a.Y, 0.0f);
Assert.Equal(a.Z, 0.0f);
}
// A test for Vector2f (float, float)
// Constructor with special floating values
[Fact]
public void Vector3ConstructorTest4()
{
Vector3 target = new Vector3(float.NaN, float.MaxValue, float.PositiveInfinity);
Assert.True(float.IsNaN(target.X), "Vector3f.constructor (Vector3f) did not return the expected value.");
Assert.True(float.Equals(float.MaxValue, target.Y), "Vector3f.constructor (Vector3f) did not return the expected value.");
Assert.True(float.IsPositiveInfinity(target.Z), "Vector3f.constructor (Vector3f) did not return the expected value.");
}
// A test for Add (Vector3f, Vector3f)
[Fact]
public void Vector3AddTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 6.0f, 7.0f);
Vector3 expected = new Vector3(6.0f, 8.0f, 10.0f);
Vector3 actual;
actual = Vector3.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector3f, float)
[Fact]
public void Vector3DivideTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float div = 2.0f;
Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f);
Vector3 actual;
actual = Vector3.Divide(a, div);
Assert.Equal(expected, actual);
}
// A test for Divide (Vector3f, Vector3f)
[Fact]
public void Vector3DivideTest1()
{
Vector3 a = new Vector3(1.0f, 6.0f, 7.0f);
Vector3 b = new Vector3(5.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(1.0f / 5.0f, 6.0f / 2.0f, 7.0f / 3.0f);
Vector3 actual;
actual = Vector3.Divide(a, b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void Vector3EqualsTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector3f, float)
[Fact]
public void Vector3MultiplyTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
const float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual = Vector3.Multiply(a, factor);
Assert.Equal(expected, actual);
}
// A test for Multiply (float, Vector3f)
[Fact]
public static void Vector3MultiplyTest2()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
const float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual = Vector3.Multiply(factor, a);
Assert.Equal(expected, actual);
}
// A test for Multiply (Vector3f, Vector3f)
[Fact]
public void Vector3MultiplyTest3()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 6.0f, 7.0f);
Vector3 expected = new Vector3(5.0f, 12.0f, 21.0f);
Vector3 actual;
actual = Vector3.Multiply(a, b);
Assert.Equal(expected, actual);
}
// A test for Negate (Vector3f)
[Fact]
public void Vector3NegateTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f);
Vector3 actual;
actual = Vector3.Negate(a);
Assert.Equal(expected, actual);
}
// A test for operator != (Vector3f, Vector3f)
[Fact]
public void Vector3InequalityTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Vector3f, Vector3f)
[Fact]
public void Vector3EqualityTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for Subtract (Vector3f, Vector3f)
[Fact]
public void Vector3SubtractTest()
{
Vector3 a = new Vector3(1.0f, 6.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-4.0f, 4.0f, 0.0f);
Vector3 actual;
actual = Vector3.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for One
[Fact]
public void Vector3OneTest()
{
Vector3 val = new Vector3(1.0f, 1.0f, 1.0f);
Assert.Equal(val, Vector3.One);
}
// A test for UnitX
[Fact]
public void Vector3UnitXTest()
{
Vector3 val = new Vector3(1.0f, 0.0f, 0.0f);
Assert.Equal(val, Vector3.UnitX);
}
// A test for UnitY
[Fact]
public void Vector3UnitYTest()
{
Vector3 val = new Vector3(0.0f, 1.0f, 0.0f);
Assert.Equal(val, Vector3.UnitY);
}
// A test for UnitZ
[Fact]
public void Vector3UnitZTest()
{
Vector3 val = new Vector3(0.0f, 0.0f, 1.0f);
Assert.Equal(val, Vector3.UnitZ);
}
// A test for Zero
[Fact]
public void Vector3ZeroTest()
{
Vector3 val = new Vector3(0.0f, 0.0f, 0.0f);
Assert.Equal(val, Vector3.Zero);
}
// A test for Equals (Vector3f)
[Fact]
public void Vector3EqualsTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Vector3f (float)
[Fact]
public void Vector3ConstructorTest5()
{
float value = 1.0f;
Vector3 target = new Vector3(value);
Vector3 expected = new Vector3(value, value, value);
Assert.Equal(expected, target);
value = 2.0f;
target = new Vector3(value);
expected = new Vector3(value, value, value);
Assert.Equal(expected, target);
}
// A test for Vector3f comparison involving NaN values
[Fact]
public void Vector3EqualsNanTest()
{
Vector3 a = new Vector3(float.NaN, 0, 0);
Vector3 b = new Vector3(0, float.NaN, 0);
Vector3 c = new Vector3(0, 0, float.NaN);
Assert.False(a == Vector3.Zero);
Assert.False(b == Vector3.Zero);
Assert.False(c == Vector3.Zero);
Assert.True(a != Vector3.Zero);
Assert.True(b != Vector3.Zero);
Assert.True(c != Vector3.Zero);
Assert.False(a.Equals(Vector3.Zero));
Assert.False(b.Equals(Vector3.Zero));
Assert.False(c.Equals(Vector3.Zero));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
Assert.False(c.Equals(c));
}
[Fact]
public void Vector3AbsTest()
{
Vector3 v1 = new Vector3(-2.5f, 2.0f, 0.5f);
Vector3 v3 = Vector3.Abs(new Vector3(0.0f, Single.NegativeInfinity, Single.NaN));
Vector3 v = Vector3.Abs(v1);
Assert.Equal(2.5f, v.X);
Assert.Equal(2.0f, v.Y);
Assert.Equal(0.5f, v.Z);
Assert.Equal(0.0f, v3.X);
Assert.Equal(Single.PositiveInfinity, v3.Y);
Assert.Equal(Single.NaN, v3.Z);
}
[Fact]
public void Vector3SqrtTest()
{
Vector3 a = new Vector3(-2.5f, 2.0f, 0.5f);
Vector3 b = new Vector3(5.5f, 4.5f, 16.5f);
Assert.Equal(2, (int)Vector3.SquareRoot(b).X);
Assert.Equal(2, (int)Vector3.SquareRoot(b).Y);
Assert.Equal(4, (int)Vector3.SquareRoot(b).Z);
Assert.Equal(Single.NaN, Vector3.SquareRoot(a).X);
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void Vector3SizeofTest()
{
Assert.Equal(12, sizeof(Vector3));
Assert.Equal(24, sizeof(Vector3_2x));
Assert.Equal(16, sizeof(Vector3PlusFloat));
Assert.Equal(32, sizeof(Vector3PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3_2x
{
private Vector3 _a;
private Vector3 _b;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3PlusFloat
{
private Vector3 _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3PlusFloat_2x
{
private Vector3PlusFloat _a;
private Vector3PlusFloat _b;
}
[Fact]
public void SetFieldsTest()
{
Vector3 v3 = new Vector3(4f, 5f, 6f);
v3.X = 1.0f;
v3.Y = 2.0f;
v3.Z = 3.0f;
Assert.Equal(1.0f, v3.X);
Assert.Equal(2.0f, v3.Y);
Assert.Equal(3.0f, v3.Z);
Vector3 v4 = v3;
v4.Y = 0.5f;
v4.Z = 2.2f;
Assert.Equal(1.0f, v4.X);
Assert.Equal(0.5f, v4.Y);
Assert.Equal(2.2f, v4.Z);
Assert.Equal(2.0f, v3.Y);
Vector3 before = new Vector3(1f, 2f, 3f);
Vector3 after = before;
after.X = 500.0f;
Assert.NotEqual(before, after);
}
[Fact]
public void EmbeddedVectorSetFields()
{
EmbeddedVectorObject evo = new EmbeddedVectorObject();
evo.FieldVector.X = 5.0f;
evo.FieldVector.Y = 5.0f;
evo.FieldVector.Z = 5.0f;
Assert.Equal(5.0f, evo.FieldVector.X);
Assert.Equal(5.0f, evo.FieldVector.Y);
Assert.Equal(5.0f, evo.FieldVector.Z);
}
private class EmbeddedVectorObject
{
public Vector3 FieldVector;
}
}
}
| |
using Bridge.Test.NUnit;
using System;
namespace Bridge.ClientTest
{
[Category(Constants.MODULE_ACTIVATOR)]
[TestFixture(TestNameFormat = "ActivatorTests - {0}")]
public class ActivatorTests
{
private class C1
{
public int i;
public C1()
{
i = 42;
}
}
private class C2
{
public int i;
public C2(int i)
{
this.i = i;
}
}
private class C3
{
public int i, j;
public C3(int i, int j)
{
this.i = i;
this.j = j;
}
}
public class C4
{
public int i;
//[Name("named")]
public C4()
{
i = 42;
}
//[Name("")]
public C4(int i)
{
this.i = 1;
}
}
public class C5
{
public int i;
[Template("{ i: 42 }")]
public C5()
{
}
}
//[Serializable]
public class C6
{
public int i;
public C6()
{
i = 42;
}
}
//[Serializable]
[ObjectLiteral]
private class C7
{
public C7()
{
}
}
public class C8<T>
{
public int I;
//[Name("named")]
public C8()
{
I = 42;
}
//[Name("")]
public C8(T t)
{
I = 1;
}
}
[Test]
public void NonGenericCreateInstanceWithoutArgumentsWorks()
{
C1 c = (C1)Activator.CreateInstance(typeof(C1));
Assert.AreNotEqual(null, c);
Assert.AreEqual(42, c.i);
}
[Test]
public void NonGenericCreateInstanceWithOneArgumentWorks_SPI_1540()
{
var c = (C2)Activator.CreateInstance(typeof(C2), 3);
Assert.AreNotEqual(null, c);
Assert.AreEqual(3, c.i);
// #1540
var arr = new object[] { 3 };
c = (C2)Activator.CreateInstance(typeof(C2), arr);
Assert.AreNotEqual(null, c);
Assert.AreEqual(3, c.i);
}
[Test]
public void NonGenericCreateInstanceWithTwoArgumentsWorks_SPI_1541()
{
var c = (C3)Activator.CreateInstance(typeof(C3), 7, 8);
Assert.AreNotEqual(null, c);
Assert.AreEqual(7, c.i);
Assert.AreEqual(8, c.j);
// #1541
var arr = new object[] { 7, 8 };
c = (C3)Activator.CreateInstance(typeof(C3), arr);
Assert.AreNotEqual(null, c);
Assert.AreEqual(7, c.i);
Assert.AreEqual(8, c.j);
}
[Test]
public void GenericCreateInstanceWithoutArgumentsWorks()
{
C1 c = Activator.CreateInstance<C1>();
Assert.AreNotEqual(null, c);
Assert.AreEqual(42, c.i);
}
[Test]
public void GenericCreateInstanceWithOneArgumentWorks_SPI_1542()
{
C2 c = Activator.CreateInstance<C2>(3);
Assert.AreNotEqual(null, c);
Assert.AreEqual(3, c.i);
// #1542
var arr = new object[] { 3 };
c = Activator.CreateInstance<C2>(arr);
Assert.AreNotEqual(null, c);
Assert.AreEqual(3, c.i);
}
[Test]
public void GenericCreateInstanceWithTwoArgumentsWorks_SPI_1543()
{
C3 c = Activator.CreateInstance<C3>(7, 8);
Assert.AreNotEqual(null, c);
Assert.AreEqual(7, c.i);
Assert.AreEqual(8, c.j);
// #1543
var arr = new object[] { 7, 8 };
c = Activator.CreateInstance<C3>(arr);
Assert.AreNotEqual(null, c);
Assert.AreEqual(7, c.i);
Assert.AreEqual(8, c.j);
}
private T Instantiate<T>() where T : new()
{
return new T();
}
[Test]
public void InstantiatingTypeParameterWithDefaultConstructorConstraintWorks_SPI_1544()
{
var c = Instantiate<C1>();
Assert.AreEqual(42, c.i);
// #1544
Assert.AreStrictEqual(0, Instantiate<int>());
}
[Test]
public void CreateInstanceWithNoArgumentsWorksForClassWithUnnamedDefaultConstructor()
{
var c1 = Activator.CreateInstance<C1>();
var c2 = (C1)Activator.CreateInstance(typeof(C1));
var c3 = Instantiate<C1>();
Assert.AreEqual(42, c1.i);
Assert.AreEqual(42, c2.i);
Assert.AreEqual(42, c3.i);
}
[Test]
public void CreateInstanceWithNoArgumentsWorksForClassWithNamedDefaultConstructor()
{
var c1 = Activator.CreateInstance<C4>();
var c2 = (C4)Activator.CreateInstance(typeof(C4));
var c3 = Instantiate<C4>();
Assert.AreEqual(42, c1.i);
Assert.AreEqual(42, c2.i);
Assert.AreEqual(42, c3.i);
}
[Test]
public void CreateInstanceWithNoArgumentsWorksForClassWithInlineCodeDefaultConstructor_SPI_1545()
{
var c1 = Activator.CreateInstance<C5>();
var c2 = Activator.CreateInstance(typeof(C5)).As<C5>();
var c3 = Instantiate<C5>();
// #1545
Assert.AreEqual(42, c1.i);
Assert.AreEqual(42, c2.i);
Assert.AreEqual(42, c3.i);
}
[Test]
public void CreateInstanceWithNoArgumentsWorksForClassWithStaticMethodDefaultConstructor()
{
var c1 = Activator.CreateInstance<C6>();
var c2 = (C6)Activator.CreateInstance(typeof(C6));
var c3 = (C6)Instantiate<C6>();
Assert.AreEqual(42, c1.i);
Assert.AreEqual(42, c2.i);
Assert.AreEqual(42, c3.i);
}
//[Test]
//public void CreateInstanceWithNoArgumentsWorksForClassWithJsonDefaultConstructor()
//{
// var c1 = Activator.CreateInstance<C7>();
// var c2 = (C7)Activator.CreateInstance(typeof(C7));
// var c3 = Instantiate<C7>();
// Assert.AreEqual(Script.ToDynamic().Object, ((dynamic)c1).constructor);
// Assert.AreEqual(Script.ToDynamic().Object, ((dynamic)c2).constructor);
// Assert.AreEqual(Script.ToDynamic().Object, ((dynamic)c3).constructor);
//}
[Test]
public void CreateInstanceWithNoArgumentsWorksForGenericClassWithNamedDefaultConstructor()
{
var c1 = Activator.CreateInstance<C8<int>>();
var c2 = (C8<int>)Activator.CreateInstance(typeof(C8<int>));
var c3 = Instantiate<C8<int>>();
Assert.AreEqual(42, c1.I);
Assert.AreEqual(typeof(int), c1.GetType().GetGenericArguments()[0]);
Assert.AreEqual(42, c2.I);
Assert.AreEqual(typeof(int), c2.GetType().GetGenericArguments()[0]);
Assert.AreEqual(42, c3.I);
Assert.AreEqual(typeof(int), c3.GetType().GetGenericArguments()[0]);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using NUnit.Common;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnitLite
{
public class TextUI
{
public ExtendedTextWriter Writer { get; private set; }
private readonly TextReader _reader;
private readonly NUnitLiteOptions _options;
private readonly bool _displayBeforeTest;
private readonly bool _displayAfterTest;
private readonly bool _displayBeforeOutput;
#region Constructor
public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options)
{
Writer = writer;
_reader = reader;
_options = options;
string labelsOption = options.DisplayTestLabels?.ToUpperInvariant() ?? "ON";
_displayBeforeTest = labelsOption == "ALL" || labelsOption == "BEFORE";
_displayAfterTest = labelsOption == "AFTER";
_displayBeforeOutput = _displayBeforeTest || _displayAfterTest || labelsOption == "ON";
}
#endregion
#region Public Methods
#region DisplayHeader
/// <summary>
/// Writes the header.
/// </summary>
public void DisplayHeader()
{
Assembly executingAssembly = GetType().GetTypeInfo().Assembly;
AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly);
Version version = assemblyName.Version;
string copyright = "Copyright (C) 2017 Charlie Poole, Rob Prouse";
string build = "";
var copyrightAttr = executingAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>();
if (copyrightAttr != null)
copyright = copyrightAttr.Copyright;
var configAttr = executingAssembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
if (configAttr != null)
build = string.Format("({0})", configAttr.Configuration);
WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build));
WriteSubHeader(copyright);
Writer.WriteLine();
}
#endregion
#region DisplayTestFiles
public void DisplayTestFiles(IEnumerable<string> testFiles)
{
WriteSectionHeader("Test Files");
foreach (string testFile in testFiles)
Writer.WriteLine(ColorStyle.Default, " " + testFile);
Writer.WriteLine();
}
#endregion
#region DisplayHelp
public void DisplayHelp()
{
WriteHeader("Usage: NUNITLITE-RUNNER assembly [options]");
WriteHeader(" USER-EXECUTABLE [options]");
Writer.WriteLine();
WriteHelpLine("Runs a set of NUnitLite tests from the console.");
Writer.WriteLine();
WriteSectionHeader("Assembly:");
WriteHelpLine(" File name or path of the assembly from which to execute tests. Required");
WriteHelpLine(" when using the nunitlite-runner executable to run the tests. Not allowed");
WriteHelpLine(" when running a self-executing user test assembly.");
Writer.WriteLine();
WriteSectionHeader("Options:");
using (var sw = new StringWriter())
{
_options.WriteOptionDescriptions(sw);
Writer.Write(ColorStyle.Help, sw.ToString());
}
WriteSectionHeader("Notes:");
WriteHelpLine(" * File names may be listed by themselves, with a relative path or ");
WriteHelpLine(" using an absolute path. Any relative path is based on the current ");
WriteHelpLine(" directory or on the Documents folder if running on a under the ");
WriteHelpLine(" compact framework.");
Writer.WriteLine();
WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired");
Writer.WriteLine();
WriteHelpLine(" * Options that take values may use an equal sign or a colon");
WriteHelpLine(" to separate the option from its value.");
Writer.WriteLine();
WriteHelpLine(" * Several options that specify processing of XML output take");
WriteHelpLine(" an output specification as a value. A SPEC may take one of");
WriteHelpLine(" the following forms:");
WriteHelpLine(" --OPTION:filename");
WriteHelpLine(" --OPTION:filename;format=formatname");
Writer.WriteLine();
WriteHelpLine(" The --result option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit");
Writer.WriteLine();
WriteHelpLine(" The --explore option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" cases - a text file listing the full names of all test cases.");
WriteHelpLine(" If --explore is used without any specification following, a list of");
WriteHelpLine(" test cases is output to the console.");
Writer.WriteLine();
}
#endregion
#region DisplayRuntimeEnvironment
/// <summary>
/// Displays info about the runtime environment.
/// </summary>
public void DisplayRuntimeEnvironment()
{
WriteSectionHeader("Runtime Environment");
#if !PLATFORM_DETECTION
Writer.WriteLabelLine(" OS Version: ", System.Runtime.InteropServices.RuntimeInformation.OSDescription);
#else
Writer.WriteLabelLine(" OS Version: ", OSPlatform.CurrentPlatform);
#endif
#if NETSTANDARD1_6
Writer.WriteLabelLine(" CLR Version: ", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
#else
Writer.WriteLabelLine(" CLR Version: ", Environment.Version);
#endif
Writer.WriteLine();
}
#endregion
#region DisplayTestFilters
public void DisplayTestFilters()
{
if (_options.TestList.Count > 0 || _options.WhereClauseSpecified)
{
WriteSectionHeader("Test Filters");
if (_options.TestList.Count > 0)
foreach (string testName in _options.TestList)
Writer.WriteLabelLine(" Test: ", testName);
if (_options.WhereClauseSpecified)
Writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim());
Writer.WriteLine();
}
}
#endregion
#region DisplayRunSettings
public void DisplayRunSettings()
{
WriteSectionHeader("Run Settings");
if (_options.DefaultTimeout >= 0)
Writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout);
#if PARALLEL
Writer.WriteLabelLine(
" Number of Test Workers: ",
_options.NumberOfTestWorkers >= 0
? _options.NumberOfTestWorkers
: Math.Max(Environment.ProcessorCount, 2));
#endif
Writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? Directory.GetCurrentDirectory());
Writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off");
if (_options.TeamCity)
Writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages");
Writer.WriteLine();
}
#endregion
#region TestStarted
public void TestStarted(ITest test)
{
if (_displayBeforeTest && !test.IsSuite)
WriteLabelLine(test.FullName);
}
#endregion
#region TestFinished
private bool _testCreatedOutput = false;
private bool _needsNewLine = false;
public void TestFinished(ITestResult result)
{
if (result.Output.Length > 0)
{
if (_displayBeforeOutput)
WriteLabelLine(result.Test.FullName);
WriteOutput(result.Output);
if (!result.Output.EndsWith("\n"))
Writer.WriteLine();
}
if (!result.Test.IsSuite)
{
if (_displayAfterTest)
WriteLabelLineAfterTest(result.Test.FullName, result.ResultState);
}
if (result.Test is TestAssembly && _testCreatedOutput)
{
Writer.WriteLine();
_testCreatedOutput = false;
}
}
#endregion
#region TestOutput
public void TestOutput(TestOutput output)
{
if (_displayBeforeOutput && output.TestName != null)
WriteLabelLine(output.TestName);
WriteOutput(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text);
}
#endregion
#region WaitForUser
public void WaitForUser(string message)
{
// Ignore if we don't have a TextReader
if (_reader != null)
{
Writer.WriteLine(ColorStyle.Label, message);
_reader.ReadLine();
}
}
#endregion
#region Test Result Reports
#region DisplaySummaryReport
public void DisplaySummaryReport(ResultSummary summary)
{
var status = summary.ResultState.Status;
var overallResult = status.ToString();
if (overallResult == "Skipped")
overallResult = "Warning";
ColorStyle overallStyle = status == TestStatus.Passed
? ColorStyle.Pass
: status == TestStatus.Failed
? ColorStyle.Failure
: status == TestStatus.Skipped
? ColorStyle.Warning
: ColorStyle.Output;
if (_testCreatedOutput)
Writer.WriteLine();
WriteSectionHeader("Test Run Summary");
Writer.WriteLabelLine(" Overall result: ", overallResult, overallStyle);
WriteSummaryCount(" Test Count: ", summary.TestCount);
WriteSummaryCount(", Passed: ", summary.PassCount);
WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure);
WriteSummaryCount(", Warnings: ", summary.WarningCount, ColorStyle.Warning);
WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount);
WriteSummaryCount(", Skipped: ", summary.TotalSkipCount);
Writer.WriteLine();
if (summary.FailedCount > 0)
{
WriteSummaryCount(" Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure);
WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error);
WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error);
Writer.WriteLine();
}
if (summary.TotalSkipCount > 0)
{
WriteSummaryCount(" Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning);
WriteSummaryCount(", Explicit: ", summary.ExplicitCount);
WriteSummaryCount(", Other: ", summary.SkipCount);
Writer.WriteLine();
}
Writer.WriteLabelLine(" Start time: ", summary.StartTime.ToString("u"));
Writer.WriteLabelLine(" End time: ", summary.EndTime.ToString("u"));
Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration));
Writer.WriteLine();
}
private void WriteSummaryCount(string label, int count)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture));
}
private void WriteSummaryCount(string label, int count, ColorStyle color)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value);
}
#endregion
#region DisplayErrorsAndFailuresReport
public void DisplayErrorsFailuresAndWarningsReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Errors, Failures and Warnings");
DisplayErrorsFailuresAndWarnings(result);
Writer.WriteLine();
if (_options.StopOnError)
{
Writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error");
Writer.WriteLine();
}
}
#endregion
#region DisplayNotRunReport
public void DisplayNotRunReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Tests Not Run");
DisplayNotRunResults(result);
Writer.WriteLine();
}
#endregion
#region DisplayFullReport
#if FULL // Not currently used, but may be reactivated
/// <summary>
/// Prints a full report of all results
/// </summary>
public void DisplayFullReport(ITestResult result)
{
WriteLine(ColorStyle.SectionHeader, "All Test Results -");
_writer.WriteLine();
DisplayAllResults(result, " ");
_writer.WriteLine();
}
#endif
#endregion
#endregion
#region DisplayWarning
public void DisplayWarning(string text)
{
Writer.WriteLine(ColorStyle.Warning, text);
}
#endregion
#region DisplayError
public void DisplayError(string text)
{
Writer.WriteLine(ColorStyle.Error, text);
}
#endregion
#region DisplayErrors
public void DisplayErrors(IList<string> messages)
{
foreach (string message in messages)
DisplayError(message);
}
#endregion
#endregion
#region Helper Methods
private void DisplayErrorsFailuresAndWarnings(ITestResult result)
{
bool display =
result.ResultState.Status == TestStatus.Failed ||
result.ResultState.Status == TestStatus.Warning;
if (result.Test.IsSuite)
{
if (display)
{
var suite = result.Test as TestSuite;
var site = result.ResultState.Site;
if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown)
DisplayTestResult(result);
if (site == FailureSite.SetUp) return;
}
foreach (ITestResult childResult in result.Children)
DisplayErrorsFailuresAndWarnings(childResult);
}
else if (display)
DisplayTestResult(result);
}
private void DisplayNotRunResults(ITestResult result)
{
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
DisplayNotRunResults(childResult);
else if (result.ResultState.Status == TestStatus.Skipped)
DisplayTestResult(result);
}
private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' };
private int _reportIndex;
private void DisplayTestResult(ITestResult result)
{
ResultState resultState = result.ResultState;
string fullName = result.FullName;
string message = result.Message;
string stackTrace = result.StackTrace;
string reportID = (++_reportIndex).ToString();
int numAsserts = result.AssertionResults.Count;
if (numAsserts > 0)
{
int assertionCounter = 0;
string assertID = reportID;
foreach (var assertion in result.AssertionResults)
{
if (numAsserts > 1)
assertID = string.Format("{0}-{1}", reportID, ++assertionCounter);
ColorStyle style = GetColorStyle(resultState);
string status = assertion.Status.ToString();
DisplayTestResult(style, assertID, status, fullName, assertion.Message, assertion.StackTrace);
}
}
else
{
ColorStyle style = GetColorStyle(resultState);
string status = GetResultStatus(resultState);
DisplayTestResult(style, reportID, status, fullName, message, stackTrace);
}
}
private void DisplayTestResult(ColorStyle style, string prefix, string status, string fullName, string message, string stackTrace)
{
Writer.WriteLine();
Writer.WriteLine(
style, string.Format("{0}) {1} : {2}", prefix, status, fullName));
if (!string.IsNullOrEmpty(message))
Writer.WriteLine(style, message.TrimEnd(TRIM_CHARS));
if (!string.IsNullOrEmpty(stackTrace))
Writer.WriteLine(style, stackTrace.TrimEnd(TRIM_CHARS));
}
private static ColorStyle GetColorStyle(ResultState resultState)
{
ColorStyle style = ColorStyle.Output;
switch (resultState.Status)
{
case TestStatus.Failed:
style = ColorStyle.Failure;
break;
case TestStatus.Warning:
style = ColorStyle.Warning;
break;
case TestStatus.Skipped:
style = resultState.Label == "Ignored" ? ColorStyle.Warning : ColorStyle.Output;
break;
case TestStatus.Passed:
style = ColorStyle.Pass;
break;
}
return style;
}
private static string GetResultStatus(ResultState resultState)
{
string status = resultState.Label;
if (string.IsNullOrEmpty(status))
status = resultState.Status.ToString();
if (status == "Failed" || status == "Error")
{
var site = resultState.Site.ToString();
if (site == "SetUp" || site == "TearDown")
status = site + " " + status;
}
return status;
}
#if FULL
private void DisplayAllResults(ITestResult result, string indent)
{
string status = null;
ColorStyle style = ColorStyle.Output;
switch (result.ResultState.Status)
{
case TestStatus.Failed:
status = "FAIL";
style = ColorStyle.Failure;
break;
case TestStatus.Skipped:
if (result.ResultState.Label == "Ignored")
{
status = "IGN ";
style = ColorStyle.Warning;
}
else
{
status = "SKIP";
style = ColorStyle.Output;
}
break;
case TestStatus.Inconclusive:
status = "INC ";
style = ColorStyle.Output;
break;
case TestStatus.Passed:
status = "OK ";
style = ColorStyle.Pass;
break;
}
WriteLine(style, status + indent + result.Name);
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
PrintAllResults(childResult, indent + " ");
}
#endif
private void WriteHeader(string text)
{
Writer.WriteLine(ColorStyle.Header, text);
}
private void WriteSubHeader(string text)
{
Writer.WriteLine(ColorStyle.SubHeader, text);
}
private void WriteSectionHeader(string text)
{
Writer.WriteLine(ColorStyle.SectionHeader, text);
}
private void WriteHelpLine(string text)
{
Writer.WriteLine(ColorStyle.Help, text);
}
private string _currentLabel;
private void WriteLabelLine(string label)
{
if (label != _currentLabel)
{
WriteNewLineIfNeeded();
Writer.WriteLine(ColorStyle.SectionHeader, "=> " + label);
_testCreatedOutput = true;
_currentLabel = label;
}
}
private void WriteLabelLineAfterTest(string label, ResultState resultState)
{
WriteNewLineIfNeeded();
string status = string.IsNullOrEmpty(resultState.Label)
? resultState.Status.ToString()
: resultState.Label;
Writer.Write(GetColorForResultStatus(status), status);
Writer.WriteLine(ColorStyle.SectionHeader, " => " + label);
_currentLabel = label;
}
private void WriteNewLineIfNeeded()
{
if (_needsNewLine)
{
Writer.WriteLine();
_needsNewLine = false;
}
}
private void WriteOutput(string text)
{
WriteOutput(ColorStyle.Output, text);
}
private void WriteOutput(ColorStyle color, string text)
{
Writer.Write(color, text);
_testCreatedOutput = true;
_needsNewLine = !text.EndsWith("\n");
}
private static ColorStyle GetColorForResultStatus(string status)
{
switch (status)
{
case "Passed":
return ColorStyle.Pass;
case "Failed":
return ColorStyle.Failure;
case "Error":
case "Invalid":
case "Cancelled":
return ColorStyle.Error;
case "Warning":
case "Ignored":
return ColorStyle.Warning;
default:
return ColorStyle.Output;
}
}
#endregion
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.