context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Semantics;
using Microsoft.Cci;
using Microsoft.Cci.MutableCodeModel;
using System.Diagnostics.Contracts;
using Microsoft.CodeAnalysis.Common.Semantics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using R = Microsoft.CodeAnalysis.CSharp.Symbols;
using RC = Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Common;
namespace CSharp2CCI {
internal class ExpressionVisitor : SyntaxVisitor<IExpression> {
#region Fields
private IMetadataHost host;
CommonSemanticModel semanticModel;
ReferenceMapper mapper;
private IMethodDefinition method;
Dictionary<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol, ILocalDefinition> locals = new Dictionary<Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol, ILocalDefinition>(); // TODO: need to make this a stack of local scopes!
Dictionary<IMethodDefinition, List<IParameterDefinition>> parameters = new Dictionary<IMethodDefinition, List<IParameterDefinition>>(); // TODO: Clean up entries when not needed?
private RC.CommonSyntaxTree tree;
#endregion
public ExpressionVisitor(IMetadataHost host, CommonSemanticModel semanticModel, ReferenceMapper mapper, IMethodDefinition method)
{
this.host = host;
this.semanticModel = semanticModel;
this.mapper = mapper;
this.method = method;
this.parameters.Add(method, new List<IParameterDefinition>(method.Parameters));
this.tree = semanticModel.SyntaxTree;
}
internal void RegisterLocal(Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol localSymbol, ILocalDefinition localDefinition) {
this.locals[localSymbol] = localDefinition;
}
/// <summary>
/// Returns a constant one to be used in pre-/post-fix increment/decrement operations
/// </summary>
private string LocalNumber(){
var s = localNumber.ToString();
localNumber++;
return s;
}
int localNumber = 0;
/// <summary>
/// Tracks whether the left-hand side of an assignment is being translated.
/// Makes a difference whether a property should be translated as a setter
/// or a getter.
/// </summary>
private bool lhs;
object GetConstantOneOfMatchingTypeForIncrementDecrement(ITypeDefinition targetType) {
if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemChar))
return (char)1;
else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemInt8))
return (sbyte)1;
else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemUInt8))
return (byte)1;
else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemInt16))
return (short)1;
else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemUInt16))
return (ushort)1;
return 1;
}
public override IExpression VisitLiteralExpression(LiteralExpressionSyntax node) {
var o = this.semanticModel.GetTypeInfo(node);
switch (node.Kind) {
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
return new CompileTimeConstant() { Type = mapper.Map(o.Type), Value = node.Token.Value, };
case SyntaxKind.NullLiteralExpression:
return new CompileTimeConstant() { Type = this.host.PlatformType.SystemObject, Value = null, };
default:
throw new InvalidDataException("VisitPrimaryExpression passed an unknown node kind: " + node.Kind);
}
}
public override IExpression VisitThisExpression(ThisExpressionSyntax node) {
var o = this.semanticModel.GetTypeInfo(node);
return new ThisReference() { Type = this.mapper.Map(o.Type), };
}
public override IExpression VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) {
var o = this.semanticModel.GetSymbolInfo(node);
var s = o.Symbol as MethodSymbol;
if (s != null) {
var m = (MethodDefinition)this.mapper.TranslateMetadata(s);
var anonDelParameters = new List<IParameterDefinition>(m.Parameters);
this.parameters.Add(m, anonDelParameters);
IBlockStatement body;
var b = node.Body;
if (b is ExpressionSyntax) {
var e = this.Visit(b);
body = new BlockStatement() {
Statements = new List<IStatement>() { new ReturnStatement() { Expression = e, } },
};
} else if (b is BlockSyntax) {
var sv = new StatementVisitor(this.host, this.semanticModel, this.mapper, m, this);
var b2 = (IBlockStatement) sv.Visit(b);
body = b2;
} else {
throw new InvalidDataException("VisitSimpleLambdaExpression: unknown type of body");
}
var anon = new AnonymousDelegate() {
Body = body,
CallingConvention = s.IsStatic ? CallingConvention.HasThis : CallingConvention.Default,
Parameters = anonDelParameters,
ReturnType = m.Type,
Type = this.mapper.Map(this.semanticModel.GetTypeInfo(node).ConvertedType),
};
return anon;
}
throw new InvalidDataException("VisitSimpleLambdaExpression couldn't find something to return");
}
public override IExpression VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) {
var o = this.semanticModel.GetTypeInfo(node);
var t = this.mapper.Map(o.Type);
var operand = this.Visit(node.Operand);
UnaryOperation op = null;
switch (node.Kind) {
case SyntaxKind.BitwiseNotExpression:
op = new OnesComplement();
break;
case SyntaxKind.UnaryMinusExpression:
op = new UnaryNegation();
op.Type = operand.Type;
break;
case SyntaxKind.PreDecrementExpression:
case SyntaxKind.PreIncrementExpression:
BinaryOperation bo;
if (node.OperatorToken.Kind == SyntaxKind.MinusMinusToken)
bo = new Subtraction();
else
bo = new Addition();
object one = GetConstantOneOfMatchingTypeForIncrementDecrement(operand.Type.ResolvedType); // REVIEW: Do we really need to resolve?
bo.LeftOperand = operand;
bo.RightOperand = new CompileTimeConstant() { Type = operand.Type, Value = one, };
bo.Type = operand.Type;
var assign = new Assignment() {
Source = bo,
Target = Helper.MakeTargetExpression(operand),
Type = operand.Type,
};
return assign;
case SyntaxKind.LogicalNotExpression:
op = new LogicalNot();
break;
default:
var typeName = node.GetType().ToString();
var msg = String.Format("Was unable to convert a {0} node to CCI because the kind '{1}' wasn't handled",
typeName, node.Kind.ToString());
throw new ConverterException(msg);
}
op.Operand = operand;
return op;
}
public override IExpression VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) {
var e = this.Visit(node.Operand);
switch (node.OperatorToken.Kind) {
case SyntaxKind.MinusMinusToken:
case SyntaxKind.PlusPlusToken:
var stmts = new List<IStatement>();
var temp = new LocalDefinition() {
MethodDefinition = this.method,
Name = this.host.NameTable.GetNameFor("__temp" + LocalNumber()),
Type = e.Type,
};
stmts.Add(
new LocalDeclarationStatement(){
InitialValue = e,
LocalVariable = temp,
});
BinaryOperation bo;
if (node.OperatorToken.Kind == SyntaxKind.MinusMinusToken)
bo = new Subtraction();
else
bo = new Addition();
object one = GetConstantOneOfMatchingTypeForIncrementDecrement(e.Type.ResolvedType); // REVIEW: Do we really need to resolve?
bo.LeftOperand = e;
bo.RightOperand = new CompileTimeConstant() { Type = e.Type, Value = one, };
bo.Type = e.Type;
var assign = new Assignment() {
Source = bo,
Target = Helper.MakeTargetExpression(e),
Type = e.Type,
};
stmts.Add(
new ExpressionStatement() {
Expression = assign,
});
var blockExpression = new BlockExpression() {
BlockStatement = new BlockStatement() {
Statements = stmts,
},
Expression = new BoundExpression() { Definition = temp, Instance = null, Type = temp.Type },
Type = e.Type,
};
return blockExpression;
default:
throw new InvalidDataException("VisitPostfixUnaryExpression: unknown operator token '" + node.OperatorToken.ValueText);
}
}
public override IExpression VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) {
return this.Visit(node.Expression);
}
public override IExpression VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) {
var o = this.semanticModel.GetSymbolInfo(node);
var s = o.Symbol;
if (s != null) {
MethodSymbol ms = s as MethodSymbol;
var mr = this.mapper.Map(ms);
var e = new CreateObjectInstance() {
Locations = Helper.SourceLocation(this.tree, node),
MethodToCall = mr,
Type = mr.ContainingType,
};
return e;
}
throw new InvalidDataException("VisitObjectCreationExpression couldn't find something to return");
}
public override IExpression VisitMemberAccessExpression(MemberAccessExpressionSyntax node) {
var o = this.semanticModel.GetSymbolInfo(node);
IExpression instance = null;
BoundExpression be = null;
var onLHS = this.lhs;
this.lhs = false; // only the right-most member is a l-value: all other member accesses are for r-value.
var s = o.Symbol;
if (s != null) {
switch (s.Kind) {
case CommonSymbolKind.Method:
R.MethodSymbol ms = (R.MethodSymbol)s;
instance = null;
if (!s.IsStatic) {
instance = this.Visit(node.Expression);
}
var mr = this.mapper.Map(ms);
be = new BoundExpression() {
Definition = mr,
Instance = instance,
Locations = Helper.SourceLocation(this.tree, node),
Type = mr.Type,
};
return be;
case CommonSymbolKind.Field:
FieldSymbol fs = (FieldSymbol)s;
instance = null;
if (!fs.IsStatic) {
instance = this.Visit(node.Expression);
}
var fr = this.mapper.Map(fs);
// Certain fields represent compile-time constants
// REVIEW: Is this the right place to do this?
// TODO: All the rest of the constants...
if (fr.ContainingType.InternedKey == this.host.PlatformType.SystemInt32.InternedKey) {
if (fr.Name.Value.Equals("MinValue")) {
return new CompileTimeConstant() { Type = fr.Type, Value = Int32.MinValue, };
} else if (fr.Name.Value.Equals("MaxValue")) {
return new CompileTimeConstant() { Type = fr.Type, Value = Int32.MaxValue, };
}
}
be = new BoundExpression() {
Definition = fr,
Instance = instance,
Locations = Helper.SourceLocation(this.tree, node),
Type = fr.Type,
};
return be;
case CommonSymbolKind.Property:
R.PropertySymbol ps = (R.PropertySymbol)s;
instance = null;
if (!ps.IsStatic) {
instance = this.Visit(node.Expression);
}
var accessor = onLHS ? this.mapper.Map(ps.SetMethod) : this.mapper.Map(ps.GetMethod);
if (!onLHS && MemberHelper.GetMemberSignature(accessor, NameFormattingOptions.None).Contains("Length")) {
return new VectorLength() {
Locations = Helper.SourceLocation(this.tree, node),
Type = accessor.Type,
Vector = instance,
};
}
return new MethodCall() {
MethodToCall = accessor,
IsStaticCall = ps.IsStatic,
Locations = Helper.SourceLocation(this.tree, node),
ThisArgument = instance,
Type = accessor.Type,
};
default:
throw new InvalidDataException("VisitMemberAccessExpression: uknown definition kind: " + s.Kind);
}
}
throw new InvalidDataException("VisitMemberAccessExpression couldn't find something to return");
}
[ContractVerification(false)]
public override IExpression VisitInvocationExpression(InvocationExpressionSyntax node) {
var o = this.semanticModel.GetSymbolInfo(node);
var args = new List<IExpression>();
foreach (var a in node.ArgumentList.Arguments) {
var a_prime = this.Visit(a);
args.Add(a_prime);
}
var s = o.Symbol;
if (s != null) {
MethodSymbol ms = s as MethodSymbol;
IMethodReference mtc = this.mapper.Map(ms);
IExpression thisArg;
thisArg = null;
if (!ms.IsStatic) {
var be = (BoundExpression) this.Visit(node.Expression);
thisArg = be.Instance;
}
//if (MemberHelper.GetMethodSignature(mtc, NameFormattingOptions.None).Contains("Length")) {
// return new VectorLength() {
// Type = mtc.Type,
// Vector = thisArg,
// };
//}
var mc = new MethodCall() {
Arguments = args,
IsStaticCall = ms.IsStatic,
Locations = Helper.SourceLocation(this.tree, node),
MethodToCall = mtc,
ThisArgument = thisArg,
Type = mtc.Type,
};
return mc;
}
throw new InvalidDataException("VisitInvocationExpression couldn't find something to return");
}
public override IExpression VisitIdentifierName(IdentifierNameSyntax node) {
var o = this.semanticModel.GetSymbolInfo(node);
var s = o.Symbol;
if (s != null) {
switch (s.Kind) {
case CommonSymbolKind.Field:
var f = this.mapper.Map(s as FieldSymbol);
var t = f.ContainingType;
return new BoundExpression() {
Definition = f,
Instance = s.IsStatic ? null : new ThisReference() { Type = t, },
Type = f.Type,
};
case CommonSymbolKind.Parameter:
var p = s as ParameterSymbol;
var m = (IMethodDefinition) this.mapper.Map(p.ContainingSymbol as MethodSymbol);
var p_prime = this.parameters[m][p.Ordinal];
if (p_prime.IsIn) {
return new BoundExpression() {
Definition = p_prime,
Instance = null,
Locations = Helper.SourceLocation(this.tree, node),
Type = p_prime.Type,
};
} else if (p_prime.IsOut || p_prime.IsByReference) {
var locs = Helper.SourceLocation(this.tree, node);
return new AddressDereference() {
Address = new BoundExpression() {
Definition = p_prime,
Instance = null,
Locations = locs,
Type = Microsoft.Cci.Immutable.ManagedPointerType.GetManagedPointerType(p_prime.Type, this.host.InternFactory),
},
Locations = locs,
Type = p_prime.Type,
};
} else {
throw new InvalidDataException("VisitIdentifierName given a parameter that is neither in, out, nor ref: " + p.Name);
}
case CommonSymbolKind.Local:
var l = s as LocalSymbol;
var l_prime = this.locals[l];
return new BoundExpression() {
Definition = l_prime,
Instance = null,
Locations = Helper.SourceLocation(this.tree, node),
Type = l_prime.Type,
};
case CommonSymbolKind.Method:
var m2 = this.mapper.Map(s as MethodSymbol);
var t2 = m2.ContainingType;
return new BoundExpression() {
Definition = m2,
Instance = s.IsStatic ? null : new ThisReference() { Type = t2, },
Type = t2,
};
default:
throw new InvalidDataException("VisitIdentifierName passed an unknown symbol kind: " + s.Kind);
}
}
return CodeDummy.Expression;
}
public override IExpression VisitElementAccessExpression(ElementAccessExpressionSyntax node) {
var indices = new List<IExpression>();
foreach (var i in node.ArgumentList.Arguments) {
var i_prime = this.Visit(i);
indices.Add(i_prime);
}
var indexedObject = this.Visit(node.Expression);
// Can index an array
var arrType = indexedObject.Type as IArrayTypeReference;
if (arrType != null) {
return new ArrayIndexer() {
IndexedObject = indexedObject,
Indices = indices,
Locations = Helper.SourceLocation(this.tree, node),
Type = arrType.ElementType,
};
}
// Otherwise the indexer represents a call to the setter or getter for the default indexed property
// This shows that the target of the translator should really be the Ast model and not the CodeModel
// because it already handles this sort of thing.
if (TypeHelper.TypesAreEquivalent(indexedObject.Type, this.host.PlatformType.SystemString)) {
return new MethodCall(){
Arguments = indices,
IsVirtualCall = true,
Locations = Helper.SourceLocation(this.tree, node),
MethodToCall = TypeHelper.GetMethod(this.host.PlatformType.SystemString.ResolvedType, this.host.NameTable.GetNameFor("get_Chars"), this.host.PlatformType.SystemInt32),
ThisArgument = indexedObject,
Type = this.host.PlatformType.SystemChar,
};
}
throw new InvalidDataException("VisitElementAccessExpression couldn't find something to return");
}
public override IExpression VisitConditionalExpression(ConditionalExpressionSyntax node) {
var o = this.semanticModel.GetTypeInfo(node);
var t = this.mapper.Map(o.Type);
return new Conditional() {
Condition = this.Visit(node.Condition),
Locations = Helper.SourceLocation(this.tree, node),
ResultIfFalse = this.Visit(node.WhenFalse),
ResultIfTrue = this.Visit(node.WhenTrue),
Type = t,
};
}
public override IExpression VisitCastExpression(CastExpressionSyntax node) {
var o = this.semanticModel.GetTypeInfo(node);
var t = this.mapper.Map(o.Type);
var result = new Microsoft.Cci.MutableCodeModel.Conversion() {
ValueToConvert = this.Visit(node.Expression),
Type = t,
TypeAfterConversion = t,
};
return result;
}
public override IExpression VisitBinaryExpression(BinaryExpressionSyntax node) {
var o = this.semanticModel.GetTypeInfo(node);
var t = this.mapper.Map(o.Type);
if (node.Kind == SyntaxKind.AssignExpression)
this.lhs = true;
var left = this.Visit(node.Left);
this.lhs = false;
var right = this.Visit(node.Right);
BinaryOperation op = null;
var locs = Helper.SourceLocation(this.tree, node);
switch (node.Kind) {
case SyntaxKind.AddAssignExpression: {
var a = new Assignment() {
Locations = locs,
Source = new Addition() {
LeftOperand = left,
RightOperand =right,
},
Target = Helper.MakeTargetExpression(left),
Type = t,
};
return a;
}
case SyntaxKind.AddExpression:
op = new Addition();
break;
case SyntaxKind.AssignExpression: {
var mc = left as MethodCall;
if (mc != null) {
// then this is really o.P = e for some property P
// and the property access has been translated into a call
// to set_P.
mc.Arguments = new List<IExpression> { right, };
return mc;
}
var be = left as BoundExpression;
if (be != null) {
var a = new Assignment() {
Locations = locs,
Source = right,
Target = new TargetExpression() {
Definition = be.Definition,
Instance = be.Instance,
Type = be.Type,
},
Type = t,
};
return a;
}
var arrayIndexer = left as ArrayIndexer;
if (arrayIndexer != null) {
var a = new Assignment() {
Locations = locs,
Source = right,
Target = new TargetExpression() {
Definition = arrayIndexer,
Instance = arrayIndexer.IndexedObject,
Type = right.Type,
},
Type = t,
};
return a;
}
var addressDereference = left as AddressDereference;
if (addressDereference != null) {
var a = new Assignment() {
Locations = locs,
Source = right,
Target = new TargetExpression() {
Definition = addressDereference,
Instance = null,
Type = t,
},
Type = t,
};
return a;
}
throw new InvalidDataException("VisitBinaryExpression: Can't figure out lhs in assignment" + left.Type.ToString());
}
case SyntaxKind.BitwiseAndExpression: op = new BitwiseAnd(); break;
case SyntaxKind.BitwiseOrExpression: op = new BitwiseOr(); break;
case SyntaxKind.DivideExpression: op = new Division(); break;
case SyntaxKind.EqualsExpression: op = new Equality(); break;
case SyntaxKind.ExclusiveOrExpression: op = new ExclusiveOr(); break;
case SyntaxKind.GreaterThanExpression: op = new GreaterThan(); break;
case SyntaxKind.GreaterThanOrEqualExpression: op = new GreaterThanOrEqual(); break;
case SyntaxKind.LeftShiftExpression: op = new LeftShift(); break;
case SyntaxKind.LessThanExpression: op = new LessThan(); break;
case SyntaxKind.LessThanOrEqualExpression: op = new LessThanOrEqual(); break;
case SyntaxKind.LogicalAndExpression:
return new Conditional() {
Condition = left,
Locations = locs,
ResultIfTrue = right,
ResultIfFalse = new CompileTimeConstant() { Type = t, Value = false },
Type = t,
};
case SyntaxKind.LogicalOrExpression:
return new Conditional() {
Condition = left,
Locations = Helper.SourceLocation(this.tree, node),
ResultIfTrue = new CompileTimeConstant() { Type = t, Value = true },
ResultIfFalse = right,
Type = t,
};
case SyntaxKind.ModuloExpression: op = new Modulus(); break;
case SyntaxKind.MultiplyExpression: op = new Multiplication(); break;
case SyntaxKind.NotEqualsExpression: op = new NotEquality(); break;
case SyntaxKind.RightShiftExpression: op = new RightShift(); break;
case SyntaxKind.SubtractAssignExpression: {
var a = new Assignment() {
Locations = locs,
Source = new Subtraction() {
LeftOperand = left,
RightOperand = right,
},
Target = Helper.MakeTargetExpression(left),
Type = t,
};
return a;
}
case SyntaxKind.MultiplyAssignExpression:
{
var a = new Assignment()
{
Locations = locs,
Source = new Multiplication()
{
LeftOperand = left,
RightOperand = right,
},
Target = Helper.MakeTargetExpression(left),
Type = t,
};
return a;
}
case SyntaxKind.DivideAssignExpression:
{
var a = new Assignment()
{
Locations = locs,
Source = new Division()
{
LeftOperand = left,
RightOperand = right,
},
Target = Helper.MakeTargetExpression(left),
Type = t,
};
return a;
}
case SyntaxKind.ModuloAssignExpression:
{
var a = new Assignment()
{
Locations = locs,
Source = new Modulus()
{
LeftOperand = left,
RightOperand = right,
},
Target = Helper.MakeTargetExpression(left),
Type = t,
};
return a;
}
case SyntaxKind.SubtractExpression: op = new Subtraction(); break;
default:
throw new InvalidDataException("VisitBinaryExpression: unknown node = " + node.Kind);
}
op.Locations = locs;
op.LeftOperand = left;
op.RightOperand = right;
op.Type = t;
return op;
}
// TODO: Handle multi-dimensional arrays
public override IExpression VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) {
var o = this.semanticModel.GetSymbolInfo(node);
var s = o.Symbol;
var arrayType = node.Type;
var elementType = this.mapper.Map(this.semanticModel.GetTypeInfo(arrayType.ElementType).Type);
var arrayOfType = Microsoft.Cci.Immutable.Vector.GetVector(elementType, this.host.InternFactory);
List<IExpression> inits = null;
int size = 0;
if (node.Initializer != null) {
inits = new List<IExpression>();
foreach (var i in node.Initializer.Expressions) {
var e = this.Visit(i);
inits.Add(e);
size++;
}
}
var result = new CreateArray() {
ElementType = elementType,
Rank = 1,
Type = arrayOfType,
};
if (inits != null) {
result.Initializers = inits;
result.Sizes = new List<IExpression> { new CompileTimeConstant() { Value = size, }, };
} else {
var rankSpecs = arrayType.RankSpecifiers;
foreach (var r in rankSpecs) {
foreach (var rs in r.Sizes) {
var e = this.Visit(rs);
result.Sizes = new List<IExpression> { e, };
break;
}
break;
}
}
return result;
}
public override IExpression VisitArgument(ArgumentSyntax node) {
var a = this.Visit(node.Expression);
if (node.RefOrOutKeyword.Kind != SyntaxKind.None) {
object def = a;
IExpression instance = null;
var be = a as IBoundExpression;
if (be != null) { // REVIEW: Maybe it should always be a bound expression?
def = be.Definition;
instance = be.Instance;
}
a = new AddressOf() {
Expression = new AddressableExpression() {
Definition = def,
Instance = instance,
Locations = new List<ILocation>(a.Locations),
},
Locations = new List<ILocation>(a.Locations),
Type = Microsoft.Cci.Immutable.ManagedPointerType.GetManagedPointerType(a.Type, this.host.InternFactory),
};
}
return a;
}
public override IExpression DefaultVisit(SyntaxNode node) {
// If you hit this, it means there was some sort of CS construct
// that we haven't written a conversion routine for. Simply add
// it above and rerun.
var typeName = node.GetType().ToString();
var msg = String.Format("Was unable to convert a {0} node to CCI", typeName);
throw new ConverterException(msg);
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
[ExportFormattingRule(Name, LanguageNames.CSharp), Shared]
[ExtensionOrder(After = QueryExpressionFormattingRule.Name)]
internal class TokenBasedFormattingRule : BaseFormattingRule
{
internal const string Name = "CSharp Token Based Formatting Rule";
public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation<AdjustNewLinesOperation> nextOperation)
{
////////////////////////////////////////////////////
// brace related operations
// * { or * }
switch (currentToken.Kind())
{
case SyntaxKind.OpenBraceToken:
if (!previousToken.IsParenInParenthesizedExpression() && previousToken.Parent != null && !previousToken.Parent.IsKind(SyntaxKind.ArrayRankSpecifier))
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
break;
}
// do { } while case
if (previousToken.Kind() == SyntaxKind.CloseBraceToken && currentToken.Kind() == SyntaxKind.WhileKeyword)
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// { * or } *
switch (previousToken.Kind())
{
case SyntaxKind.CloseBraceToken:
if (!previousToken.IsCloseBraceOfExpression())
{
if (currentToken.Kind() != SyntaxKind.SemicolonToken &&
!currentToken.IsParenInParenthesizedExpression() &&
!currentToken.IsCommaInInitializerExpression() &&
!currentToken.IsCommaInAnyArgumentsList() &&
!currentToken.IsParenInArgumentList() &&
!currentToken.IsDotInMemberAccess() &&
!currentToken.IsCloseParenInStatement())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
}
break;
case SyntaxKind.OpenBraceToken:
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
///////////////////////////////////////////////////
// statement related operations
// object and anonymous initializer "," case
if (previousToken.IsCommaInInitializerExpression())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// else * except else if case
if (previousToken.Kind() == SyntaxKind.ElseKeyword && currentToken.Kind() != SyntaxKind.IfKeyword)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// , * in enum declarations
if (previousToken.IsCommaInEnumDeclaration())
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// : cases
if (previousToken.IsColonInSwitchLabel() ||
previousToken.IsColonInLabeledStatement())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// embedded statement
if (previousToken.Kind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
if (previousToken.Kind() == SyntaxKind.DoKeyword && previousToken.Parent.Kind() == SyntaxKind.DoStatement)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// for (int i = 10; i < 10; i++) case
if (previousToken.IsSemicolonInForStatement())
{
return nextOperation.Invoke();
}
// ; case in the switch case statement and else condition
if (previousToken.Kind() == SyntaxKind.SemicolonToken &&
(currentToken.Kind() == SyntaxKind.CaseKeyword || currentToken.Kind() == SyntaxKind.DefaultKeyword || currentToken.Kind() == SyntaxKind.ElseKeyword))
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// ; * or ; * for using directive
if (previousToken.Kind() == SyntaxKind.SemicolonToken)
{
var line = (previousToken.Parent is UsingDirectiveSyntax) ? 1 : 0;
return CreateAdjustNewLinesOperation(line, AdjustNewLinesOption.PreserveLines);
}
// attribute case ] *
// force to next line for top level attributes
if (previousToken.Kind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
{
var attributeOwner = (previousToken.Parent != null) ? previousToken.Parent.Parent : null;
if (attributeOwner is CompilationUnitSyntax ||
attributeOwner is MemberDeclarationSyntax ||
attributeOwner is AccessorDeclarationSyntax)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
return nextOperation.Invoke();
}
public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation<AdjustSpacesOperation> nextOperation)
{
////////////////////////////////////////////////////
// brace related operations
// * { or * }
switch (currentToken.Kind())
{
case SyntaxKind.CloseBraceToken:
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
//////////////////////////////////////////////////////
// ";" related operations
if (currentToken.Kind() == SyntaxKind.SemicolonToken)
{
// ; ;
if (previousToken.Kind() == SyntaxKind.SemicolonToken)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ) ; with embedded statement case
if (previousToken.Kind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * ;
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// omitted tokens case
if (previousToken.Kind() == SyntaxKind.OmittedArraySizeExpressionToken ||
previousToken.Kind() == SyntaxKind.OmittedTypeArgumentToken ||
currentToken.Kind() == SyntaxKind.OmittedArraySizeExpressionToken ||
currentToken.Kind() == SyntaxKind.OmittedTypeArgumentToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// some * "(" cases
if (currentToken.Kind() == SyntaxKind.OpenParenToken)
{
if (previousToken.Kind() == SyntaxKind.IdentifierToken ||
previousToken.Kind() == SyntaxKind.DefaultKeyword ||
previousToken.Kind() == SyntaxKind.BaseKeyword ||
previousToken.Kind() == SyntaxKind.ThisKeyword ||
previousToken.Kind() == SyntaxKind.NewKeyword ||
previousToken.Parent.Kind() == SyntaxKind.OperatorDeclaration ||
previousToken.IsGenericGreaterThanToken() ||
currentToken.IsParenInArgumentList())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// empty () or []
if (previousToken.ParenOrBracketContainsNothing(currentToken))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// attribute case
// , [
if (previousToken.Kind() == SyntaxKind.CommaToken && currentToken.Kind() == SyntaxKind.OpenBracketToken && currentToken.Parent is AttributeListSyntax)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ] *
if (previousToken.Kind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
{
// preserving dev10 behavior, in dev10 we didn't touch space after attribute
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces);
}
// * )
// * [
// * ]
// * ,
// * .
// * ->
switch (currentToken.Kind())
{
case SyntaxKind.CloseParenToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.CloseBracketToken:
case SyntaxKind.CommaToken:
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// case * :
// default:
// <label> :
if (currentToken.IsKind(SyntaxKind.ColonToken))
{
if (currentToken.Parent.IsKind(SyntaxKind.CaseSwitchLabel,
SyntaxKind.DefaultSwitchLabel,
SyntaxKind.LabeledStatement,
SyntaxKind.AttributeTargetSpecifier,
SyntaxKind.NameColon))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// [cast expression] * case
if (previousToken.Parent is CastExpressionSyntax &&
previousToken.Kind() == SyntaxKind.CloseParenToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// generic name
if (previousToken.Parent.Kind() == SyntaxKind.TypeArgumentList || previousToken.Parent.Kind() == SyntaxKind.TypeParameterList)
{
// generic name < *
if (previousToken.Kind() == SyntaxKind.LessThanToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// generic name > *
if (previousToken.Kind() == SyntaxKind.GreaterThanToken && currentToken.Kind() == SyntaxKind.GreaterThanToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// generic name * < or * >
if ((currentToken.Kind() == SyntaxKind.LessThanToken || currentToken.Kind() == SyntaxKind.GreaterThanToken) &&
(currentToken.Parent.Kind() == SyntaxKind.TypeArgumentList || currentToken.Parent.Kind() == SyntaxKind.TypeParameterList))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ++ * or -- *
if ((previousToken.Kind() == SyntaxKind.PlusPlusToken || previousToken.Kind() == SyntaxKind.MinusMinusToken) &&
previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * ++ or * --
if ((currentToken.Kind() == SyntaxKind.PlusPlusToken || currentToken.Kind() == SyntaxKind.MinusMinusToken) &&
currentToken.Parent is PostfixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// For spacing between the identifer and the conditional operator
if (currentToken.IsKind(SyntaxKind.QuestionToken) && currentToken.Parent.Kind() == SyntaxKind.ConditionalAccessExpression)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ( * or ) * or [ * or ] * or . * or -> *
switch (previousToken.Kind())
{
case SyntaxKind.OpenParenToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
case SyntaxKind.CloseParenToken:
case SyntaxKind.CloseBracketToken:
int space = (previousToken.Kind() == currentToken.Kind()) ? 0 : 1;
return CreateAdjustSpacesOperation(space, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// +1 or -1
if (previousToken.IsPlusOrMinusExpression() && !currentToken.IsPlusOrMinusExpression())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// +- or -+
if (previousToken.IsPlusOrMinusExpression() && currentToken.IsPlusOrMinusExpression() &&
previousToken.Kind() != currentToken.Kind())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ! *
if (previousToken.Kind() == SyntaxKind.ExclamationToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// nullable
if (currentToken.Kind() == SyntaxKind.QuestionToken &&
currentToken.Parent.Kind() == SyntaxKind.NullableType)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// pointer case
if ((currentToken.Kind() == SyntaxKind.AsteriskToken && currentToken.Parent is PointerTypeSyntax) ||
(previousToken.Kind() == SyntaxKind.AsteriskToken && previousToken.Parent is PrefixUnaryExpressionSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ~ * case
if (previousToken.Kind() == SyntaxKind.TildeToken && (previousToken.Parent is PrefixUnaryExpressionSyntax || previousToken.Parent is DestructorDeclarationSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// & * case
if (previousToken.Kind() == SyntaxKind.AmpersandToken &&
previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * :: or :: * case
if (previousToken.Kind() == SyntaxKind.ColonColonToken || currentToken.Kind() == SyntaxKind.ColonColonToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
return nextOperation.Invoke();
}
}
}
| |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;
// GVR soundfield component that allows playback of first-order ambisonic recordings. The
// audio sample should be in Ambix (ACN-SN3D) format.
[AddComponentMenu("GoogleVR/Audio/GvrAudioSoundfield")]
public class GvrAudioSoundfield : MonoBehaviour {
/// Denotes whether the room effects should be bypassed.
public bool bypassRoomEffects = true;
/// Input gain in decibels.
public float gainDb = 0.0f;
/// Play source on awake.
public bool playOnAwake = true;
/// The default AudioClip to play.
public AudioClip clip0102 {
get { return soundfieldClip0102; }
set {
soundfieldClip0102 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[0].clip = soundfieldClip0102;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0102 = null;
public AudioClip clip0304 {
get { return soundfieldClip0304; }
set {
soundfieldClip0304 = value;
if (audioSources != null && audioSources.Length > 0) {
audioSources[1].clip = soundfieldClip0304;
}
}
}
[SerializeField]
private AudioClip soundfieldClip0304 = null;
/// Is the clip playing right now (Read Only)?
public bool isPlaying {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].isPlaying;
}
return false;
}
}
/// Is the audio clip looping?
public bool loop {
get { return soundfieldLoop; }
set {
soundfieldLoop = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].loop = soundfieldLoop;
}
}
}
}
[SerializeField]
private bool soundfieldLoop = false;
/// Un- / Mutes the soundfield. Mute sets the volume=0, Un-Mute restore the original volume.
public bool mute {
get { return soundfieldMute; }
set {
soundfieldMute = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].mute = soundfieldMute;
}
}
}
}
[SerializeField]
private bool soundfieldMute = false;
/// The pitch of the audio source.
public float pitch {
get { return soundfieldPitch; }
set {
soundfieldPitch = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].pitch = soundfieldPitch;
}
}
}
}
[SerializeField]
[Range(-3.0f, 3.0f)]
private float soundfieldPitch = 1.0f;
/// Sets the priority of the soundfield.
public int priority {
get { return soundfieldPriority; }
set {
soundfieldPriority = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].priority = soundfieldPriority;
}
}
}
}
[SerializeField]
[Range(0, 256)]
private int soundfieldPriority = 32;
/// Playback position in seconds.
public float time {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].time;
}
return 0.0f;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].time = value;
}
}
}
}
/// Playback position in PCM samples.
public int timeSamples {
get {
if(audioSources != null && audioSources.Length > 0) {
return audioSources[0].timeSamples;
}
return 0;
}
set {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].timeSamples = value;
}
}
}
}
/// The volume of the audio source (0.0 to 1.0).
public float volume {
get { return soundfieldVolume; }
set {
soundfieldVolume = value;
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].volume = soundfieldVolume;
}
}
}
}
[SerializeField]
[Range(0.0f, 1.0f)]
private float soundfieldVolume = 1.0f;
// Unique source id.
private int id = -1;
// Unity audio sources per each soundfield channel set.
private AudioSource[] audioSources = null;
// Denotes whether the source is currently paused or not.
private bool isPaused = false;
void Awake () {
// Route the source output to |GvrAudioMixer|.
AudioMixer mixer = (Resources.Load("GvrAudioMixer") as AudioMixer);
if(mixer == null) {
Debug.LogError("GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK" +
"Unity package is imported properly.");
return;
}
audioSources = new AudioSource[GvrAudio.numFoaChannels / 2];
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
GameObject channelSetObject = new GameObject("Channel Set " + channelSet);
channelSetObject.transform.parent = gameObject.transform;
channelSetObject.transform.localPosition = Vector3.zero;
channelSetObject.transform.localRotation = Quaternion.identity;
channelSetObject.hideFlags = HideFlags.HideAndDontSave;
audioSources[channelSet] = channelSetObject.AddComponent<AudioSource>();
audioSources[channelSet].enabled = false;
audioSources[channelSet].playOnAwake = false;
audioSources[channelSet].bypassReverbZones = true;
audioSources[channelSet].dopplerLevel = 0.0f;
audioSources[channelSet].spatialBlend = 0.0f;
#if UNITY_5_5_OR_NEWER
audioSources[channelSet].spatializePostEffects = true;
#endif // UNITY_5_5_OR_NEWER
audioSources[channelSet].outputAudioMixerGroup = mixer.FindMatchingGroups("Master")[0];
}
OnValidate();
}
void OnEnable () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = true;
}
if (playOnAwake && !isPlaying && InitializeSoundfield()) {
Play();
}
}
void Start () {
if (playOnAwake && !isPlaying) {
Play();
}
}
void OnDisable () {
Stop();
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].enabled = false;
}
}
void OnDestroy () {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
Destroy(audioSources[channelSet].gameObject);
}
}
void OnApplicationPause (bool pauseStatus) {
if (pauseStatus) {
Pause();
} else {
UnPause();
}
}
void Update () {
// Update soundfield.
if (!isPlaying && !isPaused) {
Stop();
} else {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
}
}
GvrAudio.UpdateAudioSoundfield(id, this);
}
void OnValidate () {
clip0102 = soundfieldClip0102;
clip0304 = soundfieldClip0304;
loop = soundfieldLoop;
mute = soundfieldMute;
pitch = soundfieldPitch;
priority = soundfieldPriority;
volume = soundfieldVolume;
}
/// Pauses playing the clip.
public void Pause () {
if (audioSources != null) {
isPaused = true;
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Pause();
}
}
}
/// Plays the clip.
public void Play () {
double dspTime = AudioSettings.dspTime;
PlayScheduled(dspTime);
}
/// Plays the clip with a delay specified in seconds.
public void PlayDelayed (float delay) {
double delayedDspTime = AudioSettings.dspTime + (double)delay;
PlayScheduled(delayedDspTime);
}
/// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads
/// from.
public void PlayScheduled (double time) {
if (audioSources != null && InitializeSoundfield()) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].PlayScheduled(time);
}
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio soundfield not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Stops playing the clip.
public void Stop () {
if(audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].Stop();
}
ShutdownSoundfield();
isPaused = false;
}
}
/// Unpauses the paused playback.
public void UnPause () {
if (audioSources != null) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
audioSources[channelSet].UnPause();
}
isPaused = true;
}
}
// Initializes the source.
private bool InitializeSoundfield () {
if (id < 0) {
id = GvrAudio.CreateAudioSoundfield();
if (id >= 0) {
GvrAudio.UpdateAudioSoundfield(id, this);
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
InitializeChannelSet(audioSources[channelSet], channelSet);
}
}
}
return id >= 0;
}
// Shuts down the source.
private void ShutdownSoundfield () {
if (id >= 0) {
for (int channelSet = 0; channelSet < audioSources.Length; ++channelSet) {
ShutdownChannelSet(audioSources[channelSet], channelSet);
}
GvrAudio.DestroyAudioSource(id);
id = -1;
}
}
// Initializes given channel set of the soundfield.
private void InitializeChannelSet(AudioSource source, int channelSet) {
source.spatialize = true;
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Type,
(float) GvrAudio.SpatializerType.Soundfield);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.NumChannels,
(float) GvrAudio.numFoaChannels);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ChannelSet, (float) channelSet);
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 0.0f);
// Soundfield id must be set after all the spatializer parameters, to ensure that the soundfield
// is properly initialized before processing.
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, (float) id);
}
// Shuts down given channel set of the soundfield.
private void ShutdownChannelSet(AudioSource source, int channelSet) {
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, -1.0f);
// Ensure that the output is zeroed after shutdown.
source.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 1.0f);
source.spatialize = false;
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.ElasticLoadBalancing.Model;
namespace Amazon.ElasticLoadBalancing
{
/// <summary>
/// Interface for accessing ElasticLoadBalancing
///
/// Elastic Load Balancing
/// <para>
/// Elastic Load Balancing automatically distributes incoming web traffic across multiple
/// Amazon EC2 instances.
/// </para>
///
/// <para>
/// All Elastic Load Balancing actions and commands are <i>idempotent</i>, which means
/// that they complete no more than one time. If you repeat a request or a command, the
/// action succeeds with a 200 OK response code.
/// </para>
///
/// <para>
/// For detailed information about the features of Elastic Load Balancing, see <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/UserScenarios.html">Managing
/// Load Balancers</a> in the <i>Elastic Load Balancing Developer Guide</i>.
/// </para>
/// </summary>
public partial interface IAmazonElasticLoadBalancing : IDisposable
{
#region AddTags
/// <summary>
/// Initiates the asynchronous execution of the AddTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddTags operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AddTagsResponse> AddTagsAsync(AddTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ApplySecurityGroupsToLoadBalancer
/// <summary>
/// Initiates the asynchronous execution of the ApplySecurityGroupsToLoadBalancer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ApplySecurityGroupsToLoadBalancer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ApplySecurityGroupsToLoadBalancerResponse> ApplySecurityGroupsToLoadBalancerAsync(ApplySecurityGroupsToLoadBalancerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region AttachLoadBalancerToSubnets
/// <summary>
/// Initiates the asynchronous execution of the AttachLoadBalancerToSubnets operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AttachLoadBalancerToSubnets operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AttachLoadBalancerToSubnetsResponse> AttachLoadBalancerToSubnetsAsync(AttachLoadBalancerToSubnetsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ConfigureHealthCheck
/// <summary>
/// Initiates the asynchronous execution of the ConfigureHealthCheck operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ConfigureHealthCheck operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ConfigureHealthCheckResponse> ConfigureHealthCheckAsync(ConfigureHealthCheckRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateAppCookieStickinessPolicy
/// <summary>
/// Initiates the asynchronous execution of the CreateAppCookieStickinessPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateAppCookieStickinessPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateAppCookieStickinessPolicyResponse> CreateAppCookieStickinessPolicyAsync(CreateAppCookieStickinessPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateLBCookieStickinessPolicy
/// <summary>
/// Initiates the asynchronous execution of the CreateLBCookieStickinessPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLBCookieStickinessPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateLBCookieStickinessPolicyResponse> CreateLBCookieStickinessPolicyAsync(CreateLBCookieStickinessPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateLoadBalancer
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLoadBalancer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateLoadBalancerResponse> CreateLoadBalancerAsync(CreateLoadBalancerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateLoadBalancerListeners
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancerListeners operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLoadBalancerListeners operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateLoadBalancerListenersResponse> CreateLoadBalancerListenersAsync(CreateLoadBalancerListenersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateLoadBalancerPolicy
/// <summary>
/// Initiates the asynchronous execution of the CreateLoadBalancerPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLoadBalancerPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateLoadBalancerPolicyResponse> CreateLoadBalancerPolicyAsync(CreateLoadBalancerPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteLoadBalancer
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLoadBalancer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteLoadBalancerResponse> DeleteLoadBalancerAsync(DeleteLoadBalancerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteLoadBalancerListeners
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancerListeners operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLoadBalancerListeners operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteLoadBalancerListenersResponse> DeleteLoadBalancerListenersAsync(DeleteLoadBalancerListenersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteLoadBalancerPolicy
/// <summary>
/// Initiates the asynchronous execution of the DeleteLoadBalancerPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLoadBalancerPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteLoadBalancerPolicyResponse> DeleteLoadBalancerPolicyAsync(DeleteLoadBalancerPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeregisterInstancesFromLoadBalancer
/// <summary>
/// Initiates the asynchronous execution of the DeregisterInstancesFromLoadBalancer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeregisterInstancesFromLoadBalancer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeregisterInstancesFromLoadBalancerResponse> DeregisterInstancesFromLoadBalancerAsync(DeregisterInstancesFromLoadBalancerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeInstanceHealth
/// <summary>
/// Initiates the asynchronous execution of the DescribeInstanceHealth operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeInstanceHealth operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeInstanceHealthResponse> DescribeInstanceHealthAsync(DescribeInstanceHealthRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeLoadBalancerAttributes
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancerAttributes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeLoadBalancerAttributes operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeLoadBalancerAttributesResponse> DescribeLoadBalancerAttributesAsync(DescribeLoadBalancerAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeLoadBalancerPolicies
/// <summary>
/// Describes the specified policies.
///
///
/// <para>
/// If you specify a load balancer name, the action returns the descriptions of all policies
/// created for the load balancer. If you specify a policy name associated with your load
/// balancer, the action returns the description of that policy. If you don't specify
/// a load balancer name, the action returns descriptions of the specified sample policies,
/// or descriptions of all sample policies. The names of the sample policies have the
/// <code>ELBSample-</code> prefix.
/// </para>
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeLoadBalancerPolicies service method, as returned by ElasticLoadBalancing.</returns>
/// <exception cref="Amazon.ElasticLoadBalancing.Model.AccessPointNotFoundException">
/// The specified load balancer does not exist.
/// </exception>
/// <exception cref="Amazon.ElasticLoadBalancing.Model.PolicyNotFoundException">
/// One or more of the specified policies do not exist.
/// </exception>
Task<DescribeLoadBalancerPoliciesResponse> DescribeLoadBalancerPoliciesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancerPolicies operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeLoadBalancerPolicies operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeLoadBalancerPoliciesResponse> DescribeLoadBalancerPoliciesAsync(DescribeLoadBalancerPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeLoadBalancerPolicyTypes
/// <summary>
/// Describes the specified load balancer policy types.
///
///
/// <para>
/// You can use these policy types with <a>CreateLoadBalancerPolicy</a> to create policy
/// configurations for a load balancer.
/// </para>
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeLoadBalancerPolicyTypes service method, as returned by ElasticLoadBalancing.</returns>
/// <exception cref="Amazon.ElasticLoadBalancing.Model.PolicyTypeNotFoundException">
/// One or more of the specified policy types do not exist.
/// </exception>
Task<DescribeLoadBalancerPolicyTypesResponse> DescribeLoadBalancerPolicyTypesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancerPolicyTypes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeLoadBalancerPolicyTypes operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeLoadBalancerPolicyTypesResponse> DescribeLoadBalancerPolicyTypesAsync(DescribeLoadBalancerPolicyTypesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeLoadBalancers
/// <summary>
/// Describes the specified the load balancers. If no load balancers are specified, the
/// call describes all of your load balancers.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeLoadBalancers service method, as returned by ElasticLoadBalancing.</returns>
/// <exception cref="Amazon.ElasticLoadBalancing.Model.AccessPointNotFoundException">
/// The specified load balancer does not exist.
/// </exception>
Task<DescribeLoadBalancersResponse> DescribeLoadBalancersAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the DescribeLoadBalancers operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeLoadBalancers operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeLoadBalancersResponse> DescribeLoadBalancersAsync(DescribeLoadBalancersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeTags
/// <summary>
/// Initiates the asynchronous execution of the DescribeTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTags operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeTagsResponse> DescribeTagsAsync(DescribeTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DetachLoadBalancerFromSubnets
/// <summary>
/// Initiates the asynchronous execution of the DetachLoadBalancerFromSubnets operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DetachLoadBalancerFromSubnets operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DetachLoadBalancerFromSubnetsResponse> DetachLoadBalancerFromSubnetsAsync(DetachLoadBalancerFromSubnetsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DisableAvailabilityZonesForLoadBalancer
/// <summary>
/// Initiates the asynchronous execution of the DisableAvailabilityZonesForLoadBalancer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DisableAvailabilityZonesForLoadBalancer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DisableAvailabilityZonesForLoadBalancerResponse> DisableAvailabilityZonesForLoadBalancerAsync(DisableAvailabilityZonesForLoadBalancerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region EnableAvailabilityZonesForLoadBalancer
/// <summary>
/// Initiates the asynchronous execution of the EnableAvailabilityZonesForLoadBalancer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EnableAvailabilityZonesForLoadBalancer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<EnableAvailabilityZonesForLoadBalancerResponse> EnableAvailabilityZonesForLoadBalancerAsync(EnableAvailabilityZonesForLoadBalancerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ModifyLoadBalancerAttributes
/// <summary>
/// Initiates the asynchronous execution of the ModifyLoadBalancerAttributes operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ModifyLoadBalancerAttributes operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ModifyLoadBalancerAttributesResponse> ModifyLoadBalancerAttributesAsync(ModifyLoadBalancerAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RegisterInstancesWithLoadBalancer
/// <summary>
/// Initiates the asynchronous execution of the RegisterInstancesWithLoadBalancer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RegisterInstancesWithLoadBalancer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<RegisterInstancesWithLoadBalancerResponse> RegisterInstancesWithLoadBalancerAsync(RegisterInstancesWithLoadBalancerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RemoveTags
/// <summary>
/// Initiates the asynchronous execution of the RemoveTags operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RemoveTags operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<RemoveTagsResponse> RemoveTagsAsync(RemoveTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SetLoadBalancerListenerSSLCertificate
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerListenerSSLCertificate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetLoadBalancerListenerSSLCertificate operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SetLoadBalancerListenerSSLCertificateResponse> SetLoadBalancerListenerSSLCertificateAsync(SetLoadBalancerListenerSSLCertificateRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SetLoadBalancerPoliciesForBackendServer
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerPoliciesForBackendServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetLoadBalancerPoliciesForBackendServer operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SetLoadBalancerPoliciesForBackendServerResponse> SetLoadBalancerPoliciesForBackendServerAsync(SetLoadBalancerPoliciesForBackendServerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SetLoadBalancerPoliciesOfListener
/// <summary>
/// Initiates the asynchronous execution of the SetLoadBalancerPoliciesOfListener operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetLoadBalancerPoliciesOfListener operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SetLoadBalancerPoliciesOfListenerResponse> SetLoadBalancerPoliciesOfListenerAsync(SetLoadBalancerPoliciesOfListenerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
[CustomEditor(typeof(tk2dFont))]
public class tk2dFontEditor : Editor
{
public Shader GetShader(bool gradient, bool packed)
{
if (packed) return Shader.Find("tk2d/Goodies/PackedTextMesh");
else if (gradient) return Shader.Find("tk2d/Blend2TexVertexColor");
else return Shader.Find("tk2d/BlendVertexColor");
}
public override void OnInspectorGUI()
{
tk2dFont gen = (tk2dFont)target;
if (gen.proxyFont)
{
GUILayout.Label("This font is managed by a Sprite Collection");
return;
}
gen.Upgrade();
EditorGUILayout.BeginVertical();
DrawDefaultInspector();
tk2dGuiUtility.SpriteCollectionSize( gen.sizeDef );
// Warning when texture is compressed
if (gen.texture != null)
{
Texture2D tex = (Texture2D)gen.texture;
if (tex && IsTextureCompressed(tex))
{
int buttonPressed;
if ((buttonPressed = tk2dGuiUtility.InfoBoxWithButtons(
"Font texture appears to be compressed. " +
"Quality will be lost and the texture may appear blocky in game.\n" +
"Do you wish to change the format?",
tk2dGuiUtility.WarningLevel.Warning,
new string[] { "16bit", "Truecolor" }
)) != -1)
{
if (buttonPressed == 0)
{
ConvertTextureToFormat(tex, TextureImporterFormat.Automatic16bit);
}
else
{
ConvertTextureToFormat(tex, TextureImporterFormat.AutomaticTruecolor);
}
}
}
}
// Warning when gradient texture is compressed
if (gen.gradientTexture != null &&
(gen.gradientTexture.format != TextureFormat.ARGB32 && gen.gradientTexture.format != TextureFormat.RGB24 && gen.gradientTexture.format != TextureFormat.RGBA32))
{
if (tk2dGuiUtility.InfoBoxWithButtons(
"The gradient texture should be truecolor for best quality. " +
"Current format is " + gen.gradientTexture.format.ToString() + ".",
tk2dGuiUtility.WarningLevel.Warning,
new string[] { "Fix" }
) != -1)
{
ConvertTextureToFormat(gen.gradientTexture, TextureImporterFormat.AutomaticTruecolor);
}
}
if (GUILayout.Button("Commit..."))
{
if (gen.bmFont == null || gen.texture == null)
{
EditorUtility.DisplayDialog("BMFont", "Need an bmFont and texture bound to work", "Ok");
return;
}
if (gen.material == null)
{
gen.material = new Material(GetShader(gen.gradientTexture != null, gen.data != null && gen.data.isPacked));
string materialPath = AssetDatabase.GetAssetPath(gen).Replace(".prefab", "material.mat");
AssetDatabase.CreateAsset(gen.material, materialPath);
}
if (gen.data == null)
{
string bmFontPath = AssetDatabase.GetAssetPath(gen).Replace(".prefab", "data.prefab");
GameObject go = new GameObject();
go.AddComponent<tk2dFontData>();
tk2dEditorUtility.SetGameObjectActive(go, false);
Object p = PrefabUtility.CreateEmptyPrefab(bmFontPath);
PrefabUtility.ReplacePrefab(go, p);
GameObject.DestroyImmediate(go);
AssetDatabase.SaveAssets();
gen.data = AssetDatabase.LoadAssetAtPath(bmFontPath, typeof(tk2dFontData)) as tk2dFontData;
}
ParseBMFont(AssetDatabase.GetAssetPath(gen.bmFont), gen.data, gen);
if (gen.manageMaterial)
{
Shader s = GetShader(gen.gradientTexture != null, gen.data != null && gen.data.isPacked);
if (gen.material.shader != s)
{
gen.material.shader = s;
tk2dUtil.SetDirty(gen.material);
}
if (gen.material.mainTexture != gen.texture)
{
gen.material.mainTexture = gen.texture;
tk2dUtil.SetDirty(gen.material);
}
if (gen.gradientTexture != null && gen.gradientTexture != gen.material.GetTexture("_GradientTex"))
{
gen.material.SetTexture("_GradientTex", gen.gradientTexture);
tk2dUtil.SetDirty(gen.material);
}
}
gen.data.version = tk2dFontData.CURRENT_VERSION;
gen.data.material = gen.material;
gen.data.textureGradients = gen.gradientTexture != null;
gen.data.gradientCount = gen.gradientCount;
gen.data.gradientTexture = gen.gradientTexture;
gen.data.invOrthoSize = 1.0f / gen.sizeDef.OrthoSize;
gen.data.halfTargetHeight = gen.sizeDef.TargetHeight * 0.5f;
// Rebuild assets already present in the scene
tk2dTextMesh[] sprs = Resources.FindObjectsOfTypeAll(typeof(tk2dTextMesh)) as tk2dTextMesh[];
foreach (tk2dTextMesh spr in sprs)
{
spr.Init(true);
}
tk2dUtil.SetDirty(gen);
tk2dUtil.SetDirty(gen.data);
// update index
tk2dEditorUtility.GetOrCreateIndex().AddOrUpdateFont(gen);
tk2dEditorUtility.CommitIndex();
}
EditorGUILayout.EndVertical();
GUILayout.Space(64);
}
bool IsTextureCompressed(Texture2D texture)
{
if (texture.format == TextureFormat.ARGB32
|| texture.format == TextureFormat.ARGB4444
#if !UNITY_3_5 && !UNITY_4_0
|| texture.format == TextureFormat.RGBA4444
#endif
|| texture.format == TextureFormat.Alpha8
|| texture.format == TextureFormat.RGB24
|| texture.format == TextureFormat.RGB565
|| texture.format == TextureFormat.RGBA32)
{
return false;
}
else
{
return true;
}
}
void ConvertTextureToFormat(Texture2D texture, TextureImporterFormat format)
{
string assetPath = AssetDatabase.GetAssetPath(texture);
if (assetPath != "")
{
// make sure the source texture is npot and readable, and uncompressed
TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(assetPath);
if (importer.textureFormat != format)
importer.textureFormat = format;
AssetDatabase.ImportAsset(assetPath);
}
}
bool ParseBMFont(string path, tk2dFontData fontData, tk2dFont source)
{
float scale = 2.0f * source.sizeDef.OrthoSize / source.sizeDef.TargetHeight;
tk2dEditor.Font.Info fontInfo = tk2dEditor.Font.Builder.ParseBMFont(path);
if (fontInfo != null)
return tk2dEditor.Font.Builder.BuildFont(fontInfo, fontData, scale, source.charPadX, source.dupeCaps, source.flipTextureY, source.gradientTexture, source.gradientCount);
else
return false;
}
[MenuItem("Assets/Create/tk2d/Font", false, 11000)]
static void DoBMFontCreate()
{
string path = tk2dEditorUtility.CreateNewPrefab("Font");
if (path.Length != 0)
{
GameObject go = new GameObject();
tk2dFont font = go.AddComponent<tk2dFont>();
font.manageMaterial = true;
font.version = tk2dFont.CURRENT_VERSION;
if (tk2dCamera.Editor__Inst != null) {
font.sizeDef.CopyFrom( tk2dSpriteCollectionSize.ForTk2dCamera( tk2dCamera.Editor__Inst ) );
}
tk2dEditorUtility.SetGameObjectActive(go, false);
Object p = PrefabUtility.CreateEmptyPrefab(path);
PrefabUtility.ReplacePrefab(go, p, ReplacePrefabOptions.ConnectToPrefab);
GameObject.DestroyImmediate(go);
// Select object
Selection.activeObject = AssetDatabase.LoadAssetAtPath(path, typeof(UnityEngine.Object));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
#if !netstandard
using Internal.Runtime.CompilerServices;
#endif
#if !netstandard11
using System.Numerics;
#endif
namespace System
{
internal static partial class SpanHelpers
{
public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
byte valueHead = value;
ref byte valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
index += relativeIndex;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength))
return index; // The tail matched. Return a successful find.
index++;
}
return -1;
}
public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if ((uint)tempIndex < (uint)index)
{
index = tempIndex;
// Reduce space for search, cause we don't care if we find the search value after the index of a previously found value
searchSpaceLength = tempIndex;
if (index == 0) break;
}
}
return index;
}
public static int LastIndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if (tempIndex > index) index = tempIndex;
}
return index;
}
public static unsafe int IndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.Add(ref searchSpace, index + 4))
goto Found4;
if (uValue == Unsafe.Add(ref searchSpace, index + 5))
goto Found5;
if (uValue == Unsafe.Add(ref searchSpace, index + 6))
goto Found6;
if (uValue == Unsafe.Add(ref searchSpace, index + 7))
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
index += 1;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> vComparison = GetVector(value);
while ((byte*)nLength > (byte*)index)
{
var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index)));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
byte valueHead = value;
ref byte valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (; ; )
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, relativeIndex + 1), ref valueTail, valueTailLength))
return relativeIndex; // The tail matched. Return a successful find.
index += remainingSearchSpaceLength - relativeIndex;
}
return -1;
}
public static unsafe int LastIndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)(uint)length; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(((length & (Vector<byte>.Count - 1)) + unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
index -= 8;
if (uValue == Unsafe.Add(ref searchSpace, index + 7))
goto Found7;
if (uValue == Unsafe.Add(ref searchSpace, index + 6))
goto Found6;
if (uValue == Unsafe.Add(ref searchSpace, index + 5))
goto Found5;
if (uValue == Unsafe.Add(ref searchSpace, index + 4))
goto Found4;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
index -= 4;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
index -= 1;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index > 0))
{
nLength = (IntPtr)(uint)((uint)index & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> vComparison = GetVector(value);
while ((byte*)nLength > (byte*)(Vector<byte>.Count - 1))
{
var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector<byte>.Count)));
if (Vector<byte>.Zero.Equals(vMatches))
{
index -= Vector<byte>.Count;
nLength -= Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)(index) - Vector<byte>.Count + LocateLastFoundByte(vMatches);
}
if ((int)(byte*)index > 0)
{
nLength = index;
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
index += 1;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
while ((byte*)nLength > (byte*)index)
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
index += 1;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
Vector<byte> values2 = GetVector(value2);
while ((byte*)nLength > (byte*)index)
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1)),
Vector.Equals(vData, values2));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)(uint)length; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(((length & (Vector<byte>.Count - 1)) + unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
index -= 8;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found7;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
index -= 4;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
index -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index > 0))
{
nLength = (IntPtr)(uint)((uint)index & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
while ((byte*)nLength > (byte*)(Vector<byte>.Count - 1))
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector<byte>.Count));
var vMatches = Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1));
if (Vector<byte>.Zero.Equals(vMatches))
{
index -= Vector<byte>.Count;
nLength -= Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)(index) - Vector<byte>.Count + LocateLastFoundByte(vMatches);
}
if ((int)(byte*)index > 0)
{
nLength = index;
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)(uint)length; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(((length & (Vector<byte>.Count - 1)) + unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
index -= 8;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found7;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
index -= 4;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
index -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index > 0))
{
nLength = (IntPtr)(uint)((uint)index & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
Vector<byte> values2 = GetVector(value2);
while ((byte*)nLength > (byte*)(Vector<byte>.Count - 1))
{
Vector<byte> vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index - Vector<byte>.Count));
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1)),
Vector.Equals(vData, values2));
if (Vector<byte>.Zero.Equals(vMatches))
{
index -= Vector<byte>.Count;
nLength -= Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)(index) - Vector<byte>.Count + LocateLastFoundByte(vMatches);
}
if ((int)(byte*)index > 0)
{
nLength = index;
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe bool SequenceEqual(ref byte first, ref byte second, int length)
{
Debug.Assert(length >= 0);
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr i = (IntPtr)0; // Use IntPtr and byte* for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr n = (IntPtr)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && (byte*)n >= (byte*)Vector<byte>.Count)
{
n -= Vector<byte>.Count;
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += Vector<byte>.Count;
}
return Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, n));
}
#endif
if ((byte*)n >= (byte*)sizeof(UIntPtr))
{
n -= sizeof(UIntPtr);
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += sizeof(UIntPtr);
}
return Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, n));
}
while ((byte*)n > (byte*)i)
{
if (Unsafe.AddByteOffset(ref first, i) != Unsafe.AddByteOffset(ref second, i))
goto NotEqual;
i += 1;
}
Equal:
return true;
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return false;
}
#if !netstandard11
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(Vector<byte> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = 0;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i < Vector<ulong>.Count; i++)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 8 + LocateFirstFoundByte(candidate);
}
#endif
public static unsafe int SequenceCompareTo(ref byte first, int firstLength, ref byte second, int secondLength)
{
Debug.Assert(firstLength >= 0);
Debug.Assert(secondLength >= 0);
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
var minLength = firstLength;
if (minLength > secondLength) minLength = secondLength;
IntPtr i = (IntPtr)0; // Use IntPtr and byte* for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr n = (IntPtr)minLength;
#if !netstandard11
if (Vector.IsHardwareAccelerated && (byte*)n > (byte*)Vector<byte>.Count)
{
n -= Vector<byte>.Count;
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += Vector<byte>.Count;
}
goto NotEqual;
}
#endif
if ((byte*)n > (byte*)sizeof(UIntPtr))
{
n -= sizeof(UIntPtr);
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += sizeof(UIntPtr);
}
}
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
while((byte*)minLength > (byte*)i)
{
int result = Unsafe.AddByteOffset(ref first, i).CompareTo(Unsafe.AddByteOffset(ref second, i));
if (result != 0) return result;
i += 1;
}
Equal:
return firstLength - secondLength;
}
#if !netstandard11
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundByte(Vector<byte> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = Vector<ulong>.Count - 1;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i >= 0; i--)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 8 + LocateLastFoundByte(candidate);
}
#endif
#if !netstandard11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(ulong match)
{
unchecked
{
// Flag least significant power of two bit
var powerOfTwoFlag = match ^ (match - 1);
// Shift all powers of two into the high byte and extract
return (int)((powerOfTwoFlag * XorPowerOfTwoToHighByte) >> 57);
}
}
#endif
#if !netstandard11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateLastFoundByte(ulong match)
{
// Find the most significant byte that has its highest bit set
int index = 7;
while ((long)match > 0)
{
match = match << 8;
index--;
}
return index;
}
#endif
#if !netstandard11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Vector<byte> GetVector(byte vectorByte)
{
#if !netcoreapp
// Vector<byte> .ctor doesn't become an intrinsic due to detection issue
// However this does cause it to become an intrinsic (with additional multiply and reg->reg copy)
// https://github.com/dotnet/coreclr/issues/7459#issuecomment-253965670
return Vector.AsVectorByte(new Vector<uint>(vectorByte * 0x01010101u));
#else
return new Vector<byte>(vectorByte);
#endif
}
#endif
#if !netstandard11
private const ulong XorPowerOfTwoToHighByte = (0x07ul |
0x06ul << 8 |
0x05ul << 16 |
0x04ul << 24 |
0x03ul << 32 |
0x02ul << 40 |
0x01ul << 48) + 1;
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Fact]
public static void IntArrayAsSpan()
{
int[] a = { 91, 92, -93, 94 };
Span<int> spanInt = a.AsSpan();
spanInt.Validate(91, 92, -93, 94);
}
[Fact]
public static void LongArrayAsSpan()
{
long[] b = { 91, -92, 93, 94, -95 };
Span<long> spanLong = b.AsSpan();
spanLong.Validate(91, -92, 93, 94, -95);
}
[Fact]
public static void ObjectArrayAsSpan()
{
object o1 = new object();
object o2 = new object();
object[] c = { o1, o2 };
Span<object> spanObject = c.AsSpan();
spanObject.ValidateReferenceType(o1, o2);
}
[Fact]
public static void NullArrayAsSpan()
{
int[] a = null;
Span<int> span = a.AsSpan();
span.Validate();
Assert.True(span == default);
}
[Fact]
public static void EmptyArrayAsSpan()
{
int[] empty = Array.Empty<int>();
Span<int> span = empty.AsSpan();
span.ValidateNonNullEmpty();
}
[Fact]
public static void IntArraySegmentAsSpan()
{
int[] a = { 91, 92, -93, 94 };
ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 2);
Span<int> spanInt = segmentInt.AsSpan();
spanInt.Validate(92, -93);
}
[Fact]
public static void LongArraySegmentAsSpan()
{
long[] b = { 91, -92, 93, 94, -95 };
ArraySegment<long> segmentLong = new ArraySegment<long>(b, 1, 3);
Span<long> spanLong = segmentLong.AsSpan();
spanLong.Validate(-92, 93, 94);
}
[Fact]
public static void ObjectArraySegmentAsSpan()
{
object o1 = new object();
object o2 = new object();
object o3 = new object();
object o4 = new object();
object[] c = { o1, o2, o3, o4 };
ArraySegment<object> segmentObject = new ArraySegment<object>(c, 1, 2);
Span<object> spanObject = segmentObject.AsSpan();
spanObject.ValidateReferenceType(o2, o3);
}
[Fact]
public static void ZeroLengthArraySegmentAsSpan()
{
int[] empty = Array.Empty<int>();
ArraySegment<int> segmentEmpty = new ArraySegment<int>(empty);
Span<int> spanEmpty = segmentEmpty.AsSpan();
spanEmpty.ValidateNonNullEmpty();
int[] a = { 91, 92, -93, 94 };
ArraySegment<int> segmentInt = new ArraySegment<int>(a, 0, 0);
Span<int> spanInt = segmentInt.AsSpan();
spanInt.ValidateNonNullEmpty();
}
[Fact]
public static void CovariantAsSpanNotSupported()
{
object[] a = new string[10];
Assert.Throws<ArrayTypeMismatchException>(() => a.AsSpan());
Assert.Throws<ArrayTypeMismatchException>(() => a.AsSpan(0, a.Length));
}
[Fact]
public static void GuidArrayAsSpanWithStartAndLength()
{
var arr = new Guid[20];
Span<Guid> slice = arr.AsSpan().Slice(2, 2);
Guid guid = Guid.NewGuid();
slice[1] = guid;
Assert.Equal(guid, arr[3]);
}
[Theory]
[InlineData(0, 0)]
[InlineData(3, 0)]
[InlineData(3, 1)]
[InlineData(3, 2)]
[InlineData(3, 3)]
[InlineData(10, 0)]
[InlineData(10, 3)]
[InlineData(10, 10)]
public static void ArrayAsSpanWithStart(int length, int start)
{
int[] a = new int[length];
Span<int> s = a.AsSpan(start);
Assert.Equal(length - start, s.Length);
if (start != length)
{
s[0] = 42;
Assert.Equal(42, a[start]);
}
}
[Theory]
[InlineData(0, 0)]
[InlineData(3, 0)]
[InlineData(3, 1)]
[InlineData(3, 2)]
[InlineData(3, 3)]
[InlineData(10, 0)]
[InlineData(10, 3)]
[InlineData(10, 10)]
public static void ArraySegmentAsSpanWithStart(int length, int start)
{
const int segmentOffset = 5;
int[] a = new int[length + segmentOffset];
ArraySegment<int> segment = new ArraySegment<int>(a, 5, length);
Span<int> s = segment.AsSpan(start);
Assert.Equal(length - start, s.Length);
if (s.Length != 0)
{
s[0] = 42;
Assert.Equal(42, a[segmentOffset + start]);
}
}
[Theory]
[InlineData(0, 0, 0)]
[InlineData(3, 0, 3)]
[InlineData(3, 1, 2)]
[InlineData(3, 2, 1)]
[InlineData(3, 3, 0)]
[InlineData(10, 0, 5)]
[InlineData(10, 3, 2)]
public static void ArrayAsSpanWithStartAndLength(int length, int start, int subLength)
{
int[] a = new int[length];
Span<int> s = a.AsSpan(start, subLength);
Assert.Equal(subLength, s.Length);
if (subLength != 0)
{
s[0] = 42;
Assert.Equal(42, a[start]);
}
}
[Theory]
[InlineData(0, 0, 0)]
[InlineData(3, 0, 3)]
[InlineData(3, 1, 2)]
[InlineData(3, 2, 1)]
[InlineData(3, 3, 0)]
[InlineData(10, 0, 5)]
[InlineData(10, 3, 2)]
public static void ArraySegmentAsSpanWithStartAndLength(int length, int start, int subLength)
{
const int segmentOffset = 5;
int[] a = new int[length + segmentOffset];
ArraySegment<int> segment = new ArraySegment<int>(a, segmentOffset, length);
Span<int> s = segment.AsSpan(start, subLength);
Assert.Equal(subLength, s.Length);
if (subLength != 0)
{
s[0] = 42;
Assert.Equal(42, a[segmentOffset + start]);
}
}
[Theory]
[InlineData(0, -1)]
[InlineData(0, 1)]
[InlineData(5, 6)]
public static void ArrayAsSpanWithStartNegative(int length, int start)
{
int[] a = new int[length];
Assert.Throws<ArgumentOutOfRangeException>(() => a.AsSpan(start));
}
[Theory]
[InlineData(0, -1, 0)]
[InlineData(0, 1, 0)]
[InlineData(0, 0, -1)]
[InlineData(0, 0, 1)]
[InlineData(5, 6, 0)]
[InlineData(5, 3, 3)]
public static void ArrayAsSpanWithStartAndLengthNegative(int length, int start, int subLength)
{
int[] a = new int[length];
Assert.Throws<ArgumentOutOfRangeException>(() => a.AsSpan(start, subLength));
}
}
}
| |
using System.Collections;
using Alachisoft.NCache.Common.Threading;
using Alachisoft.NCache.Common.Net;
namespace Alachisoft.NGroups.Stack
{
/// <summary> Maintains a pool of sequence numbers of messages that need to be retransmitted. Messages
/// are aged and retransmission requests sent according to age (linear backoff used). If a
/// TimeScheduler instance is given to the constructor, it will be used, otherwise Reransmitter
/// will create its own. The retransmit timeouts have to be set first thing after creating an instance.
/// The <code>add()</code> method adds a range of sequence numbers of messages to be retransmitted. The
/// <code>remove()</code> method removes a sequence number again, cancelling retransmission requests for it.
/// Whenever a message needs to be retransmitted, the <code>RetransmitCommand.retransmit()</code> method is called.
/// It can be used e.g. by an ack-based scheme (e.g. AckSenderWindow) to retransmit a message to the receiver, or
/// by a nak-based scheme to send a retransmission request to the sender of the missing message.
///
/// </summary>
/// <author> John Giorgiadis
/// </author>
/// <author> Bela Ban
/// </author>
/// <version> $Revision: 1.4 $
/// </version>
internal class Retransmitter
{
virtual public long[] RetransmitTimeouts
{
set
{
if (value != null)
RETRANSMIT_TIMEOUTS = value;
}
}
private const long SEC = 1000;
/// <summary>Default retransmit intervals (ms) - exponential approx. </summary>
private static long[] RETRANSMIT_TIMEOUTS = new long[]{2 * SEC, 3 * SEC, 5 * SEC, 8 * SEC};
/// <summary>Default retransmit thread suspend timeout (ms) </summary>
private const long SUSPEND_TIMEOUT = 2000;
private Address sender = null;
private System.Collections.ArrayList msgs = new System.Collections.ArrayList();
private Retransmitter.RetransmitCommand cmd = null;
private bool retransmitter_owned;
private TimeScheduler retransmitter = null;
/// <summary>Retransmit command (see Gamma et al.) used to retrieve missing messages </summary>
internal interface RetransmitCommand
{
/// <summary> Get the missing messages between sequence numbers
/// <code>first_seqno</code> and <code>last_seqno</code>. This can either be done by sending a
/// retransmit message to destination <code>sender</code> (nak-based scheme), or by
/// retransmitting the missing message(s) to <code>sender</code> (ack-based scheme).
/// </summary>
/// <param name="first_seqno">The sequence number of the first missing message
/// </param>
/// <param name="last_seqno"> The sequence number of the last missing message
/// </param>
/// <param name="sender">The destination of the member to which the retransmit request will be sent
/// (nak-based scheme), or to which the message will be retransmitted (ack-based scheme).
/// </param>
void retransmit(long first_seqno, long last_seqno, Address sender);
}
/// <summary> Create a new Retransmitter associated with the given sender address</summary>
/// <param name="sender">the address from which retransmissions are expected or to which retransmissions are sent
/// </param>
/// <param name="cmd">the retransmission callback reference
/// </param>
/// <param name="sched">retransmissions scheduler
/// </param>
public Retransmitter(Address sender, Retransmitter.RetransmitCommand cmd, TimeScheduler sched)
{
init(sender, cmd, sched, false);
}
/// <summary> Create a new Retransmitter associated with the given sender address</summary>
/// <param name="sender">the address from which retransmissions are expected or to which retransmissions are sent
/// </param>
/// <param name="cmd">the retransmission callback reference
/// </param>
public Retransmitter(Address sender, Retransmitter.RetransmitCommand cmd)
{
init(sender, cmd, new TimeScheduler(30 * 1000), true);
}
/// <summary> Add the given range [first_seqno, last_seqno] in the list of
/// entries eligible for retransmission. If first_seqno > last_seqno,
/// then the range [last_seqno, first_seqno] is added instead
/// <p>
/// If retransmitter thread is suspended, wake it up
/// TODO:
/// Does not check for duplicates !
/// </summary>
public virtual void add(long first_seqno, long last_seqno)
{
Entry e;
if (first_seqno > last_seqno)
{
long tmp = first_seqno;
first_seqno = last_seqno;
last_seqno = tmp;
}
lock (msgs.SyncRoot)
{
e = new Entry(this, first_seqno, last_seqno, RETRANSMIT_TIMEOUTS);
msgs.Add(e);
retransmitter.AddTask(e);
}
}
/// <summary> Remove the given sequence number from the list of seqnos eligible
/// for retransmission. If there are no more seqno intervals in the
/// respective entry, cancel the entry from the retransmission
/// scheduler and remove it from the pending entries
/// </summary>
public virtual void remove(long seqno)
{
lock (msgs.SyncRoot)
{
for (int index = 0; index < msgs.Count; index++)
{
Entry e = (Entry) msgs[index];
lock (e)
{
if (seqno < e.low || seqno > e.high)
continue;
e.remove(seqno);
if (e.low > e.high)
{
e.cancel();
msgs.RemoveAt(index);
}
}
break;
}
}
}
/// <summary> Reset the retransmitter: clear all msgs and cancel all the
/// respective tasks
/// </summary>
public virtual void reset()
{
lock (msgs.SyncRoot)
{
for (int index = 0; index < msgs.Count; index++)
{
Entry entry = (Entry) msgs[index];
entry.cancel();
}
msgs.Clear();
}
}
/// <summary> Stop the rentransmition and clear all pending msgs.
/// <p>
/// If this retransmitter has been provided an externally managed
/// scheduler, then just clear all msgs and the associated tasks, else
/// stop the scheduler. In this case the method blocks until the
/// scheduler's thread is dead. Only the owner of the scheduler should
/// stop it.
/// </summary>
public virtual void stop()
{
// i. If retransmitter is owned, stop it else cancel all tasks
// ii. Clear all pending msgs
lock (msgs.SyncRoot)
{
if (retransmitter_owned)
{
try
{
retransmitter.Dispose();
}
catch (System.Threading.ThreadInterruptedException ex)
{
}
}
else
{
for (int index = 0; index < msgs.Count; index++)
{
Entry e = (Entry) msgs[index];
e.cancel();
}
}
msgs.Clear();
}
}
public override string ToString()
{
return (msgs.Count + " messages to retransmit: (" + Global.CollectionToString(msgs) + ')');
}
/* ------------------------------- Private Methods -------------------------------------- */
/// <summary> Init this object
///
/// </summary>
/// <param name="sender">the address from which retransmissions are expected
/// </param>
/// <param name="cmd">the retransmission callback reference
/// </param>
/// <param name="sched">retransmissions scheduler
/// </param>
/// <param name="sched_owned">whether the scheduler parameter is owned by this
/// object or is externally provided
/// </param>
private void init(Address sender, Retransmitter.RetransmitCommand cmd, TimeScheduler sched, bool sched_owned)
{
this.sender = sender;
this.cmd = cmd;
retransmitter_owned = sched_owned;
retransmitter = sched;
}
/* ---------------------------- End of Private Methods ------------------------------------ */
/// <summary> The retransmit task executed by the scheduler in regular intervals</summary>
private abstract class Task : TimeScheduler.Task
{
private Interval intervals;
private bool isCancelled;
protected internal Task(long[] intervals)
{
this.intervals = new Interval(intervals);
this.isCancelled = false;
}
public virtual long GetNextInterval()
{
return (intervals.next());
}
public virtual bool IsCancelled()
{
return (isCancelled);
}
public virtual void cancel()
{
isCancelled = true;
}
public virtual void Run() {}
}
/// <summary> The entry associated with an initial group of missing messages
/// with contiguous sequence numbers and with all its subgroups.<br>
/// E.g.
/// - initial group: [5-34]
/// - msg 12 is acknowledged, now the groups are: [5-11], [13-34]
/// <p>
/// Groups are stored in a list as long[2] arrays of the each group's
/// bounds. For speed and convenience, the lowest & highest bounds of
/// all the groups in this entry are also stored separately
/// </summary>
private class Entry:Task
{
private Retransmitter enclosingInstance;
public System.Collections.ArrayList list;
public long low;
public long high;
public Entry(Retransmitter enclosingInstance, long low, long high, long[] intervals):base(intervals)
{
this.enclosingInstance = enclosingInstance;
this.low = low;
this.high = high;
list = new System.Collections.ArrayList();
list.Add(low);
list.Add(high);
}
/// <summary> Remove the given seqno and resize or partition groups as
/// necessary. The algorithm is as follows:<br>
/// i. Find the group with low <= seqno <= high
/// ii. If seqno == low,
/// a. if low == high, then remove the group
/// Adjust global low. If global low was pointing to the group
/// deleted in the previous step, set it to point to the next group.
/// If there is no next group, set global low to be higher than
/// global high. This way the entry is invalidated and will be removed
/// all together from the pending msgs and the task scheduler
/// iii. If seqno == high, adjust high, adjust global high if this is
/// the group at the tail of the list
/// iv. Else low < seqno < high, break [low,high] into [low,seqno-1]
/// and [seqno+1,high]
///
/// </summary>
/// <param name="seqno">the sequence number to remove
/// </param>
public virtual void remove(long seqno)
{
int i;
long loBound = -1;
long hiBound = -1;
lock (this)
{
for (i = 0; i < list.Count; i+=2)
{
loBound = (long) list[i];
hiBound = (long) list[i+1];
if (seqno < loBound || seqno > hiBound)
continue;
break;
}
if (i == list.Count)
return ;
if (seqno == loBound)
{
if (loBound == hiBound)
{
list.RemoveAt(i);
list.RemoveAt(i);
}
else
list[i] = ++loBound;
if (i == 0)
low = list.Count == 0 ? high + 1:loBound;
}
else if (seqno == hiBound)
{
list[i+1] = --hiBound;
if (i == list.Count - 1)
high = hiBound;
}
else
{
list[i+1] = seqno - 1;
list.Insert(i + 2, hiBound);
list.Insert(i + 2, seqno + 1);
}
}
}
/// <summary> Retransmission task:<br>
/// For each interval, call the retransmission callback command
/// </summary>
public override void Run()
{
ArrayList cloned;
lock (this)
{
cloned = (ArrayList) list.Clone();
}
for (int i = 0; i < cloned.Count; i+=2)
{
long loBound = (long) cloned[i];
long hiBound = (long) cloned[i+1];
enclosingInstance.cmd.retransmit(loBound, hiBound, enclosingInstance.sender);
}
}
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (low == high)
sb.Append(low);
else
sb.Append(low).Append(':').Append(high);
return sb.ToString();
}
} // end class Entry
internal static void sleep(long timeout)
{
Util.Util.sleep(timeout);
}
}
}
| |
// 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.Globalization;
using System.Text;
using Xunit;
namespace Flatbox.RegularExpressions.Tests
{
public class RegexUnicodeCharTests
{
private const int MaxUnicodeRange = 2 << 15;
[Fact]
public static void RegexUnicodeChar()
{
// Regex engine is Unicode aware now for the \w and \d character classes
// \s is not - i.e. it still only recognizes the ASCII space separators, not Unicode ones
// The new character classes for this:
// [\p{L1}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]
List<char> validChars = new List<char>();
List<char> invalidChars = new List<char>();
for (int i = 0; i < MaxUnicodeRange; i++)
{
char c = (char)i;
switch (CharUnicodeInfo.GetUnicodeCategory(c))
{
case UnicodeCategory.UppercaseLetter: //Lu
case UnicodeCategory.LowercaseLetter: //Li
case UnicodeCategory.TitlecaseLetter: // Lt
case UnicodeCategory.ModifierLetter: // Lm
case UnicodeCategory.OtherLetter: // Lo
case UnicodeCategory.DecimalDigitNumber: // Nd
// case UnicodeCategory.LetterNumber: // ??
// case UnicodeCategory.OtherNumber: // ??
case UnicodeCategory.NonSpacingMark:
// case UnicodeCategory.SpacingCombiningMark: // Mc
case UnicodeCategory.ConnectorPunctuation: // Pc
validChars.Add(c);
break;
default:
invalidChars.Add(c);
break;
}
}
// \w - we will create strings from valid characters that form \w and make sure that the regex engine catches this.
// Build a random string with valid characters followed by invalid characters
Random random = new Random(-55);
Regex regex = new Regex(@"\w*");
int validCharLength = 10;
int invalidCharLength = 15;
for (int i = 0; i < 100; i++)
{
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
for (int j = 0; j < validCharLength; j++)
{
char c = validChars[random.Next(validChars.Count)];
builder1.Append(c);
builder2.Append(c);
}
for (int j = 0; j < invalidCharLength; j++)
builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
string input = builder1.ToString();
Match match = regex.Match(input);
Assert.True(match.Success);
Assert.Equal(builder2.ToString(), match.Value);
Assert.Equal(0, match.Index);
Assert.Equal(validCharLength, match.Length);
match = match.NextMatch();
do
{
// We get empty matches for each of the non-matching characters of input to match
// the * wildcard in regex pattern.
Assert.Equal(string.Empty, match.Value);
Assert.Equal(0, match.Length);
match = match.NextMatch();
} while (match.Success);
}
// Build a random string with invalid characters followed by valid characters and then again invalid
random = new Random(-55);
regex = new Regex(@"\w+");
validCharLength = 10;
invalidCharLength = 15;
for (int i = 0; i < 500; i++)
{
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
for (int j = 0; j < invalidCharLength; j++)
builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
for (int j = 0; j < validCharLength; j++)
{
char c = validChars[random.Next(validChars.Count)];
builder1.Append(c);
builder2.Append(c);
}
for (int j = 0; j < invalidCharLength; j++)
builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
string input = builder1.ToString();
Match match = regex.Match(input);
Assert.True(match.Success);
Assert.Equal(builder2.ToString(), match.Value);
Assert.Equal(invalidCharLength, match.Index);
Assert.Equal(validCharLength, match.Length);
match = match.NextMatch();
Assert.False(match.Success);
}
validChars = new List<char>();
invalidChars = new List<char>();
for (int i = 0; i < MaxUnicodeRange; i++)
{
char c = (char)i;
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber)
{
validChars.Add(c);
}
else
{
invalidChars.Add(c);
}
}
// \d - we will create strings from valid characters that form \d and make sure that the regex engine catches this.
// Build a random string with valid characters and then again invalid
regex = new Regex(@"\d+");
validCharLength = 10;
invalidCharLength = 15;
for (int i = 0; i < 100; i++)
{
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
for (int j = 0; j < validCharLength; j++)
{
char c = validChars[random.Next(validChars.Count)];
builder1.Append(c);
builder2.Append(c);
}
for (int j = 0; j < invalidCharLength; j++)
builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
string input = builder1.ToString();
Match match = regex.Match(input);
Assert.Equal(builder2.ToString(), match.Value);
Assert.Equal(0, match.Index);
Assert.Equal(validCharLength, match.Length);
match = match.NextMatch();
Assert.False(match.Success);
}
// Build a random string with invalid characters, valid and then again invalid
regex = new Regex(@"\d+");
validCharLength = 10;
invalidCharLength = 15;
for (int i = 0; i < 100; i++)
{
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
for (int j = 0; j < invalidCharLength; j++)
builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
for (int j = 0; j < validCharLength; j++)
{
char c = validChars[random.Next(validChars.Count)];
builder1.Append(c);
builder2.Append(c);
}
for (int j = 0; j < invalidCharLength; j++)
builder1.Append(invalidChars[random.Next(invalidChars.Count)]);
string input = builder1.ToString();
Match match = regex.Match(input);
Assert.True(match.Success);
Assert.Equal(builder2.ToString(), match.Value);
Assert.Equal(invalidCharLength, match.Index);
Assert.Equal(validCharLength, match.Length);
match = match.NextMatch();
Assert.False(match.Success);
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using SystemState = IronPython.Runtime.SystemState;
using IronPython.Hosting;
using IronPython.Compiler;
using IronPython.Compiler.Ast;
using IronPython.Runtime;
namespace Microsoft.Samples.VisualStudio.IronPythonInference {
public class ScopeNode {
private List<ScopeNode> nested;
public IList<ScopeNode> NestedScopes {
get { return nested; }
}
public virtual string Name {
get { return ""; }
}
public virtual string Doc {
get { return ""; }
}
public virtual Location Start {
get {
return Location.None;
}
}
public virtual Location End {
get {
return Location.None;
}
}
public void Add(ScopeNode node) {
if (nested == null) nested = new List<ScopeNode>();
nested.Add(node);
}
}
public class ClassNode : ScopeNode {
private IronPython.Compiler.Ast.ClassDefinition cls;
public ClassNode(IronPython.Compiler.Ast.ClassDefinition cls) {
this.cls = cls;
}
public override string Name {
get {
if (cls.Name == SymbolTable.Empty) {
return "";
}
return cls.Name.GetString();
}
}
public override string Doc {
get {
return cls.Documentation;
}
}
public override Location Start {
get {
return cls.Start;
}
}
public override Location End {
get {
return cls.End;
}
}
}
public class FunctionNode : ScopeNode {
private IronPython.Compiler.Ast.FunctionDefinition func;
public FunctionNode(IronPython.Compiler.Ast.FunctionDefinition functionDefinition) {
this.func = functionDefinition;
}
public override string Name {
get {
if (func.Name == SymbolTable.Empty) {
return "";
}
return func.Name.GetString();
}
}
public override string Doc {
get {
return func.Documentation;
}
}
public override Location Start {
get {
return func.Start;
}
}
public override Location End {
get {
return func.End;
}
}
}
public class ScopeWalker : AstWalker {
private static SystemState state = new SystemState();
public static ScopeNode GetScopesFromFile(string file) {
CompilerContext context = new CompilerContext(file, new QuietCompilerSink());
Parser parser = Parser.FromFile(state, context);
Statement Statement = parser.ParseFileInput();
ScopeWalker walker = new ScopeWalker();
return walker.WalkScopes(Statement);
}
public static ScopeNode GetScopesFromText(string text) {
CompilerContext context = new CompilerContext("<input>", new QuietCompilerSink());
Parser parser = Parser.FromString(state, context, text);
Statement Statement = parser.ParseFileInput();
ScopeWalker walker = new ScopeWalker();
return walker.WalkScopes(Statement);
}
private ScopeNode root = new ScopeNode();
private Stack<ScopeNode> scopes = new Stack<ScopeNode>();
private ScopeNode WalkScopes(Statement Statement) {
Statement.Walk(this);
return root;
}
private void AddNode(ScopeNode node) {
if (scopes.Count > 0) {
ScopeNode current = scopes.Peek();
current.Add(node);
} else {
root.Add(node);
}
scopes.Push(node);
}
#region IAstWalker Members
public override void PostWalk(IronPython.Compiler.Ast.FunctionDefinition node) {
scopes.Pop();
}
public override void PostWalk(IronPython.Compiler.Ast.ClassDefinition node) {
scopes.Pop();
}
public override bool Walk(IronPython.Compiler.Ast.FunctionDefinition node) {
FunctionNode functionNode = new FunctionNode(node);
AddNode(functionNode);
return true;
}
public override bool Walk(IronPython.Compiler.Ast.ClassDefinition node) {
ClassNode classNode = new ClassNode(node);
AddNode(classNode);
return true;
}
#endregion
}
}
| |
// dnlib: See LICENSE.txt for more info
using System.Collections.Generic;
using System.IO;
using dnlib.IO;
namespace dnlib.DotNet.Emit {
/// <summary>
/// Reads strings from #US heap
/// </summary>
public interface IStringResolver {
/// <summary>
/// Reads a string from the #US heap
/// </summary>
/// <param name="token">String token</param>
/// <returns>A string</returns>
string ReadUserString(uint token);
}
/// <summary>
/// Resolves instruction operands
/// </summary>
public interface IInstructionOperandResolver : ITokenResolver, IStringResolver {
}
public static partial class Extensions {
/// <summary>
/// Resolves a token
/// </summary>
/// <param name="self">An <see cref="IInstructionOperandResolver"/> object</param>
/// <param name="token">The metadata token</param>
/// <returns>A <see cref="IMDTokenProvider"/> or <c>null</c> if <paramref name="token"/> is invalid</returns>
public static IMDTokenProvider ResolveToken(this IInstructionOperandResolver self, uint token) =>
self.ResolveToken(token, new GenericParamContext());
}
/// <summary>
/// Reads a .NET method body (header, locals, instructions, exception handlers)
/// </summary>
public sealed class MethodBodyReader : MethodBodyReaderBase {
readonly IInstructionOperandResolver opResolver;
bool hasReadHeader;
byte headerSize;
ushort flags;
ushort maxStack;
uint codeSize;
uint localVarSigTok;
uint startOfHeader;
uint totalBodySize;
DataReader? exceptionsReader;
readonly GenericParamContext gpContext;
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="reader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="method">Use parameters from this method</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader reader, MethodDef method) =>
CreateCilBody(opResolver, reader, null, method.Parameters, new GenericParamContext());
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="reader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="method">Use parameters from this method</param>
/// <param name="gpContext">Generic parameter context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader reader, MethodDef method, GenericParamContext gpContext) =>
CreateCilBody(opResolver, reader, null, method.Parameters, gpContext);
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="reader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="parameters">Method parameters</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader reader, IList<Parameter> parameters) =>
CreateCilBody(opResolver, reader, null, parameters, new GenericParamContext());
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="reader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader reader, IList<Parameter> parameters, GenericParamContext gpContext) =>
CreateCilBody(opResolver, reader, null, parameters, gpContext);
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="reader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
/// <param name="context">The module context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader reader, IList<Parameter> parameters, GenericParamContext gpContext, ModuleContext context) =>
CreateCilBody(opResolver, reader, null, parameters, gpContext, context);
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="code"/> is not
/// a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="code">All code</param>
/// <param name="exceptions">Exceptions or <c>null</c> if all exception handlers are in
/// <paramref name="code"/></param>
/// <param name="parameters">Method parameters</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, byte[] code, byte[] exceptions, IList<Parameter> parameters) =>
CreateCilBody(opResolver, ByteArrayDataReaderFactory.CreateReader(code), exceptions is null ? (DataReader?)null : ByteArrayDataReaderFactory.CreateReader(exceptions), parameters, new GenericParamContext());
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="code"/> is not
/// a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="code">All code</param>
/// <param name="exceptions">Exceptions or <c>null</c> if all exception handlers are in
/// <paramref name="code"/></param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, byte[] code, byte[] exceptions, IList<Parameter> parameters, GenericParamContext gpContext) =>
CreateCilBody(opResolver, ByteArrayDataReaderFactory.CreateReader(code), exceptions is null ? (DataReader?)null : ByteArrayDataReaderFactory.CreateReader(exceptions), parameters, gpContext);
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="codeReader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="codeReader">A reader positioned at the start of a .NET method body</param>
/// <param name="ehReader">Exception handler reader or <c>null</c> if exceptions aren't
/// present or if <paramref name="codeReader"/> contains the exception handlers</param>
/// <param name="parameters">Method parameters</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader codeReader, DataReader? ehReader, IList<Parameter> parameters) =>
CreateCilBody(opResolver, codeReader, ehReader, parameters, new GenericParamContext());
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="codeReader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="codeReader">A reader positioned at the start of a .NET method body</param>
/// <param name="ehReader">Exception handler reader or <c>null</c> if exceptions aren't
/// present or if <paramref name="codeReader"/> contains the exception handlers</param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader codeReader, DataReader? ehReader, IList<Parameter> parameters, GenericParamContext gpContext) =>
CreateCilBody(opResolver, codeReader, ehReader, parameters, gpContext, null);
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="codeReader"/> doesn't
/// point to the start of a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="codeReader">A reader positioned at the start of a .NET method body</param>
/// <param name="ehReader">Exception handler reader or <c>null</c> if exceptions aren't
/// present or if <paramref name="codeReader"/> contains the exception handlers</param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
/// <param name="context">The module context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, DataReader codeReader, DataReader? ehReader, IList<Parameter> parameters, GenericParamContext gpContext, ModuleContext context) {
var mbReader = new MethodBodyReader(opResolver, codeReader, ehReader, parameters, gpContext, context);
if (!mbReader.Read())
return new CilBody();
return mbReader.CreateCilBody();
}
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="code"/> is not
/// a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="code">All code</param>
/// <param name="exceptions">Exceptions or <c>null</c> if all exception handlers are in
/// <paramref name="code"/></param>
/// <param name="parameters">Method parameters</param>
/// <param name="flags">Method header flags, eg. 2 if tiny method</param>
/// <param name="maxStack">Max stack</param>
/// <param name="codeSize">Code size</param>
/// <param name="localVarSigTok">Local variable signature token or 0 if none</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, byte[] code, byte[] exceptions, IList<Parameter> parameters, ushort flags, ushort maxStack, uint codeSize, uint localVarSigTok) =>
CreateCilBody(opResolver, code, exceptions, parameters, flags, maxStack, codeSize, localVarSigTok, new GenericParamContext());
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="code"/> is not
/// a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="code">All code</param>
/// <param name="exceptions">Exceptions or <c>null</c> if all exception handlers are in
/// <paramref name="code"/></param>
/// <param name="parameters">Method parameters</param>
/// <param name="flags">Method header flags, eg. 2 if tiny method</param>
/// <param name="maxStack">Max stack</param>
/// <param name="codeSize">Code size</param>
/// <param name="localVarSigTok">Local variable signature token or 0 if none</param>
/// <param name="gpContext">Generic parameter context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, byte[] code, byte[] exceptions, IList<Parameter> parameters, ushort flags, ushort maxStack, uint codeSize, uint localVarSigTok, GenericParamContext gpContext) =>
CreateCilBody(opResolver, code, exceptions, parameters, flags, maxStack, codeSize, localVarSigTok, gpContext, null);
/// <summary>
/// Creates a CIL method body or returns an empty one if <paramref name="code"/> is not
/// a valid CIL method body.
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="code">All code</param>
/// <param name="exceptions">Exceptions or <c>null</c> if all exception handlers are in
/// <paramref name="code"/></param>
/// <param name="parameters">Method parameters</param>
/// <param name="flags">Method header flags, eg. 2 if tiny method</param>
/// <param name="maxStack">Max stack</param>
/// <param name="codeSize">Code size</param>
/// <param name="localVarSigTok">Local variable signature token or 0 if none</param>
/// <param name="gpContext">Generic parameter context</param>
/// <param name="context">The module context</param>
public static CilBody CreateCilBody(IInstructionOperandResolver opResolver, byte[] code, byte[] exceptions, IList<Parameter> parameters, ushort flags, ushort maxStack, uint codeSize, uint localVarSigTok, GenericParamContext gpContext, ModuleContext context) {
var codeReader = ByteArrayDataReaderFactory.CreateReader(code);
var ehReader = exceptions is null ? (DataReader?)null : ByteArrayDataReaderFactory.CreateReader(exceptions);
var mbReader = new MethodBodyReader(opResolver, codeReader, ehReader, parameters, gpContext, context);
mbReader.SetHeader(flags, maxStack, codeSize, localVarSigTok);
if (!mbReader.Read())
return new CilBody();
return mbReader.CreateCilBody();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="method">Use parameters from this method</param>
public MethodBodyReader(IInstructionOperandResolver opResolver, DataReader reader, MethodDef method)
: this(opResolver, reader, null, method.Parameters, new GenericParamContext()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="method">Use parameters from this method</param>
/// <param name="gpContext">Generic parameter context</param>
public MethodBodyReader(IInstructionOperandResolver opResolver, DataReader reader, MethodDef method, GenericParamContext gpContext)
: this(opResolver, reader, null, method.Parameters, gpContext) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="parameters">Method parameters</param>
public MethodBodyReader(IInstructionOperandResolver opResolver, DataReader reader, IList<Parameter> parameters)
: this(opResolver, reader, null, parameters, new GenericParamContext()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="reader">A reader positioned at the start of a .NET method body</param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
public MethodBodyReader(IInstructionOperandResolver opResolver, DataReader reader, IList<Parameter> parameters, GenericParamContext gpContext)
: this(opResolver, reader, null, parameters, gpContext) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="codeReader">A reader positioned at the start of a .NET method body</param>
/// <param name="ehReader">Exception handler reader or <c>null</c> if exceptions aren't
/// present or if <paramref name="codeReader"/> contains the exception handlers</param>
/// <param name="parameters">Method parameters</param>
public MethodBodyReader(IInstructionOperandResolver opResolver, DataReader codeReader, DataReader? ehReader, IList<Parameter> parameters)
: this(opResolver, codeReader, ehReader, parameters, new GenericParamContext()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="codeReader">A reader positioned at the start of a .NET method body</param>
/// <param name="ehReader">Exception handler reader or <c>null</c> if exceptions aren't
/// present or if <paramref name="codeReader"/> contains the exception handlers</param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
public MethodBodyReader(IInstructionOperandResolver opResolver, DataReader codeReader, DataReader? ehReader, IList<Parameter> parameters, GenericParamContext gpContext)
: this(opResolver, codeReader, ehReader, parameters, gpContext, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="opResolver">The operand resolver</param>
/// <param name="codeReader">A reader positioned at the start of a .NET method body</param>
/// <param name="ehReader">Exception handler reader or <c>null</c> if exceptions aren't
/// present or if <paramref name="codeReader"/> contains the exception handlers</param>
/// <param name="parameters">Method parameters</param>
/// <param name="gpContext">Generic parameter context</param>
/// <param name="context">Module context</param>
public MethodBodyReader(IInstructionOperandResolver opResolver, DataReader codeReader, DataReader? ehReader, IList<Parameter> parameters, GenericParamContext gpContext, ModuleContext context)
: base(codeReader, parameters, context) {
this.opResolver = opResolver;
exceptionsReader = ehReader;
this.gpContext = gpContext;
startOfHeader = uint.MaxValue;
}
/// <summary>
/// Initializes the method header
/// </summary>
/// <param name="flags">Header flags, eg. 2 if it's a tiny method</param>
/// <param name="maxStack">Max stack</param>
/// <param name="codeSize">Code size</param>
/// <param name="localVarSigTok">Local variable signature token</param>
void SetHeader(ushort flags, ushort maxStack, uint codeSize, uint localVarSigTok) {
hasReadHeader = true;
this.flags = flags;
this.maxStack = maxStack;
this.codeSize = codeSize;
this.localVarSigTok = localVarSigTok;
}
/// <summary>
/// Reads the method body header, locals, all instructions, and the exception handlers (if any)
/// </summary>
/// <returns><c>true</c> if it worked, and <c>false</c> if something failed</returns>
public bool Read() {
try {
if (!ReadHeader())
return false;
SetLocals(ReadLocals());
ReadInstructions();
ReadExceptionHandlers(out totalBodySize);
return true;
}
catch (InvalidMethodException) {
return false;
}
catch (IOException) {
return false;
}
}
/// <summary>
/// Reads the method header
/// </summary>
bool ReadHeader() {
if (hasReadHeader)
return true;
hasReadHeader = true;
startOfHeader = reader.Position;
byte b = reader.ReadByte();
switch (b & 7) {
case 2:
case 6:
// Tiny header. [7:2] = code size, max stack is 8, no locals or exception handlers
flags = 2;
maxStack = 8;
codeSize = (uint)(b >> 2);
localVarSigTok = 0;
headerSize = 1;
break;
case 3:
// Fat header. Can have locals and exception handlers
flags = (ushort)((reader.ReadByte() << 8) | b);
headerSize = (byte)(flags >> 12);
maxStack = reader.ReadUInt16();
codeSize = reader.ReadUInt32();
localVarSigTok = reader.ReadUInt32();
// The CLR allows the code to start inside the method header. But if it does,
// the CLR doesn't read any exceptions.
reader.Position = reader.Position - 12 + headerSize * 4U;
if (headerSize < 3)
flags &= 0xFFF7;
headerSize *= 4;
break;
default:
return false;
}
if ((ulong)reader.Position + codeSize > reader.Length)
return false;
return true;
}
/// <summary>
/// Reads the locals
/// </summary>
/// <returns>All locals or <c>null</c> if there are none</returns>
IList<TypeSig> ReadLocals() {
var standAloneSig = opResolver.ResolveToken(localVarSigTok, gpContext) as StandAloneSig;
if (standAloneSig is null)
return null;
var localSig = standAloneSig.LocalSig;
if (localSig is null)
return null;
return localSig.Locals;
}
/// <summary>
/// Reads all instructions
/// </summary>
void ReadInstructions() => ReadInstructionsNumBytes(codeSize);
/// <inheritdoc/>
protected override IField ReadInlineField(Instruction instr) => opResolver.ResolveToken(reader.ReadUInt32(), gpContext) as IField;
/// <inheritdoc/>
protected override IMethod ReadInlineMethod(Instruction instr) => opResolver.ResolveToken(reader.ReadUInt32(), gpContext) as IMethod;
/// <inheritdoc/>
protected override MethodSig ReadInlineSig(Instruction instr) {
var standAloneSig = opResolver.ResolveToken(reader.ReadUInt32(), gpContext) as StandAloneSig;
if (standAloneSig is null)
return null;
var sig = standAloneSig.MethodSig;
if (sig is not null)
sig.OriginalToken = standAloneSig.MDToken.Raw;
return sig;
}
/// <inheritdoc/>
protected override string ReadInlineString(Instruction instr) => opResolver.ReadUserString(reader.ReadUInt32()) ?? string.Empty;
/// <inheritdoc/>
protected override ITokenOperand ReadInlineTok(Instruction instr) => opResolver.ResolveToken(reader.ReadUInt32(), gpContext) as ITokenOperand;
/// <inheritdoc/>
protected override ITypeDefOrRef ReadInlineType(Instruction instr) => opResolver.ResolveToken(reader.ReadUInt32(), gpContext) as ITypeDefOrRef;
/// <summary>
/// Reads all exception handlers
/// </summary>
void ReadExceptionHandlers(out uint totalBodySize) {
if ((flags & 8) == 0) {
totalBodySize = startOfHeader == uint.MaxValue ? 0 : reader.Position - startOfHeader;
return;
}
bool canSaveTotalBodySize;
DataReader ehReader;
if (exceptionsReader is not null) {
canSaveTotalBodySize = false;
ehReader = exceptionsReader.Value;
}
else {
canSaveTotalBodySize = true;
ehReader = reader;
ehReader.Position = (ehReader.Position + 3) & ~3U;
}
// Only read the first one. Any others aren't used.
byte b = ehReader.ReadByte();
if ((b & 0x3F) != 1) {
totalBodySize = startOfHeader == uint.MaxValue ? 0 : reader.Position - startOfHeader;
return; // Not exception handler clauses
}
if ((b & 0x40) != 0)
ReadFatExceptionHandlers(ref ehReader);
else
ReadSmallExceptionHandlers(ref ehReader);
if (canSaveTotalBodySize)
totalBodySize = startOfHeader == uint.MaxValue ? 0 : ehReader.Position - startOfHeader;
else
totalBodySize = 0;
}
void ReadFatExceptionHandlers(ref DataReader ehReader) {
ehReader.Position--;
int num = (int)((ehReader.ReadUInt32() >> 8) / 24);
for (int i = 0; i < num; i++) {
var eh = new ExceptionHandler((ExceptionHandlerType)ehReader.ReadUInt32());
uint offs = ehReader.ReadUInt32();
eh.TryStart = GetInstruction(offs);
eh.TryEnd = GetInstruction(offs + ehReader.ReadUInt32());
offs = ehReader.ReadUInt32();
eh.HandlerStart = GetInstruction(offs);
eh.HandlerEnd = GetInstruction(offs + ehReader.ReadUInt32());
if (eh.IsCatch)
eh.CatchType = opResolver.ResolveToken(ehReader.ReadUInt32(), gpContext) as ITypeDefOrRef;
else if (eh.IsFilter)
eh.FilterStart = GetInstruction(ehReader.ReadUInt32());
else
ehReader.ReadUInt32();
Add(eh);
}
}
void ReadSmallExceptionHandlers(ref DataReader ehReader) {
int num = (int)((uint)ehReader.ReadByte() / 12);
ehReader.Position += 2;
for (int i = 0; i < num; i++) {
var eh = new ExceptionHandler((ExceptionHandlerType)ehReader.ReadUInt16());
uint offs = ehReader.ReadUInt16();
eh.TryStart = GetInstruction(offs);
eh.TryEnd = GetInstruction(offs + ehReader.ReadByte());
offs = ehReader.ReadUInt16();
eh.HandlerStart = GetInstruction(offs);
eh.HandlerEnd = GetInstruction(offs + ehReader.ReadByte());
if (eh.IsCatch)
eh.CatchType = opResolver.ResolveToken(ehReader.ReadUInt32(), gpContext) as ITypeDefOrRef;
else if (eh.IsFilter)
eh.FilterStart = GetInstruction(ehReader.ReadUInt32());
else
ehReader.ReadUInt32();
Add(eh);
}
}
/// <summary>
/// Creates a CIL body. Must be called after <see cref="Read()"/>, and can only be
/// called once.
/// </summary>
/// <returns>A new <see cref="CilBody"/> instance</returns>
public CilBody CreateCilBody() {
// Set init locals if it's a tiny method or if the init locals bit is set (fat header)
bool initLocals = flags == 2 || (flags & 0x10) != 0;
var cilBody = new CilBody(initLocals, instructions, exceptionHandlers, locals);
cilBody.HeaderSize = headerSize;
cilBody.MaxStack = maxStack;
cilBody.LocalVarSigTok = localVarSigTok;
cilBody.MetadataBodySize = totalBodySize;
instructions = null;
exceptionHandlers = null;
locals = null;
return cilBody;
}
}
}
| |
// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: [email protected] (Anash P. Oommen)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.v201505;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201505 {
/// <summary>
/// UnitTests for <see cref="LineItemCreativeAssociationServiceTests"/> class.
/// </summary>
[TestFixture]
public class LineItemCreativeAssociationServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="LineItemCreativeAssociationService"/> class.
/// </summary>
private LineItemCreativeAssociationService licaService;
/// <summary>
/// Advertiser company id for running tests.
/// </summary>
private long advertiserId;
/// <summary>
/// Salesperson user id for running tests.
/// </summary>
private long salespersonId;
/// <summary>
/// Trafficker user id for running tests.
/// </summary>
private long traffickerId;
/// <summary>
/// Order id for running tests.
/// </summary>
private long orderId;
/// <summary>
/// Ad unit id for running tests.
/// </summary>
private string adUnitId;
/// <summary>
/// Creative id 1 for running tests.
/// </summary>
private long creativeId1;
/// <summary>
/// Creative id 2 for running tests.
/// </summary>
private long creativeId2;
/// <summary>
/// Creative id 3 for running tests.
/// </summary>
private long creativeId3;
/// <summary>
/// Creative id 4 for running tests.
/// </summary>
private long creativeId4;
/// <summary>
/// Line item id 1 for running tests.
/// </summary>
private long lineItemId1;
/// <summary>
/// Line item id 2 for running tests.
/// </summary>
private long lineItemId2;
/// <summary>
/// Line item id 3 for running tests.
/// </summary>
private long lineItemId3;
/// <summary>
/// Line item id 4 for running tests.
/// </summary>
private long lineItemId4;
/// <summary>
/// Line item creative association 1 for running tests.
/// </summary>
private LineItemCreativeAssociation lica1;
/// <summary>
/// Line item creative association 2 for running tests.
/// </summary>
private LineItemCreativeAssociation lica2;
/// <summary>
/// Default public constructor.
/// </summary>
public LineItemCreativeAssociationServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
licaService = (LineItemCreativeAssociationService) user.GetService(
DfpService.v201505.LineItemCreativeAssociationService);
advertiserId = utils.CreateCompany(user, CompanyType.ADVERTISER).id;
salespersonId = utils.GetSalesperson(user).id;
traffickerId = utils.GetTrafficker(user).id;
orderId = utils.CreateOrder(user, advertiserId, salespersonId, traffickerId).id;
adUnitId = utils.CreateAdUnit(user).id;
lineItemId1 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId2 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId3 = utils.CreateLineItem(user, orderId, adUnitId).id;
lineItemId4 = utils.CreateLineItem(user, orderId, adUnitId).id;
creativeId1 = utils.CreateCreative(user, advertiserId).id;
creativeId2 = utils.CreateCreative(user, advertiserId).id;
creativeId3 = utils.CreateCreative(user, advertiserId).id;
creativeId4 = utils.CreateCreative(user, advertiserId).id;
lica1 = utils.CreateLica(user, lineItemId3, creativeId3);
lica2 = utils.CreateLica(user, lineItemId4, creativeId4);
}
/// <summary>
/// Test whether we can create a list of line item creative associations.
/// </summary>
[Test]
public void TestCreateLineItemCreativeAssociations() {
LineItemCreativeAssociation localLica1 = new LineItemCreativeAssociation();
localLica1.creativeId = creativeId1;
localLica1.lineItemId = lineItemId1;
LineItemCreativeAssociation localLica2 = new LineItemCreativeAssociation();
localLica2.creativeId = creativeId2;
localLica2.lineItemId = lineItemId2;
LineItemCreativeAssociation[] newLicas = null;
Assert.DoesNotThrow(delegate() {
newLicas = licaService.createLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {localLica1, localLica2});
});
Assert.NotNull(newLicas);
Assert.AreEqual(newLicas.Length, 2);
Assert.NotNull(newLicas[0]);
Assert.AreEqual(newLicas[0].creativeId, localLica1.creativeId);
Assert.AreEqual(newLicas[0].lineItemId, localLica1.lineItemId);
Assert.NotNull(newLicas[1]);
Assert.AreEqual(newLicas[1].creativeId, localLica2.creativeId);
Assert.AreEqual(newLicas[1].lineItemId, localLica2.lineItemId);
}
/// <summary>
/// Test whether we can fetch a list of existing line item creative
/// associations that match given statement.
/// </summary>
[Test]
public void TestGetLineItemCreativeAssociationsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 500", lineItemId3);
LineItemCreativeAssociationPage page = null;
Assert.DoesNotThrow(delegate() {
page = licaService.getLineItemCreativeAssociationsByStatement(statement);
});
Assert.NotNull(page);
Assert.NotNull(page.results);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results[0]);
Assert.AreEqual(page.results[0].creativeId, lica1.creativeId);
Assert.AreEqual(page.results[0].lineItemId, lica1.lineItemId);
}
/// <summary>
/// Test whether we can deactivate a line item create association.
/// </summary>
[Test]
public void TestPerformLineItemCreativeAssociationAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE lineItemId = '{0}' LIMIT 1", lineItemId3);
DeactivateLineItemCreativeAssociations action = new DeactivateLineItemCreativeAssociations();
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = licaService.performLineItemCreativeAssociationAction(action, statement);
});
Assert.NotNull(result);
Assert.AreEqual(result.numChanges, 1);
}
/// <summary>
/// Test whether we can update a list of line item creative associations.
/// </summary>
[Test]
public void TestUpdateLineItemCreativeAssociations() {
lica1.destinationUrl = "http://news.google.com";
lica2.destinationUrl = "http://news.google.com";
LineItemCreativeAssociation[] newLicas = null;
Assert.DoesNotThrow(delegate() {
newLicas = licaService.updateLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {lica1, lica2});
});
Assert.NotNull(newLicas);
Assert.AreEqual(newLicas.Length, 2);
Assert.NotNull(newLicas[0]);
Assert.AreEqual(newLicas[0].creativeId, lica1.creativeId);
Assert.AreEqual(newLicas[0].lineItemId, lica1.lineItemId);
Assert.NotNull(newLicas[1]);
Assert.AreEqual(newLicas[1].creativeId, lica2.creativeId);
Assert.AreEqual(newLicas[1].lineItemId, lica2.lineItemId);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.SpanTests
{
public static partial class ReadOnlySpanTests
{
[Fact]
public static void ZeroLengthLastIndexOfAny_TwoByte()
{
var sp = new ReadOnlySpan<int>(Array.Empty<int>());
int idx = sp.LastIndexOfAny(0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_TwoByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
var span = new ReadOnlySpan<int>(a);
int[] targets = { default, 99 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
int target0 = targets[index];
int target1 = targets[(index + 1) % 2];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_TwoByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
a[i] = i + 1;
}
var span = new ReadOnlySpan<int>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
int target0 = a[targetIndex];
int target1 = 0;
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
int target0 = a[targetIndex];
int target1 = a[targetIndex + 1];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
int target0 = 0;
int target1 = a[targetIndex + 1];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_TwoByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
int target0 = rnd.Next(1, 256);
int target1 = rnd.Next(1, 256);
var span = new ReadOnlySpan<int>(a);
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_TwoByte()
{
for (int length = 3; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
int val = i + 1;
a[i] = val == 200 ? 201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
var span = new ReadOnlySpan<int>(a);
int idx = span.LastIndexOfAny(200, 200);
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_TwoByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 98;
var span = new ReadOnlySpan<int>(a, 1, length - 1);
int index = span.LastIndexOfAny(99, 98);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 99;
var span = new ReadOnlySpan<int>(a, 1, length - 1);
int index = span.LastIndexOfAny(99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOf_ThreeByte()
{
var sp = new ReadOnlySpan<int>(Array.Empty<int>());
int idx = sp.LastIndexOfAny(0, 0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_ThreeByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
var span = new ReadOnlySpan<int>(a);
int[] targets = { default, 99, 98 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 3);
int target0 = targets[index];
int target1 = targets[(index + 1) % 2];
int target2 = targets[(index + 1) % 3];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_ThreeByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
a[i] = i + 1;
}
var span = new ReadOnlySpan<int>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
int target0 = a[targetIndex];
int target1 = 0;
int target2 = 0;
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
int target0 = a[targetIndex];
int target1 = a[targetIndex + 1];
int target2 = a[targetIndex + 2];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
int target0 = 0;
int target1 = 0;
int target2 = a[targetIndex + 2];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_ThreeByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
int target0 = rnd.Next(1, 256);
int target1 = rnd.Next(1, 256);
int target2 = rnd.Next(1, 256);
var span = new ReadOnlySpan<int>(a);
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_ThreeByte()
{
for (int length = 4; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
int val = i + 1;
a[i] = val == 200 ? 201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
var span = new ReadOnlySpan<int>(a);
int idx = span.LastIndexOfAny(200, 200, 200);
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_ThreeByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 98;
var span = new ReadOnlySpan<int>(a, 1, length - 1);
int index = span.LastIndexOfAny(99, 98, 99);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 99;
var span = new ReadOnlySpan<int>(a, 1, length - 1);
int index = span.LastIndexOfAny(99, 99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthLastIndexOfAny_ManyByte()
{
var sp = new ReadOnlySpan<int>(Array.Empty<int>());
var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, 0 });
int idx = sp.LastIndexOfAny(values);
Assert.Equal(-1, idx);
values = new ReadOnlySpan<int>(new int[] { });
idx = sp.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_ManyByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
var span = new ReadOnlySpan<int>(a);
var values = new ReadOnlySpan<int>(new int[] { default, 99, 98, 0 });
for (int i = 0; i < length; i++)
{
int idx = span.LastIndexOfAny(values);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_ManyByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
a[i] = i + 1;
}
var span = new ReadOnlySpan<int>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], 0, 0, 0 });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, a[targetIndex + 3] });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
}
}
[Fact]
public static void TestMatchValuesLargerLastIndexOfAny_ManyByte()
{
var rnd = new Random(42);
for (int length = 2; length < byte.MaxValue; length++)
{
var a = new int[length];
int expectedIndex = length / 2;
for (int i = 0; i < length; i++)
{
if (i == expectedIndex)
{
continue;
}
a[i] = 255;
}
var span = new ReadOnlySpan<int>(a);
var targets = new int[length * 2];
for (int i = 0; i < targets.Length; i++)
{
if (i == length + 1)
{
continue;
}
targets[i] = rnd.Next(1, 255);
}
var values = new ReadOnlySpan<int>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(expectedIndex, idx);
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_ManyByte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length];
var targets = new int[length];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256);
}
var span = new ReadOnlySpan<int>(a);
var values = new ReadOnlySpan<int>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestNoMatchValuesLargerLastIndexOfAny_ManyByte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length];
var targets = new int[length * 2];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256);
}
var span = new ReadOnlySpan<int>(a);
var values = new ReadOnlySpan<int>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_ManyByte()
{
for (int length = 5; length < byte.MaxValue; length++)
{
var a = new int[length];
for (int i = 0; i < length; i++)
{
int val = i + 1;
a[i] = val == 200 ? 201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
a[length - 5] = 200;
var span = new ReadOnlySpan<int>(a);
var values = new ReadOnlySpan<int>(new int[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 });
int idx = span.LastIndexOfAny(values);
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_ManyByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 98;
var span = new ReadOnlySpan<int>(a, 1, length - 1);
var values = new ReadOnlySpan<int>(new int[] { 99, 98, 99, 98, 99, 98 });
int index = span.LastIndexOfAny(values);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new int[length + 2];
a[0] = 99;
a[length + 1] = 99;
var span = new ReadOnlySpan<int>(a, 1, length - 1);
var values = new ReadOnlySpan<int>(new int[] { 99, 99, 99, 99, 99, 99 });
int index = span.LastIndexOfAny(values);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthLastIndexOfAny_String_TwoByte()
{
var sp = new ReadOnlySpan<string>(Array.Empty<string>());
int idx = sp.LastIndexOfAny("0", "0");
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_String_TwoByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
var tempSpan = new Span<string>(a);
tempSpan.Fill("");
ReadOnlySpan<string> span = tempSpan;
string[] targets = { "", "99" };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
string target0 = targets[index];
string target1 = targets[(index + 1) % 2];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_String_TwoByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
a[i] = (i + 1).ToString();
}
var span = new ReadOnlySpan<string>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
string target0 = a[targetIndex];
string target1 = "0";
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
string target0 = a[targetIndex];
string target1 = a[targetIndex + 1];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
string target0 = "0";
string target1 = a[targetIndex + 1];
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_String_TwoByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
string target0 = rnd.Next(1, 256).ToString();
string target1 = rnd.Next(1, 256).ToString();
var span = new ReadOnlySpan<string>(a);
int idx = span.LastIndexOfAny(target0, target1);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_String_TwoByte()
{
for (int length = 3; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
string val = (i + 1).ToString();
a[i] = val == "200" ? "201" : val;
}
a[length - 1] = "200";
a[length - 2] = "200";
a[length - 3] = "200";
var span = new ReadOnlySpan<string>(a);
int idx = span.LastIndexOfAny("200", "200");
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_TwoByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "98";
var span = new ReadOnlySpan<string>(a, 1, length - 1);
int index = span.LastIndexOfAny("99", "98");
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "99";
var span = new ReadOnlySpan<string>(a, 1, length - 1);
int index = span.LastIndexOfAny("99", "99");
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOf_String_ThreeByte()
{
var sp = new ReadOnlySpan<string>(Array.Empty<string>());
int idx = sp.LastIndexOfAny("0", "0", "0");
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_String_ThreeByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
var tempSpan = new Span<string>(a);
tempSpan.Fill("");
ReadOnlySpan<string> span = tempSpan;
string[] targets = { "", "99", "98" };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 3);
string target0 = targets[index];
string target1 = targets[(index + 1) % 2];
string target2 = targets[(index + 1) % 3];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_String_ThreeByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
a[i] = (i + 1).ToString();
}
var span = new ReadOnlySpan<string>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
string target0 = a[targetIndex];
string target1 = "0";
string target2 = "0";
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
string target0 = a[targetIndex];
string target1 = a[targetIndex + 1];
string target2 = a[targetIndex + 2];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
string target0 = "0";
string target1 = "0";
string target2 = a[targetIndex + 2];
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_String_ThreeByte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
string target0 = rnd.Next(1, 256).ToString();
string target1 = rnd.Next(1, 256).ToString();
string target2 = rnd.Next(1, 256).ToString();
var span = new ReadOnlySpan<string>(a);
int idx = span.LastIndexOfAny(target0, target1, target2);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_String_ThreeByte()
{
for (int length = 4; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
string val = (i + 1).ToString();
a[i] = val == "200" ? "201" : val;
}
a[length - 1] = "200";
a[length - 2] = "200";
a[length - 3] = "200";
a[length - 4] = "200";
var span = new ReadOnlySpan<string>(a);
int idx = span.LastIndexOfAny("200", "200", "200");
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_ThreeByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "98";
var span = new ReadOnlySpan<string>(a, 1, length - 1);
int index = span.LastIndexOfAny("99", "98", "99");
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "99";
var span = new ReadOnlySpan<string>(a, 1, length - 1);
int index = span.LastIndexOfAny("99", "99", "99");
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthLastIndexOfAny_String_ManyByte()
{
var sp = new ReadOnlySpan<string>(Array.Empty<string>());
var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", "0" });
int idx = sp.LastIndexOfAny(values);
Assert.Equal(-1, idx);
values = new ReadOnlySpan<string>(new string[] { });
idx = sp.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledLastIndexOfAny_String_ManyByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
var tempSpan = new Span<string>(a);
tempSpan.Fill("");
ReadOnlySpan<string> span = tempSpan;
var values = new ReadOnlySpan<string>(new string[] { "", "99", "98", "0" });
for (int i = 0; i < length; i++)
{
int idx = span.LastIndexOfAny(values);
Assert.Equal(span.Length - 1, idx);
}
}
}
[Fact]
public static void TestMatchLastIndexOfAny_String_ManyByte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
a[i] = (i + 1).ToString();
}
var span = new ReadOnlySpan<string>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], "0", "0", "0" });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", a[targetIndex + 3] });
int idx = span.LastIndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
}
}
[Fact]
public static void TestMatchValuesLargerLastIndexOfAny_String_ManyByte()
{
var rnd = new Random(42);
for (int length = 2; length < byte.MaxValue; length++)
{
var a = new string[length];
int expectedIndex = length / 2;
for (int i = 0; i < length; i++)
{
if (i == expectedIndex)
{
a[i] = "val";
continue;
}
a[i] = "255";
}
var span = new ReadOnlySpan<string>(a);
var targets = new string[length * 2];
for (int i = 0; i < targets.Length; i++)
{
if (i == length + 1)
{
targets[i] = "val";
continue;
}
targets[i] = rnd.Next(1, 255).ToString();
}
var values = new ReadOnlySpan<string>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(expectedIndex, idx);
}
}
[Fact]
public static void TestNoMatchLastIndexOfAny_String_ManyByte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length];
var targets = new string[length];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256).ToString();
}
var span = new ReadOnlySpan<string>(a);
var values = new ReadOnlySpan<string>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestNoMatchValuesLargerLastIndexOfAny_String_ManyByte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length];
var targets = new string[length * 2];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = rnd.Next(1, 256).ToString();
}
var span = new ReadOnlySpan<string>(a);
var values = new ReadOnlySpan<string>(targets);
int idx = span.LastIndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchLastIndexOfAny_String_ManyByte()
{
for (int length = 5; length < byte.MaxValue; length++)
{
var a = new string[length];
for (int i = 0; i < length; i++)
{
string val = (i + 1).ToString();
a[i] = val == "200" ? "201" : val;
}
a[length - 1] = "200";
a[length - 2] = "200";
a[length - 3] = "200";
a[length - 4] = "200";
a[length - 5] = "200";
var span = new ReadOnlySpan<string>(a);
var values = new ReadOnlySpan<string>(new string[] { "200", "200", "200", "200", "200", "200", "200", "200", "200" });
int idx = span.LastIndexOfAny(values);
Assert.Equal(length - 1, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_ManyByte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "98";
var span = new ReadOnlySpan<string>(a, 1, length - 1);
var values = new ReadOnlySpan<string>(new string[] { "99", "98", "99", "98", "99", "98" });
int index = span.LastIndexOfAny(values);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
var a = new string[length + 2];
a[0] = "99";
a[length + 1] = "99";
var span = new ReadOnlySpan<string>(a, 1, length - 1);
var values = new ReadOnlySpan<string>(new string[] { "99", "99", "99", "99", "99", "99" });
int index = span.LastIndexOfAny(values);
Assert.Equal(-1, index);
}
}
[Theory]
[MemberData(nameof(TestHelpers.LastIndexOfAnyNullSequenceData), MemberType = typeof(TestHelpers))]
public static void LastIndexOfAnyNullSequence_String(string[] spanInput, string[] searchInput, int expected)
{
ReadOnlySpan<string> theStrings = spanInput;
Assert.Equal(expected, theStrings.LastIndexOfAny(searchInput));
Assert.Equal(expected, theStrings.LastIndexOfAny((ReadOnlySpan<string>)searchInput));
if (searchInput != null)
{
if (searchInput.Length >= 3)
{
Assert.Equal(expected, theStrings.LastIndexOfAny(searchInput[0], searchInput[1], searchInput[2]));
}
if (searchInput.Length >= 2)
{
Assert.Equal(expected, theStrings.LastIndexOfAny(searchInput[0], searchInput[1]));
}
}
}
}
}
| |
using System;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using SharpGL.SceneGraph.Core;
using SharpGL.SceneGraph.Primitives;
using VirtualScene.Entities.Properties;
using VirtualScene.Entities.SceneEntities.Builders;
using VirtualScene.Entities.SceneEntities.CalculationStrategies;
using VirtualScene.Entities.SceneEntities.SceneElements;
using Math = VirtualScene.Common.Helpers.Math;
namespace VirtualScene.Entities.SceneEntities
{
/// <summary>
/// The <see cref="ISceneEntity" /> with <see cref="SpurGear" /> geometry.
/// </summary>
[Serializable]
[KnownType(typeof(SpurGearCalculationStrategyBase))]
[KnownType(typeof(SpurGearCalculationStrategyByNumberOfTeethAndOutsideDiameter))]
[KnownType(typeof(SpurGearCalculationStrategyByNumberOfTeethAndPitchDiameter))]
public class SpurGearEntity : SceneEntity<SpurGear>
{
private SpurGearCalculationStrategyBase _calculationStrategy;
private float _faceWidth;
private float _outsideDiameter;
private int _numberOfTeeth;
private float _pitchDiameter;
private float _shaftDiameter;
private bool _showAxiliaryGeometry;
private float _pressureAngle;
private readonly SpurGearBuilder _spurGearBuilder;
/// <summary>
/// Initializes a new instance of the <see cref="SpurGearEntity" />
/// </summary>
public SpurGearEntity()
: base(Resources.Title_Spur_gear)
{
CalculationStrategy = new SpurGearCalculationStrategyByNumberOfTeethAndOutsideDiameter();
_spurGearBuilder = new SpurGearBuilder(2f);
}
/// <summary>
/// The face width of the cylinder.
/// </summary>
[XmlIgnore]
public float FaceWidth
{
get { return _faceWidth; }
set
{
if (Math.AssignValue(ref _faceWidth, value, SceneElement, v => SceneElement.FaceWidth = v, 0))
Rebuild();
}
}
/// <summary>
/// The pressure angle of teeth.
/// </summary>
[XmlIgnore]
public float PressureAngle
{
get { return _pressureAngle; }
set
{
if (Math.AssignValue(ref _pressureAngle, value, SceneElement, v => SceneElement.PressureAngle = v, 0))
Rebuild();
}
}
/// <summary>
/// The diameter of the shaft.
/// </summary>
[XmlIgnore]
public float ShaftDiameter
{
get { return _shaftDiameter; }
set
{
if (Math.AssignValue(ref _shaftDiameter, value, SceneElement, v => SceneElement.ShaftDiameter = v, 0))
Rebuild();
}
}
/// <summary>
/// The number of teeth.
/// </summary>
[XmlIgnore]
public int NumberOfTeeth
{
get { return _numberOfTeeth; }
set
{
if (SceneElement == null ||
!Math.AssignValue(ref _numberOfTeeth, value, () => ValidateNumberOfTeeth(value)))
return;
SceneElement.NumberOfTeeth = _numberOfTeeth;
RecalculateGear();
}
}
private bool ValidateNumberOfTeeth(int value)
{
return !CalculationStrategy.NumberOfTeethReadOnly && value > 1;
}
/// <summary>
/// The outside diameter.
/// </summary>
[XmlIgnore]
public float OutsideDiameter
{
get { return _outsideDiameter; }
set
{
if (SceneElement == null || !Math.AssignValue(ref _outsideDiameter, value, () => ValidateOutsideDiameter(value)))
return;
SceneElement.OutsideDiameter = _outsideDiameter;
RecalculateGear();
}
}
private bool ValidateOutsideDiameter(float value)
{
return !CalculationStrategy.OutsideDiameterReadOnly && value > 0;
}
/// <summary>
/// The pitch diameter.
/// </summary>
[XmlIgnore]
public float PitchDiameter
{
get { return _pitchDiameter; }
set
{
if (SceneElement == null || !Math.AssignValue(ref _pitchDiameter, value, () => ValidatePitchDiameter(value)))
return;
SceneElement.PitchDiameter = _pitchDiameter;
RecalculateGear();
}
}
private bool ValidatePitchDiameter(float value)
{
return !CalculationStrategy.PitchDiameterReadOnly && value > 0;
}
/// <summary>
/// The strategy to calculate parameters of the spur gear.
/// <exception cref="CalculationStrategyNullException">When null is assigned.</exception>
/// </summary>
public SpurGearCalculationStrategyBase CalculationStrategy
{
get { return _calculationStrategy; }
set
{
if(_calculationStrategy == value)
return;
if (value == null)
throw new CalculationStrategyNullException();
_calculationStrategy = value;
RecalculateGear();
}
}
/// <summary>
/// Show the axiliary geometry.
/// </summary>
[XmlIgnore]
public bool ShowAxiliaryGeometry
{
get { return _showAxiliaryGeometry; }
set
{
if(_showAxiliaryGeometry == value)
return;
_showAxiliaryGeometry = value;
Rebuild();
}
}
/// <summary>
/// Show the advanced details.
/// </summary>
[XmlIgnore]
public bool ShowAdvancedDetails { get; set; }
private void RecalculateGear()
{
if(SceneElement == null)
return;
CalculationStrategy.Calculate(this);
Rebuild();
}
/// <summary>
/// Update private data after new geometry was assigned.
/// </summary>
/// <param name="sceneElement">The concrete geometry of type <see cref="SpurGear" />.</param>
protected override void UpdateFields(SpurGear sceneElement)
{
_numberOfTeeth = sceneElement == null? 0: sceneElement.NumberOfTeeth;
_outsideDiameter = sceneElement == null? 0: sceneElement.OutsideDiameter;
_pitchDiameter = sceneElement == null ? 0 : sceneElement.PitchDiameter;
_faceWidth = sceneElement == null? 0: sceneElement.FaceWidth;
_shaftDiameter = sceneElement == null ? 0 : sceneElement.ShaftDiameter;
_pressureAngle = sceneElement == null ? 0 : sceneElement.PressureAngle;
_spurGearBuilder.SpurGear = sceneElement;
RecalculateGear();
}
/// <summary>
/// Build the spur gear shaped <see cref="Polygon" />.
/// </summary>
/// <returns>Returns the spur gear shaped <see cref="Polygon" /> as <see cref="SceneElement" />.</returns>
protected override SpurGear CreateGeometry()
{
return CalculationStrategy.CreateSpurGear();
}
/// <summary>
/// Set the pitch diameter private field without notifying property changes.
/// </summary>
/// <param name="pitchDiameter"></param>
public void SetPitchDiameter(float pitchDiameter)
{
_pitchDiameter = pitchDiameter;
}
private void Rebuild()
{
_spurGearBuilder.Build(0f, 0f, ShowAxiliaryGeometry);
// ReSharper disable once ExplicitCallerInfoArgument
OnPropertyChanged(string.Empty);//notify "all properties changed"
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace SSCompService.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: 515691 $
* $Date: 2007-03-07 19:39:07 +0100 (mer., 07 mars 2007) $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* 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.Data;
using IBatisNet.Common;
using IBatisNet.Common.Logging;
using IBatisNet.DataMapper.Exceptions;
namespace IBatisNet.DataMapper
{
/// <summary>
/// SqlMapSession.
/// </summary>
[Serializable]
public class SqlMapSession : ISqlMapSession
{
#region Fields
private static readonly ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private ISqlMapper _sqlMapper = null;
private IDataSource _dataSource = null;
#endregion
#region Constructor (s) / Destructor
/// <summary>
///
/// </summary>
/// <param name="sqlMapper"></param>
public SqlMapSession(ISqlMapper sqlMapper)
{
_dataSource = sqlMapper.DataSource;
_sqlMapper = sqlMapper;
}
#endregion
#region IDalSession Members
#region Fields
private bool _isTransactionOpen = false;
/// <summary>
/// Changes the vote to commit (true) or to abort (false) in transsaction
/// </summary>
private bool _consistent = false;
/// <summary>
/// Holds value of connection
/// </summary>
private IDbConnection _connection = null;
/// <summary>
/// Holds value of transaction
/// </summary>
private IDbTransaction _transaction = null;
#endregion
#region Properties
/// <summary>
/// Gets the SQL mapper.
/// </summary>
/// <value>The SQL mapper.</value>
public ISqlMapper SqlMapper
{
get { return _sqlMapper; }
}
/// <summary>
/// The data source use by the session.
/// </summary>
/// <value></value>
public IDataSource DataSource
{
get { return _dataSource; }
}
/// <summary>
/// The Connection use by the session.
/// </summary>
/// <value></value>
public IDbConnection Connection
{
get { return _connection; }
}
/// <summary>
/// The Transaction use by the session.
/// </summary>
/// <value></value>
public IDbTransaction Transaction
{
get { return _transaction; }
}
/// <summary>
/// Indicates if a transaction is open on
/// the session.
/// </summary>
public bool IsTransactionStart
{
get { return _isTransactionOpen; }
}
/// <summary>
/// Changes the vote for transaction to commit (true) or to abort (false).
/// </summary>
private bool Consistent
{
set { _consistent = value; }
}
#endregion
#region Methods
/// <summary>
/// Complete (commit) a transaction
/// </summary>
/// <remarks>
/// Use in 'using' syntax.
/// </remarks>
public void Complete()
{
this.Consistent = true;
}
/// <summary>
/// Open the connection
/// </summary>
public void OpenConnection()
{
this.OpenConnection(_dataSource.ConnectionString);
}
/// <summary>
/// Create the connection
/// </summary>
public void CreateConnection()
{
CreateConnection(_dataSource.ConnectionString);
}
/// <summary>
/// Create the connection
/// </summary>
public void CreateConnection(string connectionString)
{
_connection = _dataSource.DbProvider.CreateConnection();
_connection.ConnectionString = connectionString;
}
/// <summary>
/// Open a connection, on the specified connection string.
/// </summary>
/// <param name="connectionString">The connection string</param>
public void OpenConnection(string connectionString)
{
if (_connection == null)
{
CreateConnection(connectionString);
try
{
_connection.Open();
if (_logger.IsDebugEnabled)
{
_logger.Debug(string.Format("Open Connection \"{0}\" to \"{1}\".", _connection.GetHashCode().ToString(), _dataSource.DbProvider.Description));
}
}
catch (Exception ex)
{
throw new DataMapperException(string.Format("Unable to open connection to \"{0}\".", _dataSource.DbProvider.Description), ex);
}
}
else if (_connection.State != ConnectionState.Open)
{
try
{
_connection.Open();
if (_logger.IsDebugEnabled)
{
_logger.Debug(string.Format("Open Connection \"{0}\" to \"{1}\".", _connection.GetHashCode().ToString(), _dataSource.DbProvider.Description));
}
}
catch (Exception ex)
{
throw new DataMapperException(string.Format("Unable to open connection to \"{0}\".", _dataSource.DbProvider.Description), ex);
}
}
}
/// <summary>
/// Close the connection
/// </summary>
public void CloseConnection()
{
if ((_connection != null) && (_connection.State != ConnectionState.Closed))
{
_connection.Close();
if (_logger.IsDebugEnabled)
{
_logger.Debug(string.Format("Close Connection \"{0}\" to \"{1}\".", _connection.GetHashCode().ToString(), _dataSource.DbProvider.Description));
}
_connection.Dispose();
}
_connection = null;
}
/// <summary>
/// Begins a database transaction.
/// </summary>
public void BeginTransaction()
{
this.BeginTransaction(_dataSource.ConnectionString);
}
/// <summary>
/// Open a connection and begin a transaction on the specified connection string.
/// </summary>
/// <param name="connectionString">The connection string</param>
public void BeginTransaction(string connectionString)
{
if (_connection == null || _connection.State != ConnectionState.Open)
{
this.OpenConnection(connectionString);
}
_transaction = _connection.BeginTransaction();
if (_logger.IsDebugEnabled)
{
_logger.Debug("Begin Transaction.");
}
_isTransactionOpen = true;
}
/// <summary>
/// Begins a database transaction
/// </summary>
/// <param name="openConnection">Open a connection.</param>
public void BeginTransaction(bool openConnection)
{
if (openConnection)
{
this.BeginTransaction();
}
else
{
if (_connection == null || _connection.State != ConnectionState.Open)
{
this.OpenConnection();
}
_transaction = _connection.BeginTransaction();
if (_logger.IsDebugEnabled)
{
_logger.Debug("Begin Transaction.");
}
_isTransactionOpen = true;
}
}
/// <summary>
/// Begins a database transaction with the specified isolation level.
/// </summary>
/// <param name="isolationLevel">
/// The isolation level under which the transaction should run.
/// </param>
public void BeginTransaction(IsolationLevel isolationLevel)
{
this.BeginTransaction(_dataSource.ConnectionString, isolationLevel);
}
/// <summary>
/// Open a connection and begin a transaction on the specified connection string.
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <param name="isolationLevel">The transaction isolation level for this connection.</param>
public void BeginTransaction(string connectionString, IsolationLevel isolationLevel)
{
if (_connection == null || _connection.State != ConnectionState.Open)
{
this.OpenConnection(connectionString);
}
_transaction = _connection.BeginTransaction(isolationLevel);
if (_logger.IsDebugEnabled)
{
_logger.Debug("Begin Transaction.");
}
_isTransactionOpen = true;
}
/// <summary>
/// Begins a transaction on the current connection
/// with the specified IsolationLevel value.
/// </summary>
/// <param name="isolationLevel">The transaction isolation level for this connection.</param>
/// <param name="openConnection">Open a connection.</param>
public void BeginTransaction(bool openConnection, IsolationLevel isolationLevel)
{
this.BeginTransaction(_dataSource.ConnectionString, openConnection, isolationLevel);
}
/// <summary>
/// Begins a transaction on the current connection
/// with the specified IsolationLevel value.
/// </summary>
/// <param name="isolationLevel">The transaction isolation level for this connection.</param>
/// <param name="connectionString">The connection string</param>
/// <param name="openConnection">Open a connection.</param>
public void BeginTransaction(string connectionString, bool openConnection, IsolationLevel isolationLevel)
{
if (openConnection)
{
this.BeginTransaction(connectionString, isolationLevel);
}
else
{
if (_connection == null || _connection.State != ConnectionState.Open)
{
throw new DataMapperException("SqlMapSession could not invoke StartTransaction(). A Connection must be started. Call OpenConnection() first.");
}
_transaction = _connection.BeginTransaction(isolationLevel);
if (_logger.IsDebugEnabled)
{
_logger.Debug("Begin Transaction.");
}
_isTransactionOpen = true;
}
}
/// <summary>
/// Commits the database transaction.
/// </summary>
/// <remarks>
/// Will close the connection.
/// </remarks>
public void CommitTransaction()
{
if (_logger.IsDebugEnabled)
{
_logger.Debug("Commit Transaction.");
}
_transaction.Commit();
_transaction.Dispose();
_transaction = null;
_isTransactionOpen = false;
if (_connection.State != ConnectionState.Closed)
{
this.CloseConnection();
}
}
/// <summary>
/// Commits the database transaction.
/// </summary>
/// <param name="closeConnection">Close the connection</param>
public void CommitTransaction(bool closeConnection)
{
if (closeConnection)
{
this.CommitTransaction();
}
else
{
if (_logger.IsDebugEnabled)
{
_logger.Debug("Commit Transaction.");
}
_transaction.Commit();
_transaction.Dispose();
_transaction = null;
_isTransactionOpen = false;
}
}
/// <summary>
/// Rolls back a transaction from a pending state.
/// </summary>
/// <remarks>
/// Will close the connection.
/// </remarks>
public void RollBackTransaction()
{
if (_logger.IsDebugEnabled)
{
_logger.Debug("RollBack Transaction.");
}
_transaction.Rollback();
_transaction.Dispose();
_transaction = null;
_isTransactionOpen = false;
if (_connection.State != ConnectionState.Closed)
{
this.CloseConnection();
}
}
/// <summary>
/// Rolls back a transaction from a pending state.
/// </summary>
/// <param name="closeConnection">Close the connection</param>
public void RollBackTransaction(bool closeConnection)
{
if (closeConnection)
{
this.RollBackTransaction();
}
else
{
if (_logger.IsDebugEnabled)
{
_logger.Debug("RollBack Transaction.");
}
_transaction.Rollback();
_transaction.Dispose();
_transaction = null;
_isTransactionOpen = false;
}
}
/// <summary>
/// Create a command object
/// </summary>
/// <param name="commandType"></param>
/// <returns></returns>
public IDbCommand CreateCommand(CommandType commandType)
{
IDbCommand command = _dataSource.DbProvider.CreateCommand();
command.CommandType = commandType;
command.Connection = _connection;
// Assign transaction
if (_transaction != null)
{
try
{
command.Transaction = _transaction;
}
catch
{ }
}
// Assign connection timeout
if (_connection != null)
{
try // MySql provider doesn't suppport it !
{
command.CommandTimeout = _connection.ConnectionTimeout;
}
catch (NotSupportedException e)
{
if (_logger.IsInfoEnabled)
{
_logger.Info(e.Message);
}
}
}
// if (_logger.IsDebugEnabled)
// {
// command = IDbCommandProxy.NewInstance(command);
// }
return command;
}
/// <summary>
/// Create an IDataParameter
/// </summary>
/// <returns>An IDataParameter.</returns>
public IDbDataParameter CreateDataParameter()
{
return _dataSource.DbProvider.CreateDataParameter();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IDbDataAdapter CreateDataAdapter()
{
return _dataSource.DbProvider.CreateDataAdapter();
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public IDbDataAdapter CreateDataAdapter(IDbCommand command)
{
IDbDataAdapter dataAdapter = null;
dataAdapter = _dataSource.DbProvider.CreateDataAdapter();
dataAdapter.SelectCommand = command;
return dataAdapter;
}
#endregion
#endregion
#region IDisposable Members
/// <summary>
/// Releasing, or resetting resources.
/// </summary>
public void Dispose()
{
if (_logger.IsDebugEnabled)
{
_logger.Debug("Dispose SqlMapSession");
}
if (_isTransactionOpen == false)
{
if (_connection.State != ConnectionState.Closed)
{
_sqlMapper.CloseConnection();
}
}
else
{
if (_consistent)
{
_sqlMapper.CommitTransaction();
_isTransactionOpen = false;
}
else
{
if (_connection.State != ConnectionState.Closed)
{
_sqlMapper.RollBackTransaction();
_isTransactionOpen = false;
}
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class SymbolLoader
{
private readonly NameManager _nameManager;
public PredefinedMembers PredefinedMembers { get; }
private GlobalSymbolContext GlobalSymbolContext { get; }
public ErrorHandling ErrorContext { get; }
public SymbolTable RuntimeBinderSymbolTable { get; private set; }
public SymbolLoader(
GlobalSymbolContext globalSymbols,
UserStringBuilder userStringBuilder,
ErrorHandling errorContext
)
{
_nameManager = globalSymbols.GetNameManager();
PredefinedMembers = new PredefinedMembers(this);
ErrorContext = errorContext;
GlobalSymbolContext = globalSymbols;
Debug.Assert(GlobalSymbolContext != null);
}
public ErrorHandling GetErrorContext()
{
return ErrorContext;
}
public GlobalSymbolContext GetGlobalSymbolContext()
{
return GlobalSymbolContext;
}
public MethodSymbol LookupInvokeMeth(AggregateSymbol pAggDel)
{
Debug.Assert(pAggDel.AggKind() == AggKindEnum.Delegate);
for (Symbol pSym = LookupAggMember(GetNameManager().GetPredefName(PredefinedName.PN_INVOKE), pAggDel, symbmask_t.MASK_ALL);
pSym != null;
pSym = LookupNextSym(pSym, pAggDel, symbmask_t.MASK_ALL))
{
if (pSym.IsMethodSymbol() && pSym.AsMethodSymbol().isInvoke())
{
return pSym.AsMethodSymbol();
}
}
return null;
}
public NameManager GetNameManager()
{
return _nameManager;
}
public PredefinedTypes getPredefTypes()
{
return GlobalSymbolContext.GetPredefTypes();
}
public TypeManager GetTypeManager()
{
return TypeManager;
}
public TypeManager TypeManager
{
get { return GlobalSymbolContext.TypeManager; }
}
public PredefinedMembers getPredefinedMembers()
{
return PredefinedMembers;
}
public BSYMMGR getBSymmgr()
{
return GlobalSymbolContext.GetGlobalSymbols();
}
public SymFactory GetGlobalSymbolFactory()
{
return GlobalSymbolContext.GetGlobalSymbolFactory();
}
public MiscSymFactory GetGlobalMiscSymFactory()
{
return GlobalSymbolContext.GetGlobalMiscSymFactory();
}
public AggregateType GetReqPredefType(PredefinedType pt)
{
return GetReqPredefType(pt, true);
}
public AggregateType GetReqPredefType(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetReqPredefAgg(pt);
if (agg == null)
{
Debug.Assert(false, "Required predef type missing");
return null;
}
AggregateType ats = agg.getThisType();
return ats;
}
public AggregateSymbol GetOptPredefAgg(PredefinedType pt)
{
return GetOptPredefAgg(pt, true);
}
private AggregateSymbol GetOptPredefAgg(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
return agg;
}
public AggregateType GetOptPredefType(PredefinedType pt)
{
return GetOptPredefType(pt, true);
}
public AggregateType GetOptPredefType(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
if (agg == null)
return null;
AggregateType ats = agg.getThisType();
return ats;
}
public AggregateType GetOptPredefTypeErr(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
if (agg == null)
{
getPredefTypes().ReportMissingPredefTypeError(ErrorContext, pt);
return null;
}
AggregateType ats = agg.getThisType();
return ats;
}
public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask)
{
return getBSymmgr().LookupAggMember(name, agg, mask);
}
public Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask)
{
return BSYMMGR.LookupNextSym(sym, parent, kindmask);
}
public bool isManagedType(CType type)
{
return type.computeManagedType(this);
}
// It would be nice to make this a virtual method on typeSym.
public AggregateType GetAggTypeSym(CType typeSym)
{
Debug.Assert(typeSym != null);
Debug.Assert(typeSym.IsAggregateType() ||
typeSym.IsTypeParameterType() ||
typeSym.IsArrayType() ||
typeSym.IsNullableType());
switch (typeSym.GetTypeKind())
{
case TypeKind.TK_AggregateType:
return typeSym.AsAggregateType();
case TypeKind.TK_ArrayType:
return GetReqPredefType(PredefinedType.PT_ARRAY);
case TypeKind.TK_TypeParameterType:
return typeSym.AsTypeParameterType().GetEffectiveBaseClass();
case TypeKind.TK_NullableType:
return typeSym.AsNullableType().GetAts(ErrorContext);
}
Debug.Assert(false, "Bad typeSym!");
return null;
}
private bool IsBaseInterface(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
if (!pBase.isInterfaceType())
{
return false;
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
while (atsDer != null)
{
TypeArray ifacesAll = atsDer.GetIfacesAll();
for (int i = 0; i < ifacesAll.Size; i++)
{
if (AreTypesEqualForConversion(ifacesAll.Item(i), pBase))
{
return true;
}
}
atsDer = atsDer.GetBaseClass();
}
return false;
}
public bool IsBaseClassOfClass(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
// This checks to see whether derived is a class, and if so,
// if base is a base class of derived.
if (!pDerived.isClassType())
{
return false;
}
return IsBaseClass(pDerived, pBase);
}
private bool IsBaseClass(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
// A base class has got to be a class. The derived type might be a struct.
if (!pBase.isClassType())
{
return false;
}
if (pDerived.IsNullableType())
{
pDerived = pDerived.AsNullableType().GetAts(ErrorContext);
if (pDerived == null)
{
return false;
}
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
AggregateType atsBase = pBase.AsAggregateType();
AggregateType atsCur = atsDer.GetBaseClass();
while (atsCur != null)
{
if (atsCur == atsBase)
{
return true;
}
atsCur = atsCur.GetBaseClass();
}
return false;
}
private bool HasCovariantArrayConversion(ArrayType pSource, ArrayType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// * S and T differ only in element type. In other words, S and T have the same number of dimensions.
// * Both SE and TE are reference types.
// * An implicit reference conversion exists from SE to TE.
return (pSource.rank == pDest.rank) &&
HasImplicitReferenceConversion(pSource.GetElementType(), pDest.GetElementType());
}
public bool HasIdentityOrImplicitReferenceConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (AreTypesEqualForConversion(pSource, pDest))
{
return true;
}
return HasImplicitReferenceConversion(pSource, pDest);
}
private bool AreTypesEqualForConversion(CType pType1, CType pType2)
{
return pType1.Equals(pType2);
}
private bool HasArrayConversionToInterface(ArrayType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource.rank != 1)
{
return false;
}
if (!pDest.isInterfaceType())
{
return false;
}
// * From a single-dimensional array type S[] to IList<T> or IReadOnlyList<T> and their base
// interfaces, provided that there is an implicit identity or reference
// conversion from S to T.
// We only have six interfaces to check. IList<T>, IReadOnlyList<T> and their bases:
// * The base interface of IList<T> is ICollection<T>.
// * The base interface of ICollection<T> is IEnumerable<T>.
// * The base interface of IEnumerable<T> is IEnumerable.
// * The base interface of IReadOnlyList<T> is IReadOnlyCollection<T>.
// * The base interface of IReadOnlyCollection<T> is IEnumerable<T>.
if (pDest.isPredefType(PredefinedType.PT_IENUMERABLE))
{
return true;
}
AggregateType atsDest = pDest.AsAggregateType();
AggregateSymbol aggDest = pDest.getAggregate();
if (!aggDest.isPredefAgg(PredefinedType.PT_G_ILIST) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_ICOLLECTION) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IENUMERABLE) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYCOLLECTION) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYLIST))
{
return false;
}
Debug.Assert(atsDest.GetTypeArgsAll().Size == 1);
CType pSourceElement = pSource.GetElementType();
CType pDestTypeArgument = atsDest.GetTypeArgsAll().Item(0);
return HasIdentityOrImplicitReferenceConversion(pSourceElement, pDestTypeArgument);
}
private bool HasImplicitReferenceConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// The implicit reference conversions are:
// * From any reference type to Object.
if (pSource.IsRefType() && pDest.isPredefType(PredefinedType.PT_OBJECT))
{
return true;
}
// * From any class type S to any class type T provided S is derived from T.
if (pSource.isClassType() && pDest.isClassType() && IsBaseClass(pSource, pDest))
{
return true;
}
// ORIGINAL RULES:
// // * From any class type S to any interface type T provided S implements T.
// if (pSource.isClassType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest))
// {
// return true;
// }
// // * from any interface type S to any interface type T, provided S is derived from T.
// if (pSource.isInterfaceType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest))
// {
// return true;
// }
// VARIANCE EXTENSIONS:
// * From any class type S to any interface type T provided S implements an interface
// convertible to T.
// * From any interface type S to any interface type T provided S implements an interface
// convertible to T.
// * From any interface type S to any interface type T provided S is not T and S is
// an interface convertible to T.
if (pSource.isClassType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
if (pSource.isInterfaceType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
if (pSource.isInterfaceType() && pDest.isInterfaceType() && pSource != pDest &&
HasInterfaceConversion(pSource.AsAggregateType(), pDest.AsAggregateType()))
{
return true;
}
// * From an array type S with an element type SE to an array type T with element type TE
// provided that all of the following are true:
// * S and T differ only in element type. In other words, S and T have the same number of dimensions.
// * Both SE and TE are reference types.
// * An implicit reference conversion exists from SE to TE.
if (pSource.IsArrayType() && pDest.IsArrayType() &&
HasCovariantArrayConversion(pSource.AsArrayType(), pDest.AsArrayType()))
{
return true;
}
// * From any array type to System.Array or any interface implemented by System.Array.
if (pSource.IsArrayType() && (pDest.isPredefType(PredefinedType.PT_ARRAY) ||
IsBaseInterface(GetReqPredefType(PredefinedType.PT_ARRAY, false), pDest)))
{
return true;
}
// * From a single-dimensional array type S[] to IList<T> and its base
// interfaces, provided that there is an implicit identity or reference
// conversion from S to T.
if (pSource.IsArrayType() && HasArrayConversionToInterface(pSource.AsArrayType(), pDest))
{
return true;
}
// * From any delegate type to System.Delegate
//
// SPEC OMISSION:
//
// The spec should actually say
//
// * From any delegate type to System.Delegate
// * From any delegate type to System.MulticastDelegate
// * From any delegate type to any interface implemented by System.MulticastDelegate
if (pSource.isDelegateType() &&
(pDest.isPredefType(PredefinedType.PT_MULTIDEL) ||
pDest.isPredefType(PredefinedType.PT_DELEGATE) ||
IsBaseInterface(GetReqPredefType(PredefinedType.PT_MULTIDEL, false), pDest)))
{
return true;
}
// VARIANCE EXTENSION:
// * From any delegate type S to a delegate type T provided S is not T and
// S is a delegate convertible to T
if (pSource.isDelegateType() && pDest.isDelegateType() &&
HasDelegateConversion(pSource.AsAggregateType(), pDest.AsAggregateType()))
{
return true;
}
// * From the null literal to any reference type
// NOTE: We extend the specification here. The C# 3.0 spec does not describe
// a "null type". Rather, it says that the null literal is typeless, and is
// convertible to any reference or nullable type. However, the C# 2.0 and 3.0
// implementations have a "null type" which some expressions other than the
// null literal may have. (For example, (null??null), which is also an
// extension to the specification.)
if (pSource.IsNullType() && pDest.IsRefType())
{
return true;
}
if (pSource.IsNullType() && pDest.IsNullableType())
{
return true;
}
// * Implicit conversions involving type parameters that are known to be reference types.
if (pSource.IsTypeParameterType() &&
HasImplicitReferenceTypeParameterConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
return false;
}
private bool HasImplicitReferenceTypeParameterConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (!pSource.IsRefType())
{
// Not a reference conversion.
return false;
}
// The following implicit conversions exist for a given type parameter T:
//
// * From T to its effective base class C.
AggregateType pEBC = pSource.GetEffectiveBaseClass();
if (pDest == pEBC)
{
return true;
}
// * From T to any base class of C.
if (IsBaseClass(pEBC, pDest))
{
return true;
}
// * From T to any interface implemented by C.
if (IsBaseInterface(pEBC, pDest))
{
return true;
}
// * From T to any interface type I in T's effective interface set, and
// from T to any base interface of I.
TypeArray pInterfaces = pSource.GetInterfaceBounds();
for (int i = 0; i < pInterfaces.Size; ++i)
{
if (pInterfaces.Item(i) == pDest)
{
return true;
}
}
// * From T to a type parameter U, provided T depends on U.
if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType()))
{
return true;
}
return false;
}
private bool HasAnyBaseInterfaceConversion(CType pDerived, CType pBase)
{
if (!pBase.isInterfaceType())
{
return false;
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
while (atsDer != null)
{
TypeArray ifacesAll = atsDer.GetIfacesAll();
for (int i = 0; i < ifacesAll.size; i++)
{
if (HasInterfaceConversion(ifacesAll.Item(i).AsAggregateType(), pBase.AsAggregateType()))
{
return true;
}
}
atsDer = atsDer.GetBaseClass();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// The rules for variant interface and delegate conversions are the same:
//
// An interface/delegate type S is convertible to an interface/delegate type T
// if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all
// parameters of U:
//
// * if the ith parameter of U is invariant then Si is exactly equal to Ti.
// * if the ith parameter of U is covariant then either Si is exactly equal
// to Ti, or there is an implicit reference conversion from Si to Ti.
// * if the ith parameter of U is contravariant then either Si is exactly
// equal to Ti, or there is an implicit reference conversion from Ti to Si.
private bool HasInterfaceConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null && pSource.isInterfaceType());
Debug.Assert(pDest != null && pDest.isInterfaceType());
return HasVariantConversion(pSource, pDest);
}
//////////////////////////////////////////////////////////////////////////////
private bool HasDelegateConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null && pSource.isDelegateType());
Debug.Assert(pDest != null && pDest.isDelegateType());
return HasVariantConversion(pSource, pDest);
}
//////////////////////////////////////////////////////////////////////////////
private bool HasVariantConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource == pDest)
{
return true;
}
AggregateSymbol pAggSym = pSource.getAggregate();
if (pAggSym != pDest.getAggregate())
{
return false;
}
TypeArray pTypeParams = pAggSym.GetTypeVarsAll();
TypeArray pSourceArgs = pSource.GetTypeArgsAll();
TypeArray pDestArgs = pDest.GetTypeArgsAll();
Debug.Assert(pTypeParams.size == pSourceArgs.size);
Debug.Assert(pTypeParams.size == pDestArgs.size);
for (int iParam = 0; iParam < pTypeParams.size; ++iParam)
{
CType pSourceArg = pSourceArgs.Item(iParam);
CType pDestArg = pDestArgs.Item(iParam);
// If they're identical then this one is automatically good, so skip it.
if (pSourceArg == pDestArg)
{
continue;
}
TypeParameterType pParam = pTypeParams.Item(iParam).AsTypeParameterType();
if (pParam.Invariant)
{
return false;
}
if (pParam.Covariant)
{
if (!HasImplicitReferenceConversion(pSourceArg, pDestArg))
{
return false;
}
}
if (pParam.Contravariant)
{
if (!HasImplicitReferenceConversion(pDestArg, pSourceArg))
{
return false;
}
}
}
return true;
}
private bool HasImplicitBoxingTypeParameterConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource.IsRefType())
{
// Not a boxing conversion; both source and destination are references.
return false;
}
// The following implicit conversions exist for a given type parameter T:
//
// * From T to its effective base class C.
AggregateType pEBC = pSource.GetEffectiveBaseClass();
if (pDest == pEBC)
{
return true;
}
// * From T to any base class of C.
if (IsBaseClass(pEBC, pDest))
{
return true;
}
// * From T to any interface implemented by C.
if (IsBaseInterface(pEBC, pDest))
{
return true;
}
// * From T to any interface type I in T's effective interface set, and
// from T to any base interface of I.
TypeArray pInterfaces = pSource.GetInterfaceBounds();
for (int i = 0; i < pInterfaces.Size; ++i)
{
if (pInterfaces.Item(i) == pDest)
{
return true;
}
}
// * The conversion from T to a type parameter U, provided T depends on U, is not
// classified as a boxing conversion because it is not guaranteed to box.
// (If both T and U are value types then it is an identity conversion.)
return false;
}
private bool HasImplicitTypeParameterBaseConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (HasImplicitReferenceTypeParameterConversion(pSource, pDest))
{
return true;
}
if (HasImplicitBoxingTypeParameterConversion(pSource, pDest))
{
return true;
}
if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType()))
{
return true;
}
return false;
}
public bool HasImplicitBoxingConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// Certain type parameter conversions are classified as boxing conversions.
if (pSource.IsTypeParameterType() &&
HasImplicitBoxingTypeParameterConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
// The rest of the boxing conversions only operate when going from a value type
// to a reference type.
if (!pSource.IsValType() || !pDest.IsRefType())
{
return false;
}
// A boxing conversion exists from a nullable type to a reference type
// if and only if a boxing conversion exists from the underlying type.
if (pSource.IsNullableType())
{
return HasImplicitBoxingConversion(pSource.AsNullableType().GetUnderlyingType(), pDest);
}
// A boxing conversion exists from any non-nullable value type to object,
// to System.ValueType, and to any interface type implemented by the
// non-nullable value type. Furthermore, an enum type can be converted
// to the type System.Enum.
// We set the base class of the structs to System.ValueType, System.Enum, etc,
// so we can just check here.
if (IsBaseClass(pSource, pDest))
{
return true;
}
if (HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
return false;
}
public bool HasBaseConversion(CType pSource, CType pDest)
{
// By a "base conversion" we mean:
//
// * an identity conversion
// * an implicit reference conversion
// * an implicit boxing conversion
// * an implicit type parameter conversion
//
// In other words, these are conversions that can be made to a base
// class, base interface or co/contravariant type without any change in
// representation other than boxing. A conversion from, say, int to double,
// is NOT a "base conversion", because representation is changed. A conversion
// from, say, lambda to expression tree is not a "base conversion" because
// do not have a type.
//
// The existence of a base conversion depends solely upon the source and
// destination types, not the source expression.
//
// This notion is not found in the spec but it is useful in the implementation.
if (pSource.IsAggregateType() && pDest.isPredefType(PredefinedType.PT_OBJECT))
{
// If we are going from any aggregate type (class, struct, interface, enum or delegate)
// to object, we immediately return true. This may seem like a mere optimization --
// after all, if we have an aggregate then we have some kind of implicit conversion
// to object.
//
// However, it is not a mere optimization; this introduces a control flow change
// in error reporting scenarios for unresolved type forwarders. If a type forwarder
// cannot be resolved then the resulting type symbol will be an aggregate, but
// we will not be able to classify it into class, struct, etc.
//
// We know that we will have an error in this case; we do not wish to compound
// that error by giving a spurious "you cannot convert this thing to object"
// error, which, after all, will go away when the type forwarding problem is
// fixed.
return true;
}
if (HasIdentityOrImplicitReferenceConversion(pSource, pDest))
{
return true;
}
if (HasImplicitBoxingConversion(pSource, pDest))
{
return true;
}
if (pSource.IsTypeParameterType() &&
HasImplicitTypeParameterBaseConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
return false;
}
public bool FCanLift()
{
return null != GetOptPredefAgg(PredefinedType.PT_G_OPTIONAL, false);
}
public bool IsBaseAggregate(AggregateSymbol derived, AggregateSymbol @base)
{
Debug.Assert(!derived.IsEnum() && [email protected]());
if (derived == @base)
return true; // identity.
// refactoring error tolerance: structs and delegates can be base classes in error scenarios so
// we cannot filter on whether or not the base is marked as sealed.
if (@base.IsInterface())
{
// Search the direct and indirect interfaces via ifacesAll, going up the base chain...
while (derived != null)
{
for (int i = 0; i < derived.GetIfacesAll().Size; i++)
{
AggregateType iface = derived.GetIfacesAll().Item(i).AsAggregateType();
if (iface.getAggregate() == @base)
return true;
}
derived = derived.GetBaseAgg();
}
return false;
}
// base is a class. Just go up the base class chain to look for it.
while (derived.GetBaseClass() != null)
{
derived = derived.GetBaseClass().getAggregate();
if (derived == @base)
return true;
}
return false;
}
internal void SetSymbolTable(SymbolTable symbolTable)
{
RuntimeBinderSymbolTable = symbolTable;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Elmah
{
#region Imports
using System;
using System.Collections.Specialized;
using System.IO;
using System.Threading;
using System.Web;
using System.Xml;
using XmlReader = System.Xml.XmlReader;
using XmlWriter = System.Xml.XmlWriter;
using Thread = System.Threading.Thread;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
using XmlConvert = System.Xml.XmlConvert;
using WriteState = System.Xml.WriteState;
#endregion
/// <summary>
/// Responsible for primarily encoding the JSON representation of
/// <see cref="Error"/> objects.
/// </summary>
[ Serializable ]
public sealed class ErrorJson
{
/// <summary>
/// Encodes the default JSON representation of an <see cref="Error"/>
/// object to a string.
/// </summary>
/// <remarks>
/// Only properties and collection entires with non-null
/// and non-empty strings are emitted.
/// </remarks>
public static string EncodeString(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
StringWriter writer = new StringWriter();
Encode(error, writer);
return writer.ToString();
}
/// <summary>
/// Encodes the default JSON representation of an <see cref="Error"/>
/// object to a <see cref="TextWriter" />.
/// </summary>
/// <remarks>
/// Only properties and collection entires with non-null
/// and non-empty strings are emitted.
/// </remarks>
public static void Encode(Error error, TextWriter writer)
{
if (error == null)
throw new ArgumentNullException("error");
if (writer == null)
throw new ArgumentNullException("writer");
EncodeEnclosed(error, new JsonTextWriter(writer));
}
private static void EncodeEnclosed(Error error, JsonTextWriter writer)
{
Debug.Assert(error != null);
Debug.Assert(writer != null);
writer.Object();
Encode(error, writer);
writer.Pop();
}
internal static void Encode(Error error, JsonTextWriter writer)
{
Debug.Assert(error != null);
Debug.Assert(writer != null);
Member(writer, "application", error.ApplicationName);
Member(writer, "host", error.HostName);
Member(writer, "type", error.Type);
Member(writer, "message", error.Message);
Member(writer, "source", error.Source);
Member(writer, "detail", error.Detail);
Member(writer, "user", error.User);
Member(writer, "time", error.Time, DateTime.MinValue);
Member(writer, "statusCode", error.StatusCode, 0);
Member(writer, "webHostHtmlMessage", error.WebHostHtmlMessage);
Member(writer, "serverVariables", error.ServerVariables);
Member(writer, "queryString", error.QueryString);
Member(writer, "form", error.Form);
Member(writer, "cookies", error.Cookies);
}
private static void Member(JsonTextWriter writer, string name, int value, int defaultValue)
{
if (value == defaultValue)
return;
writer.Member(name).Number(value);
}
private static void Member(JsonTextWriter writer, string name, DateTime value, DateTime defaultValue)
{
if (value == defaultValue)
return;
writer.Member(name).String(value);
}
private static void Member(JsonTextWriter writer, string name, string value)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(name);
if (value == null || value.Length == 0)
return;
writer.Member(name).String(value);
}
private static void Member(JsonTextWriter writer, string name, NameValueCollection collection)
{
Debug.Assert(writer != null);
Debug.AssertStringNotEmpty(name);
//
// Bail out early if the collection is null or empty.
//
if (collection == null || collection.Count == 0)
return;
//
// Save the depth, which we'll use to lazily emit the collection.
// That is, if we find that there is nothing useful in it, then
// we could simply avoid emitting anything.
//
int depth = writer.Depth;
//
// For each key, we get all associated values and loop through
// twice. The first time round, we count strings that are
// neither null nor empty. If none are found then the key is
// skipped. Otherwise, second time round, we encode
// strings that are neither null nor empty. If only such string
// exists for a key then it is written directly, otherwise
// multiple strings are naturally wrapped in an array.
//
foreach (string key in collection.Keys)
{
string[] values = collection.GetValues(key);
if (values == null || values.Length == 0)
continue;
int count = 0; // Strings neither null nor empty.
for (int i = 0; i < values.Length; i++)
{
string value = values[i];
if (value != null && value.Length > 0)
count++;
}
if (count == 0) // None?
continue; // Skip key
//
// There is at least one value so now we emit the key.
// Before doing that, we check if the collection member
// was ever started. If not, this would be a good time.
//
if (depth == writer.Depth)
{
writer.Member(name);
writer.Object();
}
writer.Member(key);
if (count > 1)
writer.Array(); // Wrap multiples in an array
for (int i = 0; i < values.Length; i++)
{
string value = values[i];
if (value != null && value.Length > 0)
writer.String(value);
}
if (count > 1)
writer.Pop(); // Close multiples array
}
//
// If we are deeper than when we began then the collection was
// started so we terminate it here.
//
if (writer.Depth > depth)
writer.Pop();
}
private ErrorJson()
{
throw new NotSupportedException();
}
}
}
| |
// 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.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace System.Reflection
{
//
// Common logic for computing the effective set of custom attributes on a reflection element of type E where
// E is a MemberInfo, ParameterInfo, Assembly or Module.
//
// This class is only used by the CustomAttributeExtensions class - hence, we bake in the CustomAttributeExtensions behavior of
// filtering out WinRT attributes.
//
internal abstract class CustomAttributeSearcher<E>
where E : class
{
//
// Returns the effective set of custom attributes on a reflection element.
//
public IEnumerable<CustomAttributeData> GetMatchingCustomAttributes(E element, Type optionalAttributeTypeFilter, bool inherit, bool skipTypeValidation = false)
{
// Do all parameter validation here before we enter the iterator function (so that exceptions from validations
// show up immediately rather than on the first MoveNext()).
if (element == null)
throw new ArgumentNullException(nameof(element));
bool typeFilterKnownToBeSealed = false;
if (!skipTypeValidation)
{
if (optionalAttributeTypeFilter == null)
throw new ArgumentNullException("type");
TypeInfo attributeTypeFilterInfo = optionalAttributeTypeFilter.GetTypeInfo();
if (!(optionalAttributeTypeFilter.Equals(CommonRuntimeTypes.Attribute) ||
attributeTypeFilterInfo.IsSubclassOf(CommonRuntimeTypes.Attribute)))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
try
{
typeFilterKnownToBeSealed = attributeTypeFilterInfo.IsSealed;
}
catch (MissingMetadataException)
{
// If we got here, the custom attribute type itself was not opted into metadata. This can and does happen in the real world when an app
// contains a check for custom attributes that never actually appear on any entity within the app.
//
// Since "typeFilterKnownToBeSealed" is only used to enable an optimization, it's always safe to leave it "false".
//
// Because the Project N toolchain removes any custom attribute that refuses to opt into metadata so at this point,
// we could simply return an empty enumeration and "be correct." However, the code paths following this already do that naturally.
// (i.e. the "passFilter" will never return true, thus we will never attempt to query the custom attribute type for its
// own AttributeUsage custom attribute.) If the toolchain behavior changes in the future, it's preferable that
// this shows up as new MissingMetadataExceptions rather than incorrect results from the api so we will not put
// in an explicit return here.
}
}
Func<Type, bool> passesFilter;
if (optionalAttributeTypeFilter == null)
{
passesFilter =
delegate (Type actualType)
{
return true;
};
}
else
{
passesFilter =
delegate (Type actualType)
{
if (optionalAttributeTypeFilter.Equals(actualType))
return true;
if (typeFilterKnownToBeSealed)
return false;
return actualType.GetTypeInfo().IsSubclassOf(optionalAttributeTypeFilter);
};
}
return GetMatchingCustomAttributesIterator(element, passesFilter, inherit);
}
//
// Subclasses should override this to compute the "parent" of the element for the purpose of finding "inherited" custom attributes.
// Return null if no parent.
//
public virtual E GetParent(E e)
{
return null;
}
//
// Main iterator.
//
private IEnumerable<CustomAttributeData> GetMatchingCustomAttributesIterator(E element, Func<Type, bool> rawPassesFilter, bool inherit)
{
Func<Type, bool> passesFilter =
delegate (Type attributeType)
{
// Windows prohibits instantiating WinRT custom attributes. Filter them from the search as the desktop CLR does.
TypeAttributes typeAttributes = attributeType.GetTypeInfo().Attributes;
if (0 != (typeAttributes & TypeAttributes.WindowsRuntime))
return false;
return rawPassesFilter(attributeType);
};
LowLevelList<CustomAttributeData> immediateResults = new LowLevelList<CustomAttributeData>();
foreach (CustomAttributeData cad in GetDeclaredCustomAttributes(element))
{
if (passesFilter(cad.AttributeType))
{
yield return cad;
immediateResults.Add(cad);
}
}
if (inherit)
{
// Because the "inherit" parameter defaults to "true", we probably get here for a lot of elements that
// don't actually have any inheritance chains. Try to avoid doing any unnecessary setup for the inheritance walk
// unless we have to.
element = GetParent(element);
if (element != null)
{
// This dictionary serves two purposes:
// - Let us know which attribute types we've encountered at lower levels so we can block them from appearing twice in the results
// if appropriate.
//
// - Cache the results of retrieving the usage attribute.
//
LowLevelDictionary<Type, AttributeUsageAttribute> encounteredTypes = new LowLevelDictionary<Type, AttributeUsageAttribute>(11);
for (int i = 0; i < immediateResults.Count; i++)
{
Type attributeType = immediateResults[i].AttributeType;
AttributeUsageAttribute usage;
if (!encounteredTypes.TryGetValue(attributeType, out usage))
encounteredTypes.Add(attributeType, null);
}
do
{
foreach (CustomAttributeData cad in GetDeclaredCustomAttributes(element))
{
Type attributeType = cad.AttributeType;
if (!passesFilter(attributeType))
continue;
AttributeUsageAttribute usage;
if (!encounteredTypes.TryGetValue(attributeType, out usage))
{
// Type was not encountered before. Only include it if it is inheritable.
usage = GetAttributeUsage(attributeType);
encounteredTypes.Add(attributeType, usage);
if (usage.Inherited)
yield return cad;
}
else
{
if (usage == null)
usage = GetAttributeUsage(attributeType);
encounteredTypes[attributeType] = usage;
// Type was encountered at a lower level. Only include it if its inheritable AND allowMultiple.
if (usage.Inherited && usage.AllowMultiple)
yield return cad;
}
}
}
while ((element = GetParent(element)) != null);
}
}
}
//
// Internal helper to compute the AttributeUsage. This must be coded specially to avoid an infinite recursion.
//
private AttributeUsageAttribute GetAttributeUsage(Type attributeType)
{
// This is only invoked when the seacher is called with "inherit: true", thus calling the searcher again
// with "inherit: false" will not cause infinite recursion.
//
// Legacy: Why aren't we checking the parent types? Answer: Although AttributeUsageAttribute is itself marked inheritable, desktop Reflection
// treats it as *non*-inheritable for the purpose of deciding whether another attribute class is inheritable.
// This behavior goes all the way back to at least 3.5 (and perhaps earlier). For compat reasons,
// we won't-fixed this in 4.5 and we won't-fix this in Project N.
//
AttributeUsageAttribute usage = attributeType.GetTypeInfo().GetCustomAttribute<AttributeUsageAttribute>(inherit: false);
if (usage == null)
return new AttributeUsageAttribute(AttributeTargets.All) { AllowMultiple = false, Inherited = true };
return usage;
}
//
// Subclasses must implement this to call the element-specific CustomAttributes property.
//
protected abstract IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(E element);
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using Aga.Controls.Tree;
using Gallio.Icarus.Commands;
using Gallio.Icarus.Controllers.Interfaces;
using Gallio.Icarus.Models.ProjectTreeNodes;
using Gallio.Icarus.ProjectProperties;
using Gallio.Icarus.Utilities;
using Gallio.Icarus.WindowManager;
using Gallio.UI.ProgressMonitoring;
namespace Gallio.Icarus.ProjectExplorer
{
internal partial class ProjectExplorerView : UserControl
{
private readonly IReportController reportController;
private readonly ITaskManager taskManager;
private readonly ICommandFactory commandFactory;
private readonly IProjectController projectController;
private readonly IWindowManager windowManager;
public ProjectExplorerView(IProjectController projectController, IReportController reportController,
ITaskManager taskManager, ICommandFactory commandFactory, IWindowManager windowManager)
{
this.projectController = projectController;
this.windowManager = windowManager;
this.taskManager = taskManager;
this.commandFactory = commandFactory;
this.reportController = reportController;
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
projectTree.Model = projectController.Model;
projectTree.ExpandAll();
SetupReportMenus();
base.OnLoad(e);
}
private void SetupReportMenus()
{
// add a menu item for each report type (View report as)
var reportTypes = new List<string>();
reportTypes.AddRange(reportController.ReportTypes);
reportTypes.Sort();
foreach (var reportType in reportTypes)
{
var menuItem = CreateMenuItem(reportType);
viewReportAsMenuItem.DropDownItems.Add(menuItem);
}
}
private ToolStripMenuItem CreateMenuItem(string reportType)
{
var menuItem = new ToolStripMenuItem
{
Text = reportType
};
menuItem.Click += (s, e) =>
{
var reportNode = (ReportNode)projectTree.SelectedNode.Tag;
var command = commandFactory.CreateConvertSavedReportCommand(reportNode.FileName, menuItem.Text);
taskManager.QueueTask(command);
};
return menuItem;
}
private void projectTree_SelectionChanged(object sender, EventArgs e)
{
projectTree.ContextMenuStrip = new ContextMenuStrip();
if (projectTree.SelectedNode == null || !(projectTree.SelectedNode.Tag is ProjectTreeNode))
return;
var node = (ProjectTreeNode)projectTree.SelectedNode.Tag;
if (node.Commands != null)
{
// add commands to context menu
var menuItems = new List<ToolStripMenuItem>();
foreach (var command in node.Commands)
{
menuItems.Add(new UI.Controls.CommandToolStripMenuItem(command, taskManager));
}
projectTree.ContextMenuStrip.Items.AddRange(menuItems.ToArray());
return;
}
// TODO: change these to command menu items
if (node is FilesNode)
projectTree.ContextMenuStrip = filesNodeMenuStrip;
else if (node is FileNode)
projectTree.ContextMenuStrip = fileNodeMenuStrip;
else if (node is ReportNode)
projectTree.ContextMenuStrip = reportNodeMenuStrip;
else
projectTree.ContextMenuStrip = null;
}
private void removeFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (projectTree.SelectedNode == null || !(projectTree.SelectedNode.Tag is FileNode))
return;
var node = (FileNode)projectTree.SelectedNode.Tag;
var command = commandFactory.CreateRemoveFileCommand(node.FileName);
taskManager.QueueTask(command);
}
private void removeAllFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
var command = commandFactory.CreateRemoveAllFilesCommand();
taskManager.QueueTask(command);
}
private void addFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var openFileDialog = Dialogs.CreateAddFilesDialog())
{
if (openFileDialog.ShowDialog(this) != DialogResult.OK)
return;
var command = commandFactory.CreateAddFilesCommand(openFileDialog.FileNames);
taskManager.QueueTask(command);
}
}
private void projectTree_DoubleClick(object sender, EventArgs e)
{
if (projectTree.SelectedNode == null)
return;
var selectedNode = (Node)projectTree.SelectedNode.Tag;
if (selectedNode is PropertiesNode)
{
ShowPropertiesWindow();
}
else if (selectedNode is ReportNode)
{
OpenReport();
}
}
private void OpenReport()
{
if (projectTree.SelectedNode == null || !(projectTree.SelectedNode.Tag is ReportNode))
return;
var reportNode = (ReportNode)projectTree.SelectedNode.Tag;
Process.Start(reportNode.FileName);
}
private void deleteReportToolStripMenuItem_Click(object sender, EventArgs e)
{
if (projectTree.SelectedNode != null && projectTree.SelectedNode.Tag is ReportNode)
DeleteReport((ReportNode)projectTree.SelectedNode.Tag);
}
private void DeleteReport(ReportNode reportNode)
{
var deleteReportCommand = commandFactory.CreateDeleteReportCommand(reportNode.FileName);
taskManager.QueueTask(deleteReportCommand);
}
private void propertiesToolStripButton_Click(object sender, EventArgs e)
{
ShowPropertiesWindow();
}
private void ShowPropertiesWindow()
{
windowManager.Show(Package.WindowId);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Delete && projectTree.SelectedNode != null
&& projectTree.SelectedNode.Tag is ReportNode)
{
var selectedNode = projectTree.SelectedNode;
projectTree.SelectedNode = selectedNode.NextNode;
DeleteReport((ReportNode)selectedNode.Tag);
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
}
| |
// <copyright file="MlkBiCgStab.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// A Multiple-Lanczos Bi-Conjugate Gradient stabilized iterative matrix solver.
/// </summary>
/// <remarks>
/// <para>
/// The Multiple-Lanczos Bi-Conjugate Gradient stabilized (ML(k)-BiCGStab) solver is an 'improvement'
/// of the standard BiCgStab solver.
/// </para>
/// <para>
/// The algorithm was taken from: <br/>
/// ML(k)BiCGSTAB: A BiCGSTAB variant based on multiple Lanczos starting vectors
/// <br/>
/// Man-chung Yeung and Tony F. Chan
/// <br/>
/// SIAM Journal of Scientific Computing
/// <br/>
/// Volume 21, Number 4, pp. 1263 - 1290
/// </para>
/// <para>
/// The example code below provides an indication of the possible use of the
/// solver.
/// </para>
/// </remarks>
public sealed class MlkBiCgStab : IIterativeSolver<Complex>
{
/// <summary>
/// The default number of starting vectors.
/// </summary>
const int DefaultNumberOfStartingVectors = 50;
/// <summary>
/// The collection of starting vectors which are used as the basis for the Krylov sub-space.
/// </summary>
IList<Vector<Complex>> _startingVectors;
/// <summary>
/// The number of starting vectors used by the algorithm
/// </summary>
int _numberOfStartingVectors = DefaultNumberOfStartingVectors;
/// <summary>
/// Gets or sets the number of starting vectors.
/// </summary>
/// <remarks>
/// Must be larger than 1 and smaller than the number of variables in the matrix that
/// for which this solver will be used.
/// </remarks>
public int NumberOfStartingVectors
{
[DebuggerStepThrough]
get { return _numberOfStartingVectors; }
[DebuggerStepThrough]
set
{
if (value <= 1)
{
throw new ArgumentOutOfRangeException("value");
}
_numberOfStartingVectors = value;
}
}
/// <summary>
/// Resets the number of starting vectors to the default value.
/// </summary>
public void ResetNumberOfStartingVectors()
{
_numberOfStartingVectors = DefaultNumberOfStartingVectors;
}
/// <summary>
/// Gets or sets a series of orthonormal vectors which will be used as basis for the
/// Krylov sub-space.
/// </summary>
public IList<Vector<Complex>> StartingVectors
{
[DebuggerStepThrough]
get { return _startingVectors; }
[DebuggerStepThrough]
set
{
if ((value == null) || (value.Count == 0))
{
_startingVectors = null;
}
else
{
_startingVectors = value;
}
}
}
/// <summary>
/// Gets the number of starting vectors to create
/// </summary>
/// <param name="maximumNumberOfStartingVectors">Maximum number</param>
/// <param name="numberOfVariables">Number of variables</param>
/// <returns>Number of starting vectors to create</returns>
static int NumberOfStartingVectorsToCreate(int maximumNumberOfStartingVectors, int numberOfVariables)
{
// Create no more starting vectors than the size of the problem - 1
return Math.Min(maximumNumberOfStartingVectors, (numberOfVariables - 1));
}
/// <summary>
/// Returns an array of starting vectors.
/// </summary>
/// <param name="maximumNumberOfStartingVectors">The maximum number of starting vectors that should be created.</param>
/// <param name="numberOfVariables">The number of variables.</param>
/// <returns>
/// An array with starting vectors. The array will never be larger than the
/// <paramref name="maximumNumberOfStartingVectors"/> but it may be smaller if
/// the <paramref name="numberOfVariables"/> is smaller than
/// the <paramref name="maximumNumberOfStartingVectors"/>.
/// </returns>
static IList<Vector<Complex>> CreateStartingVectors(int maximumNumberOfStartingVectors, int numberOfVariables)
{
// Create no more starting vectors than the size of the problem - 1
// Get random values and then orthogonalize them with
// modified Gramm - Schmidt
var count = NumberOfStartingVectorsToCreate(maximumNumberOfStartingVectors, numberOfVariables);
// Get a random set of samples based on the standard normal distribution with
// mean = 0 and sd = 1
var distribution = new Normal();
var matrix = new DenseMatrix(numberOfVariables, count);
for (var i = 0; i < matrix.ColumnCount; i++)
{
var samples = new Complex[matrix.RowCount];
var samplesRe = distribution.Samples().Take(matrix.RowCount).ToArray();
var samplesIm = distribution.Samples().Take(matrix.RowCount).ToArray();
for (int j = 0; j < matrix.RowCount; j++)
{
samples[j] = new Complex(samplesRe[j], samplesIm[j]);
}
// Set the column
matrix.SetColumn(i, samples);
}
// Compute the orthogonalization.
var gs = matrix.GramSchmidt();
var orthogonalMatrix = gs.Q;
// Now transfer this to vectors
var result = new List<Vector<Complex>>();
for (var i = 0; i < orthogonalMatrix.ColumnCount; i++)
{
result.Add(orthogonalMatrix.Column(i));
// Normalize the result vector
result[i].Multiply(1 / result[i].L2Norm(), result[i]);
}
return result;
}
/// <summary>
/// Create random vecrors array
/// </summary>
/// <param name="arraySize">Number of vectors</param>
/// <param name="vectorSize">Size of each vector</param>
/// <returns>Array of random vectors</returns>
static Vector<Complex>[] CreateVectorArray(int arraySize, int vectorSize)
{
var result = new Vector<Complex>[arraySize];
for (var i = 0; i < result.Length; i++)
{
result[i] = new DenseVector(vectorSize);
}
return result;
}
/// <summary>
/// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax
/// </summary>
/// <param name="matrix">Source <see cref="Matrix"/>A.</param>
/// <param name="residual">Residual <see cref="Vector"/> data.</param>
/// <param name="x">x <see cref="Vector"/> data.</param>
/// <param name="b">b <see cref="Vector"/> data.</param>
static void CalculateTrueResidual(Matrix<Complex> matrix, Vector<Complex> residual, Vector<Complex> x, Vector<Complex> b)
{
// -Ax = residual
matrix.Multiply(x, residual);
residual.Multiply(-1, residual);
// residual + b
residual.Add(b, residual);
}
/// <summary>
/// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
/// solution vector and x is the unknown vector.
/// </summary>
/// <param name="matrix">The coefficient matrix, <c>A</c>.</param>
/// <param name="input">The solution vector, <c>b</c></param>
/// <param name="result">The result vector, <c>x</c></param>
/// <param name="iterator">The iterator to use to control when to stop iterating.</param>
/// <param name="preconditioner">The preconditioner to use for approximations.</param>
public void Solve(Matrix<Complex> matrix, Vector<Complex> input, Vector<Complex> result, Iterator<Complex> iterator, IPreconditioner<Complex> preconditioner)
{
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resource.ArgumentMatrixSquare, "matrix");
}
if (input.Count != matrix.RowCount || result.Count != input.Count)
{
throw Matrix.DimensionsDontMatch<ArgumentException>(matrix, input, result);
}
if (iterator == null)
{
iterator = new Iterator<Complex>();
}
if (preconditioner == null)
{
preconditioner = new UnitPreconditioner<Complex>();
}
preconditioner.Initialize(matrix);
// Choose an initial guess x_0
// Take x_0 = 0
var xtemp = new DenseVector(input.Count);
// Choose k vectors q_1, q_2, ..., q_k
// Build a new set if:
// a) the stored set doesn't exist (i.e. == null)
// b) Is of an incorrect length (i.e. too long)
// c) The vectors are of an incorrect length (i.e. too long or too short)
var useOld = false;
if (_startingVectors != null)
{
// We don't accept collections with zero starting vectors so ...
if (_startingVectors.Count <= NumberOfStartingVectorsToCreate(_numberOfStartingVectors, input.Count))
{
// Only check the first vector for sizing. If that matches we assume the
// other vectors match too. If they don't the process will crash
if (_startingVectors[0].Count == input.Count)
{
useOld = true;
}
}
}
_startingVectors = useOld ? _startingVectors : CreateStartingVectors(_numberOfStartingVectors, input.Count);
// Store the number of starting vectors. Not really necessary but easier to type :)
var k = _startingVectors.Count;
// r_0 = b - Ax_0
// This is basically a SAXPY so it could be made a lot faster
var residuals = new DenseVector(matrix.RowCount);
CalculateTrueResidual(matrix, residuals, xtemp, input);
// Define the temporary values
var c = new Complex[k];
// Define the temporary vectors
var gtemp = new DenseVector(residuals.Count);
var u = new DenseVector(residuals.Count);
var utemp = new DenseVector(residuals.Count);
var temp = new DenseVector(residuals.Count);
var temp1 = new DenseVector(residuals.Count);
var temp2 = new DenseVector(residuals.Count);
var zd = new DenseVector(residuals.Count);
var zg = new DenseVector(residuals.Count);
var zw = new DenseVector(residuals.Count);
var d = CreateVectorArray(_startingVectors.Count, residuals.Count);
// g_0 = r_0
var g = CreateVectorArray(_startingVectors.Count, residuals.Count);
residuals.CopyTo(g[k - 1]);
var w = CreateVectorArray(_startingVectors.Count, residuals.Count);
// FOR (j = 0, 1, 2 ....)
var iterationNumber = 0;
while (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) == IterationStatus.Continue)
{
// SOLVE M g~_((j-1)k+k) = g_((j-1)k+k)
preconditioner.Approximate(g[k - 1], gtemp);
// w_((j-1)k+k) = A g~_((j-1)k+k)
matrix.Multiply(gtemp, w[k - 1]);
// c_((j-1)k+k) = q^T_1 w_((j-1)k+k)
c[k - 1] = _startingVectors[0].ConjugateDotProduct(w[k - 1]);
if (c[k - 1].Real.AlmostEqualNumbersBetween(0, 1) && c[k - 1].Imaginary.AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// alpha_(jk+1) = q^T_1 r_((j-1)k+k) / c_((j-1)k+k)
var alpha = _startingVectors[0].ConjugateDotProduct(residuals)/c[k - 1];
// u_(jk+1) = r_((j-1)k+k) - alpha_(jk+1) w_((j-1)k+k)
w[k - 1].Multiply(-alpha, temp);
residuals.Add(temp, u);
// SOLVE M u~_(jk+1) = u_(jk+1)
preconditioner.Approximate(u, temp1);
temp1.CopyTo(utemp);
// rho_(j+1) = -u^t_(jk+1) A u~_(jk+1) / ||A u~_(jk+1)||^2
matrix.Multiply(temp1, temp);
var rho = temp.ConjugateDotProduct(temp);
// If rho is zero then temp is a zero vector and we're probably
// about to have zero residuals (i.e. an exact solution).
// So set rho to 1.0 because in the next step it will turn to zero.
if (rho.Real.AlmostEqualNumbersBetween(0, 1) && rho.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
rho = 1.0;
}
rho = -u.ConjugateDotProduct(temp)/rho;
// r_(jk+1) = rho_(j+1) A u~_(jk+1) + u_(jk+1)
u.CopyTo(residuals);
// Reuse temp
temp.Multiply(rho, temp);
residuals.Add(temp, temp2);
temp2.CopyTo(residuals);
// x_(jk+1) = x_((j-1)k_k) - rho_(j+1) u~_(jk+1) + alpha_(jk+1) g~_((j-1)k+k)
utemp.Multiply(-rho, temp);
xtemp.Add(temp, temp2);
temp2.CopyTo(xtemp);
gtemp.Multiply(alpha, gtemp);
xtemp.Add(gtemp, temp2);
temp2.CopyTo(xtemp);
// Check convergence and stop if we are converged.
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// Calculate the true residual
CalculateTrueResidual(matrix, residuals, xtemp, input);
// Now recheck the convergence
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// We're all good now.
// Exit from the while loop.
break;
}
}
// FOR (i = 1,2, ...., k)
for (var i = 0; i < k; i++)
{
// z_d = u_(jk+1)
u.CopyTo(zd);
// z_g = r_(jk+i)
residuals.CopyTo(zg);
// z_w = 0
zw.Clear();
// FOR (s = i, ...., k-1) AND j >= 1
Complex beta;
if (iterationNumber >= 1)
{
for (var s = i; s < k - 1; s++)
{
// beta^(jk+i)_((j-1)k+s) = -q^t_(s+1) z_d / c_((j-1)k+s)
beta = -_startingVectors[s + 1].ConjugateDotProduct(zd)/c[s];
// z_d = z_d + beta^(jk+i)_((j-1)k+s) d_((j-1)k+s)
d[s].Multiply(beta, temp);
zd.Add(temp, temp2);
temp2.CopyTo(zd);
// z_g = z_g + beta^(jk+i)_((j-1)k+s) g_((j-1)k+s)
g[s].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
// z_w = z_w + beta^(jk+i)_((j-1)k+s) w_((j-1)k+s)
w[s].Multiply(beta, temp);
zw.Add(temp, temp2);
temp2.CopyTo(zw);
}
}
beta = rho*c[k - 1];
if (beta.Real.AlmostEqualNumbersBetween(0, 1) && beta.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// beta^(jk+i)_((j-1)k+k) = -(q^T_1 (r_(jk+1) + rho_(j+1) z_w)) / (rho_(j+1) c_((j-1)k+k))
zw.Multiply(rho, temp2);
residuals.Add(temp2, temp);
beta = -_startingVectors[0].ConjugateDotProduct(temp)/beta;
// z_g = z_g + beta^(jk+i)_((j-1)k+k) g_((j-1)k+k)
g[k - 1].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
// z_w = rho_(j+1) (z_w + beta^(jk+i)_((j-1)k+k) w_((j-1)k+k))
w[k - 1].Multiply(beta, temp);
zw.Add(temp, temp2);
temp2.CopyTo(zw);
zw.Multiply(rho, zw);
// z_d = r_(jk+i) + z_w
residuals.Add(zw, zd);
// FOR (s = 1, ... i - 1)
for (var s = 0; s < i - 1; s++)
{
// beta^(jk+i)_(jk+s) = -q^T_s+1 z_d / c_(jk+s)
beta = -_startingVectors[s + 1].ConjugateDotProduct(zd)/c[s];
// z_d = z_d + beta^(jk+i)_(jk+s) * d_(jk+s)
d[s].Multiply(beta, temp);
zd.Add(temp, temp2);
temp2.CopyTo(zd);
// z_g = z_g + beta^(jk+i)_(jk+s) * g_(jk+s)
g[s].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
}
// d_(jk+i) = z_d - u_(jk+i)
zd.Subtract(u, d[i]);
// g_(jk+i) = z_g + z_w
zg.Add(zw, g[i]);
// IF (i < k - 1)
if (i < k - 1)
{
// c_(jk+1) = q^T_i+1 d_(jk+i)
c[i] = _startingVectors[i + 1].ConjugateDotProduct(d[i]);
if (c[i].Real.AlmostEqualNumbersBetween(0, 1) && c[i].Imaginary.AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// alpha_(jk+i+1) = q^T_(i+1) u_(jk+i) / c_(jk+i)
alpha = _startingVectors[i + 1].ConjugateDotProduct(u)/c[i];
// u_(jk+i+1) = u_(jk+i) - alpha_(jk+i+1) d_(jk+i)
d[i].Multiply(-alpha, temp);
u.Add(temp, temp2);
temp2.CopyTo(u);
// SOLVE M g~_(jk+i) = g_(jk+i)
preconditioner.Approximate(g[i], gtemp);
// x_(jk+i+1) = x_(jk+i) + rho_(j+1) alpha_(jk+i+1) g~_(jk+i)
gtemp.Multiply(rho*alpha, temp);
xtemp.Add(temp, temp2);
temp2.CopyTo(xtemp);
// w_(jk+i) = A g~_(jk+i)
matrix.Multiply(gtemp, w[i]);
// r_(jk+i+1) = r_(jk+i) - rho_(j+1) alpha_(jk+i+1) w_(jk+i)
w[i].Multiply(-rho*alpha, temp);
residuals.Add(temp, temp2);
temp2.CopyTo(residuals);
// We can check the residuals here if they're close
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// Recalculate the residuals and go round again. This is done to ensure that
// we have the proper residuals.
CalculateTrueResidual(matrix, residuals, xtemp, input);
}
}
} // END ITERATION OVER i
iterationNumber++;
}
// copy the temporary result to the real result vector
xtemp.CopyTo(result);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** Purpose: Unsafe code that uses pointers should use
** SafePointer to fix subtle lifetime problems with the
** underlying resource.
**
===========================================================*/
// Design points:
// *) Avoid handle-recycling problems (including ones triggered via
// resurrection attacks) for all accesses via pointers. This requires tying
// together the lifetime of the unmanaged resource with the code that reads
// from that resource, in a package that uses synchronization to enforce
// the correct semantics during finalization. We're using SafeHandle's
// ref count as a gate on whether the pointer can be dereferenced because that
// controls the lifetime of the resource.
//
// *) Keep the penalties for using this class small, both in terms of space
// and time. Having multiple threads reading from a memory mapped file
// will already require 2 additional interlocked operations. If we add in
// a "current position" concept, that requires additional space in memory and
// synchronization. Since the position in memory is often (but not always)
// something that can be stored on the stack, we can save some memory by
// excluding it from this object. However, avoiding the need for
// synchronization is a more significant win. This design allows multiple
// threads to read and write memory simultaneously without locks (as long as
// you don't write to a region of memory that overlaps with what another
// thread is accessing).
//
// *) Space-wise, we use the following memory, including SafeHandle's fields:
// Object Header MT* handle int bool bool <2 pad bytes> length
// On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes.
// (We can safe 4 bytes on x86 only by shrinking SafeHandle)
//
// *) Wrapping a SafeHandle would have been a nice solution, but without an
// ordering between critical finalizable objects, it would have required
// changes to each SafeHandle subclass to opt in to being usable from a
// SafeBuffer (or some clever exposure of SafeHandle's state fields and a
// way of forcing ReleaseHandle to run even after the SafeHandle has been
// finalized with a ref count > 1). We can use less memory and create fewer
// objects by simply inserting a SafeBuffer into the class hierarchy.
//
// *) In an ideal world, we could get marshaling support for SafeBuffer that
// would allow us to annotate a P/Invoke declaration, saying this parameter
// specifies the length of the buffer, and the units of that length are X.
// P/Invoke would then pass that size parameter to SafeBuffer.
// [DllImport(...)]
// static extern SafeMemoryHandle AllocCharBuffer(int numChars);
// If we could put an attribute on the SafeMemoryHandle saying numChars is
// the element length, and it must be multiplied by 2 to get to the byte
// length, we can simplify the usage model for SafeBuffer.
//
// *) This class could benefit from a constraint saying T is a value type
// containing no GC references.
// Implementation notes:
// *) The Initialize method must be called before you use any instance of
// a SafeBuffer. To avoid race conditions when storing SafeBuffers in statics,
// you either need to take a lock when publishing the SafeBuffer, or you
// need to create a local, initialize the SafeBuffer, then assign to the
// static variable (perhaps using Interlocked.CompareExchange). Of course,
// assignments in a static class constructor are under a lock implicitly.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Runtime.InteropServices
{
public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
// Steal UIntPtr.MaxValue as our uninitialized value.
private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ?
((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue);
private UIntPtr _numBytes;
protected SafeBuffer(bool ownsHandle) : base(ownsHandle)
{
_numBytes = Uninitialized;
}
/// <summary>
/// Specifies the size of the region of memory, in bytes. Must be
/// called before using the SafeBuffer.
/// </summary>
/// <param name="numBytes">Number of valid bytes in memory.</param>
[CLSCompliant(false)]
public void Initialize(ulong numBytes)
{
if (numBytes < 0)
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum);
if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace);
Contract.EndContractBlock();
if (numBytes >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax);
_numBytes = (UIntPtr)numBytes;
}
/// <summary>
/// Specifies the the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
public void Initialize(uint numElements, uint sizeOfEachElement)
{
if (numElements < 0)
throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_NeedNonNegNum);
if (sizeOfEachElement < 0)
throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), SR.ArgumentOutOfRange_NeedNonNegNum);
if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
Contract.EndContractBlock();
if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
_numBytes = checked((UIntPtr)(numElements * sizeOfEachElement));
}
/// <summary>
/// Specifies the the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
public void Initialize<T>(uint numElements) where T : struct
{
Initialize(numElements, Marshal.AlignedSizeOf<T>());
}
// Callers should ensure that they check whether the pointer ref param
// is null when AcquirePointer returns. If it is not null, they must
// call ReleasePointer in a CER. This method calls DangerousAddRef
// & exposes the pointer. Unlike Read, it does not alter the "current
// position" of the pointer. Here's how to use it:
//
// byte* pointer = null;
// RuntimeHelpers.PrepareConstrainedRegions();
// try {
// safeBuffer.AcquirePointer(ref pointer);
// // Use pointer here, with your own bounds checking
// }
// finally {
// if (pointer != null)
// safeBuffer.ReleasePointer();
// }
//
// Note: If you cast this byte* to a T*, you have to worry about
// whether your pointer is aligned. Additionally, you must take
// responsibility for all bounds checking with this pointer.
/// <summary>
/// Obtain the pointer from a SafeBuffer for a block of code,
/// with the express responsibility for bounds checking and calling
/// ReleasePointer later within a CER to ensure the pointer can be
/// freed later. This method either completes successfully or
/// throws an exception and returns with pointer set to null.
/// </summary>
/// <param name="pointer">A byte*, passed by reference, to receive
/// the pointer from within the SafeBuffer. You must set
/// pointer to null before calling this method.</param>
[CLSCompliant(false)]
public void AcquirePointer(ref byte* pointer)
{
if (_numBytes == Uninitialized)
throw NotInitialized();
pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
bool junk = false;
DangerousAddRef(ref junk);
pointer = (byte*)handle;
}
}
public void ReleasePointer()
{
if (_numBytes == Uninitialized)
throw NotInitialized();
DangerousRelease();
}
/// <summary>
/// Read a value type from memory at the given offset. This is
/// equivalent to: return *(T*)(bytePtr + byteOffset);
/// </summary>
/// <typeparam name="T">The value type to read</typeparam>
/// <param name="byteOffset">Where to start reading from memory. You
/// may have to consider alignment.</param>
/// <returns>An instance of T read from memory.</returns>
[CLSCompliant(false)]
public T Read<T>(ulong byteOffset) where T : struct
{
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);
// return *(T*) (_ptr + byteOffset);
T value;
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
GenericPtrToStructure<T>(ptr, out value, sizeofT);
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
return value;
}
[CLSCompliant(false)]
public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
if (array == null)
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
uint alignedSizeofT = Marshal.AlignedSizeOf<T>();
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
for (int i = 0; i < count; i++)
unsafe { GenericPtrToStructure<T>(ptr + alignedSizeofT * i, out array[i + index], sizeofT); }
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
/// <summary>
/// Write a value type to memory at the given offset. This is
/// equivalent to: *(T*)(bytePtr + byteOffset) = value;
/// </summary>
/// <typeparam name="T">The type of the value type to write to memory.</typeparam>
/// <param name="byteOffset">The location in memory to write to. You
/// may have to consider alignment.</param>
/// <param name="value">The value type to write to memory.</param>
[CLSCompliant(false)]
public void Write<T>(ulong byteOffset, T value) where T : struct
{
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);
// *((T*) (_ptr + byteOffset)) = value;
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
GenericStructureToPtr(ref value, ptr, sizeofT);
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
[CLSCompliant(false)]
public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
if (array == null)
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
uint alignedSizeofT = Marshal.AlignedSizeOf<T>();
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
for (int i = 0; i < count; i++)
unsafe { GenericStructureToPtr(ref array[i + index], ptr + alignedSizeofT * i, sizeofT); }
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
/// <summary>
/// Returns the number of bytes in the memory region.
/// </summary>
[CLSCompliant(false)]
public ulong ByteLength
{
get
{
if (_numBytes == Uninitialized)
throw NotInitialized();
return (ulong)_numBytes;
}
}
/* No indexer. The perf would be misleadingly bad. People should use
* AcquirePointer and ReleasePointer instead. */
private void SpaceCheck(byte* ptr, ulong sizeInBytes)
{
if ((ulong)_numBytes < sizeInBytes)
NotEnoughRoom();
if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes)
NotEnoughRoom();
}
private static void NotEnoughRoom()
{
throw new ArgumentException(SR.Arg_BufferTooSmall);
}
private static InvalidOperationException NotInitialized()
{
Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize);
}
// FCALL limitations mean we can't have generic FCALL methods. However, we can pass
// TypedReferences to FCALL methods.
internal static void GenericPtrToStructure<T>(byte* ptr, out T structure, uint sizeofT) where T : struct
{
structure = default(T); // Dummy assignment to silence the compiler
PtrToStructureNative(ptr, __makeref(structure), sizeofT);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void PtrToStructureNative(byte* ptr, /*out T*/ TypedReference structure, uint sizeofT);
internal static void GenericStructureToPtr<T>(ref T structure, byte* ptr, uint sizeofT) where T : struct
{
StructureToPtrNative(__makeref(structure), ptr, sizeofT);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void StructureToPtrNative(/*ref T*/ TypedReference structure, byte* ptr, uint sizeofT);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http.Headers;
using System.Reactive.Linq;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Lucene.Net.Linq;
using NuGet.Lucene.IO;
using Lucene.Net.QueryParsers;
using NuGet.Lucene.Util;
using LuceneDirectory = Lucene.Net.Store.Directory;
#if NET_4_5
using TaskEx=System.Threading.Tasks.Task;
#endif
namespace NuGet.Lucene
{
public class LucenePackageRepository : LocalPackageRepository, ILucenePackageRepository
{
private static readonly ISet<char> AdvancedQueryCharacters = new HashSet<char>(new[] {':', '+', '-', '[', ']', '(', ')'});
private static readonly ILog Log = LogManager.GetLogger<LucenePackageRepository>();
public LuceneDataProvider LuceneDataProvider { get; set; }
public IQueryable<LucenePackage> LucenePackages { get; set; }
public IPackageIndexer Indexer { get; set; }
public IHashProvider HashProvider { get; set; }
public string HashAlgorithmName { get; set; }
public bool DisablePackageHash { get; set; }
public string LucenePackageSource { get; set; }
public PackageOverwriteMode PackageOverwriteMode { get; set; }
/// <summary>
/// Flag that enables or disables including list of files on <see cref="LucenePackage.Files"/>.
/// Setting this flag to <c>true</c> keeps the index smaller when packages with many files
/// are added. Setting this flag to <c>false</c> enables queries that match packages that
/// contain a file path.
///
/// Default: <c>false</c>.
/// </summary>
public bool IgnorePackageFiles { get; set; }
private readonly FrameworkCompatibilityTool frameworkCompatibilityTool = new FrameworkCompatibilityTool();
private readonly object fileSystemLock = new object();
private volatile int packageCount;
public int PackageCount { get { return packageCount; } }
public LucenePackageRepository(IPackagePathResolver packageResolver, IFileSystem fileSystem)
: base(packageResolver, fileSystem)
{
}
public void Initialize()
{
LuceneDataProvider.RegisterCacheWarmingCallback(UpdatePackageCount, () => new LucenePackage(FileSystem));
UpdatePackageCount(LucenePackages);
frameworkCompatibilityTool.InitializeKnownFrameworkShortNamesFromIndex(LuceneDataProvider);
}
public override string Source
{
get { return LucenePackageSource ?? base.Source; }
}
public virtual HashingWriteStream CreateStreamForStagingPackage()
{
var tmpPath = Path.Combine(StagingDirectory, "package-" + Guid.NewGuid() + ".nupkg.tmp");
var directoryName = Path.GetDirectoryName(tmpPath);
if (directoryName != null && !Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
return new HashingWriteStream(tmpPath, OpenFileWriteStream(tmpPath), HashAlgorithm.Create(HashAlgorithmName));
}
public virtual IFastZipPackage LoadStagedPackage(HashingWriteStream packageStream)
{
packageStream.Dispose();
return FastZipPackage.Open(packageStream.FileLocation, packageStream.Hash);
}
public void DiscardStagedPackage(HashingWriteStream packageStream)
{
packageStream.Dispose();
FileSystem.DeleteFile(packageStream.FileLocation);
}
protected virtual string StagingDirectory
{
get { return FileSystem.GetTempFolder(); }
}
public async Task AddPackageAsync(IPackage package, CancellationToken cancellationToken)
{
var lucenePackage = await DownloadOrMoveOrAddPackageToFileSystemAsync(package, cancellationToken);
Log.Info(m => m("Indexing package {0} {1}", package.Id, package.Version));
await Indexer.AddPackageAsync(lucenePackage, cancellationToken);
}
private async Task<LucenePackage> DownloadOrMoveOrAddPackageToFileSystemAsync(IPackage package, CancellationToken cancellationToken)
{
string temporaryLocation = null;
try
{
if (PackageOverwriteMode == PackageOverwriteMode.Deny && FindPackage(package.Id, package.Version) != null)
{
throw new PackageOverwriteDeniedException(package);
}
LucenePackage lucenePackage = null;
var fastZipPackage = package as IFastZipPackage;
var dataPackage = package as DataServicePackage;
if (dataPackage != null)
{
fastZipPackage = await DownloadDataServicePackage(dataPackage, cancellationToken);
lucenePackage = Convert(fastZipPackage);
lucenePackage.OriginUrl = dataPackage.DownloadUrl;
lucenePackage.IsMirrored = true;
}
temporaryLocation = fastZipPackage != null ? fastZipPackage.GetFileLocation() : null;
if (!string.IsNullOrEmpty(temporaryLocation))
{
MoveFileWithOverwrite(temporaryLocation, base.GetPackageFilePath(fastZipPackage));
if (lucenePackage == null)
{
lucenePackage = Convert(fastZipPackage);
}
return lucenePackage;
}
else
{
return await AddPackageToFileSystemAsync(package);
}
}
finally
{
if (!string.IsNullOrEmpty(temporaryLocation))
{
FileSystem.DeleteFile(temporaryLocation);
}
}
}
private Task<LucenePackage> AddPackageToFileSystemAsync(IPackage package)
{
Log.Info(m => m("Adding package {0} {1} to file system", package.Id, package.Version));
lock (fileSystemLock)
{
base.AddPackage(package);
}
return TaskEx.FromResult(Convert(package));
}
private async Task<IFastZipPackage> DownloadDataServicePackage(DataServicePackage dataPackage, CancellationToken cancellationToken)
{
var assembly = typeof(LucenePackageRepository).Assembly;
using (var client = CreateHttpClient())
{
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(assembly.GetName().Name,
assembly.GetName().Version.ToString()));
client.DefaultRequestHeaders.Add(RepositoryOperationNames.OperationHeaderName,
RepositoryOperationNames.Mirror);
Stream stream;
using (cancellationToken.Register(client.CancelPendingRequests))
{
stream = await client.GetStreamAsync(dataPackage.DownloadUrl);
}
cancellationToken.ThrowIfCancellationRequested();
using (var hashingStream = CreateStreamForStagingPackage())
{
await stream.CopyToAsync(hashingStream, 4096, cancellationToken);
return LoadStagedPackage(hashingStream);
}
}
}
protected virtual System.Net.Http.HttpClient CreateHttpClient()
{
return new System.Net.Http.HttpClient();
}
protected virtual Stream OpenFileWriteStream(string path)
{
return File.OpenWrite(path);
}
protected virtual void MoveFileWithOverwrite(string src, string dest)
{
dest = FileSystem.GetFullPath(dest);
lock (fileSystemLock)
{
var parent = Path.GetDirectoryName(dest);
if (parent != null && !Directory.Exists(parent))
{
Directory.CreateDirectory(parent);
}
if (File.Exists(dest))
{
File.Delete(dest);
}
Log.Info(m => m("Moving package file from {0} to {1}.", src, dest));
File.Move(src, dest);
}
}
public override void AddPackage(IPackage package)
{
var task = TaskEx.Run(async () => await AddPackageAsync(package, CancellationToken.None));
task.Wait();
}
public async Task IncrementDownloadCountAsync(IPackage package, CancellationToken cancellationToken)
{
await Indexer.IncrementDownloadCountAsync(package, cancellationToken);
}
private void UpdatePackageCount(IQueryable<LucenePackage> packages)
{
packageCount = packages.Count();
Log.Info(m => m("Refreshing index. Package count: " + packageCount));
}
public async Task RemovePackageAsync(IPackage package, CancellationToken cancellationToken)
{
var task = Indexer.RemovePackageAsync(package, cancellationToken);
lock (fileSystemLock)
{
base.RemovePackage(package);
}
await task;
}
public override void RemovePackage(IPackage package)
{
var task = TaskEx.Run(async () => await RemovePackageAsync(package, CancellationToken.None));
task.Wait();
}
public override IQueryable<IPackage> GetPackages()
{
return LucenePackages;
}
public override IPackage FindPackage(string packageId, SemanticVersion version)
{
return FindLucenePackage(packageId, version);
}
public LucenePackage FindLucenePackage(string packageId, SemanticVersion version)
{
var packages = LucenePackages;
var matches = from p in packages
where p.Id == packageId && p.Version == new StrictSemanticVersion(version)
select p;
return matches.SingleOrDefault();
}
public override IEnumerable<IPackage> FindPackagesById(string packageId)
{
return LucenePackages.Where(p => p.Id == packageId);
}
public IEnumerable<string> GetAvailableSearchFieldNames()
{
var propertyNames = LuceneDataProvider.GetIndexedPropertyNames<LucenePackage>();
var aliasMap = NuGetQueryParser.IndexedPropertyAliases;
return propertyNames.Except(aliasMap.Values).Union(aliasMap.Keys);
}
public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
return Search(new SearchCriteria(searchTerm)
{
TargetFrameworks = targetFrameworks,
AllowPrereleaseVersions = allowPrereleaseVersions
});
}
public IQueryable<IPackage> Search(SearchCriteria criteria)
{
var packages = LucenePackages;
if (!string.IsNullOrEmpty(criteria.SearchTerm))
{
packages = ApplySearchCriteria(criteria, packages);
}
if (!criteria.AllowPrereleaseVersions)
{
packages = packages.Where(p => !p.IsPrerelease);
}
if (criteria.TargetFrameworks != null && criteria.TargetFrameworks.Any())
{
packages = ApplyTargetFrameworkFilter(criteria, packages);
}
if (criteria.PackageOriginFilter != PackageOriginFilter.Any)
{
var flag = criteria.PackageOriginFilter == PackageOriginFilter.Mirror;
packages = packages.Where(p => p.IsMirrored == flag);
}
packages = ApplySort(criteria, packages);
return packages;
}
protected virtual IQueryable<LucenePackage> ApplyTargetFrameworkFilter(SearchCriteria criteria, IQueryable<LucenePackage> packages)
{
return frameworkCompatibilityTool.FilterByTargetFramework(packages, criteria.TargetFrameworks.First());
}
protected virtual IQueryable<LucenePackage> ApplySearchCriteria(SearchCriteria criteria, IQueryable<LucenePackage> packages)
{
var advancedQuerySyntax = criteria.SearchTerm.Any(c => AdvancedQueryCharacters.Contains(c));
if (advancedQuerySyntax)
{
var queryParser = new NuGetQueryParser(LuceneDataProvider.CreateQueryParser<LucenePackage>())
{
AllowLeadingWildcard = true
};
try
{
var query = queryParser.Parse(criteria.SearchTerm);
return packages.Where(query);
}
catch (ParseException ex)
{
throw new InvalidSearchCriteriaException("Failed to parse query", ex);
}
}
return from
pkg in packages
where
((pkg.Id == criteria.SearchTerm).Boost(5) ||
(pkg.SearchId == criteria.SearchTerm).Boost(4) ||
(pkg.Title == criteria.SearchTerm).Boost(3) ||
(pkg.Tags == criteria.SearchTerm).Boost(2) ||
(pkg.Authors.Contains(criteria.SearchTerm) || pkg.Owners.Contains(criteria.SearchTerm)).Boost(2) ||
(pkg.Files.Contains(criteria.SearchTerm)) ||
(pkg.Summary == criteria.SearchTerm || pkg.Description == criteria.SearchTerm)).AllowSpecialCharacters()
select
pkg;
}
private static IQueryable<LucenePackage> ApplySort(SearchCriteria criteria, IQueryable<LucenePackage> packages)
{
Expression<Func<LucenePackage, object>> sortSelector = null;
switch (criteria.SortField)
{
case SearchSortField.Id:
sortSelector = p => p.Id;
break;
case SearchSortField.Title:
sortSelector = p => p.Title;
break;
case SearchSortField.Published:
sortSelector = p => p.Published;
break;
case SearchSortField.Score:
sortSelector = p => p.Score();
break;
}
if (sortSelector == null)
{
return packages;
}
var orderedPackages = criteria.SortDirection == SearchSortDirection.Ascending
? packages.OrderBy(sortSelector)
: packages.OrderByDescending(sortSelector);
if (criteria.SortField == SearchSortField.Id)
{
orderedPackages = orderedPackages.ThenByDescending(p => p.Version);
}
return orderedPackages;
}
public IEnumerable<IPackage> GetUpdates(IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions,
IEnumerable<FrameworkName> targetFrameworks, IEnumerable<IVersionSpec> versionConstraints)
{
var baseQuery = LucenePackages;
if (!includePrerelease)
{
baseQuery = baseQuery.Where(pkg => !pkg.IsPrerelease);
}
var targetFrameworkList = (targetFrameworks ?? Enumerable.Empty<FrameworkName>()).ToList();
var versionConstraintList = (versionConstraints ?? Enumerable.Empty<IVersionSpec>()).ToList();
var results = new List<IPackage>();
var i = 0;
foreach (var current in packages)
{
var ii = i;
var id = current.Id;
var currentVersion = new StrictSemanticVersion(current.Version);
var matchedPackages = (IEnumerable<LucenePackage>)baseQuery.Where(pkg => pkg.Id == id).OrderBy(pkg => pkg.Version).ToList();
if (targetFrameworkList.Any())
{
matchedPackages = matchedPackages.Where(pkg => targetFrameworkList.Any(fwk => VersionUtility.IsCompatible(fwk, pkg.GetSupportedFrameworks())));
}
matchedPackages = matchedPackages.Where(pkg => pkg.Version > currentVersion);
if (versionConstraintList.Any() && versionConstraintList[ii] != null)
{
matchedPackages = matchedPackages.Where(pkg => versionConstraintList[ii].Satisfies(pkg.Version.SemanticVersion));
}
if (includeAllVersions)
{
results.AddRange(matchedPackages);
}
else
{
var latest = matchedPackages.LastOrDefault();
if (latest != null)
{
results.Add(latest);
}
}
i++;
}
return results;
}
public Task SynchronizeWithFileSystem(SynchronizationMode mode, CancellationToken cancellationToken)
{
Log.Info(m => m("Synchronizing packages with filesystem."));
return Indexer.SynchronizeIndexWithFileSystemAsync(mode, cancellationToken);
}
public RepositoryInfo GetStatus()
{
return new RepositoryInfo(packageCount, Indexer.GetIndexingStatus());
}
public void Optimize()
{
Indexer.Optimize();
}
public IObservable<RepositoryInfo> StatusChanged
{
get
{
return Indexer.StatusChanged.Select(s => new RepositoryInfo(packageCount, s));
}
}
public LucenePackage LoadFromIndex(string path)
{
var relativePath = FileSystem.MakeRelative(path);
var results = from p in LucenePackages where p.Path == relativePath select p;
return results.SingleOrDefault();
}
public LucenePackage LoadFromFileSystem(string path)
{
var fullPath = FileSystem.GetFullPath(path);
var package = Convert(OpenPackage(fullPath), new LucenePackage(FileSystem) { Path = FileSystem.MakeRelative(fullPath) });
return package;
}
protected override string GetPackageFilePath(IPackage package)
{
return GetPackageFilePath(package);
}
protected override string GetPackageFilePath(string id, SemanticVersion version)
{
return GetPackageFilePath(new PackageName(id, version));
}
protected string GetPackageFilePath(IPackageName package)
{
var lucenePackage = package as LucenePackage ?? FindLucenePackage(package.Id, package.Version);
if (lucenePackage != null && !string.IsNullOrEmpty(lucenePackage.Path))
{
return lucenePackage.Path;
}
return base.GetPackageFilePath(package.Id, package.Version);
}
protected virtual IPackage OpenPackage(string path)
{
if (DisablePackageHash)
{
return FastZipPackage.Open(path, new byte[0]);
}
return FastZipPackage.Open(path, HashProvider);
}
public LucenePackage Convert(IPackage package)
{
var lucenePackage = package as LucenePackage;
if (lucenePackage == null)
{
lucenePackage = new LucenePackage(FileSystem);
Convert(package, lucenePackage);
}
frameworkCompatibilityTool.AddKnownFrameworkShortNames(lucenePackage.SupportedFrameworks);
return lucenePackage;
}
private LucenePackage Convert(IPackage package, LucenePackage lucenePackage)
{
CopyPackageData(package, lucenePackage);
if (string.IsNullOrWhiteSpace(lucenePackage.Path))
{
lucenePackage.Path = GetPackageFilePath(lucenePackage);
}
CalculateDerivedData(package, lucenePackage, lucenePackage.Path, lucenePackage.GetStream);
return lucenePackage;
}
private void CopyPackageData(IPackage package, LucenePackage lucenePackage)
{
lucenePackage.Id = package.Id;
lucenePackage.Version = new StrictSemanticVersion(package.Version.ToString());
lucenePackage.MinClientVersion = package.MinClientVersion;
lucenePackage.Title = package.Title;
lucenePackage.Authors = (package.Authors ?? Enumerable.Empty<string>()).Select(i => i.Trim()).ToArray();
lucenePackage.Owners = (package.Owners ?? Enumerable.Empty<string>()).Select(i => i.Trim()).ToArray();
lucenePackage.IconUrl = FilterPlaceholderUri(package.IconUrl);
lucenePackage.LicenseUrl = FilterPlaceholderUri(package.LicenseUrl);
lucenePackage.ProjectUrl = FilterPlaceholderUri(package.ProjectUrl);
lucenePackage.RequireLicenseAcceptance = package.RequireLicenseAcceptance;
lucenePackage.Description = package.Description;
lucenePackage.Summary = package.Summary;
lucenePackage.ReleaseNotes = package.ReleaseNotes;
lucenePackage.Language = package.Language;
lucenePackage.Tags = package.Tags;
lucenePackage.Copyright = package.Copyright;
lucenePackage.FrameworkAssemblies = package.FrameworkAssemblies;
lucenePackage.DependencySets = package.DependencySets;
lucenePackage.ReportAbuseUrl = package.ReportAbuseUrl;
lucenePackage.DownloadCount = package.DownloadCount;
lucenePackage.IsAbsoluteLatestVersion = package.IsAbsoluteLatestVersion;
lucenePackage.IsLatestVersion = package.IsLatestVersion;
lucenePackage.Listed = package.Listed;
lucenePackage.Published = package.Published;
lucenePackage.AssemblyReferences = package.AssemblyReferences;
lucenePackage.PackageAssemblyReferences = package.PackageAssemblyReferences;
lucenePackage.DevelopmentDependency = package.DevelopmentDependency;
}
private Uri FilterPlaceholderUri(Uri uri)
{
if (uri != null && uri.IsAbsoluteUri && uri.Host.ToLowerInvariant().Contains("url_here_or_delete_this_line"))
{
return null;
}
return uri;
}
protected virtual void CalculateDerivedData(IPackage sourcePackage, LucenePackage package, string path, Func<Stream> openStream)
{
var fastPackage = sourcePackage as FastZipPackage;
if (fastPackage == null)
{
CalculateDerivedDataFromStream(package, openStream);
}
else
{
package.PackageSize = fastPackage.Size;
package.PackageHash = System.Convert.ToBase64String(fastPackage.Hash);
package.Created = fastPackage.Created;
}
package.PackageHashAlgorithm = HashAlgorithmName;
package.LastUpdated = GetLastModified(package, path);
package.Published = package.LastUpdated;
package.Path = path;
package.SupportedFrameworks = sourcePackage.GetSupportedFrameworks().Select(VersionUtility.GetShortFrameworkName);
var files = IgnorePackageFiles
? Enumerable.Empty<string>()
: sourcePackage.GetFiles().Select(f => f.Path).ToArray();
package.Files = files;
}
private DateTimeOffset GetLastModified(LucenePackage package, string path)
{
var lastModified = FileSystem.GetLastModified(path);
if (lastModified.Year <= 1700)
{
lastModified = package.Created;
}
return lastModified;
}
private void CalculateDerivedDataFromStream(LucenePackage package, Func<Stream> openStream)
{
using (var stream = openStream())
{
if (!stream.CanSeek)
{
throw new InvalidOperationException("Package stream must support CanSeek.");
}
package.Created = FastZipPackageBase.GetPackageCreatedDateTime(stream);
package.PackageSize = stream.Length;
stream.Seek(0, SeekOrigin.Begin);
package.PackageHash = System.Convert.ToBase64String(HashProvider.CalculateHash(stream));
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Xml;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;
namespace Dalssoft.DiagramNet
{
public class Designer : System.Windows.Forms.UserControl
{
private System.ComponentModel.IContainer components;
#region Designer Control Initialization
//Document
private Document document = new Document();
// Drag and Drop
MoveAction moveAction = null;
// Selection
BaseElement selectedElement;
private bool isMultiSelection = false;
private RectangleElement selectionArea = new RectangleElement(0, 0, 0, 0);
private IController[] controllers;
private BaseElement mousePointerElement;
// Resize
private ResizeAction resizeAction = null;
// Add Element
private bool isAddSelection = false;
// Link
private bool isAddLink = false;
private ConnectorElement connStart;
private ConnectorElement connEnd;
private BaseLinkElement linkLine;
// Label
private bool isEditLabel = false;
private LabelElement selectedLabel;
private System.Windows.Forms.TextBox labelTextBox = new TextBox();
private EditLabelAction editLabelAction = null;
//Undo
[NonSerialized]
private UndoManager undo = new UndoManager(5);
private bool changed = false;
public Designer()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// This change control to not flick
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
// Selection Area Properties
selectionArea.Opacity = 40;
selectionArea.FillColor1 = SystemColors.Control;
selectionArea.FillColor2 = Color.Empty;
selectionArea.BorderColor = SystemColors.Control;
// Link Line Properties
//linkLine.BorderColor = Color.FromArgb(127, Color.DarkGray);
//linkLine.BorderWidth = 4;
// Label Edit
labelTextBox.BorderStyle = BorderStyle.FixedSingle;
labelTextBox.Multiline = true;
labelTextBox.Hide();
this.Controls.Add(labelTextBox);
//EventsHandlers
RecreateEventsHandlers();
}
#endregion
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// Designer
//
this.AutoScroll = true;
this.BackColor = System.Drawing.SystemColors.Window;
this.Name = "Designer";
}
#endregion
public new void Invalidate()
{
if (document.Elements.Count > 0)
{
for (int i = 0; i <= document.Elements.Count - 1; i++)
{
BaseElement el = document.Elements[i];
Invalidate(el);
if (el is ILabelElement)
Invalidate(((ILabelElement)el).Label);
}
}
else
base.Invalidate();
if ((moveAction != null) && (moveAction.IsMoving))
this.AutoScrollMinSize = new Size((int)((document.Location.X + document.Size.Width) * document.Zoom), (int)((document.Location.Y + document.Size.Height) * document.Zoom));
}
private void Invalidate(BaseElement el)
{
this.Invalidate(el, false);
}
private void Invalidate(BaseElement el, bool force)
{
if (el == null) return;
if ((force) || (el.IsInvalidated))
{
Rectangle invalidateRec = Goc2Gsc(el.invalidateRec);
invalidateRec.Inflate(10, 10);
base.Invalidate(invalidateRec);
}
}
#region Events Overrides
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
GraphicsContainer gc;
Matrix mtx;
g.PageUnit = GraphicsUnit.Pixel;
Point scrollPoint = this.AutoScrollPosition;
g.TranslateTransform(scrollPoint.X, scrollPoint.Y);
//Zoom
mtx = g.Transform;
gc = g.BeginContainer();
g.SmoothingMode = document.SmoothingMode;
g.PixelOffsetMode = document.PixelOffsetMode;
g.CompositingQuality = document.CompositingQuality;
g.ScaleTransform(document.Zoom, document.Zoom);
Rectangle clipRectangle = Gsc2Goc(e.ClipRectangle);
document.DrawElements(g, clipRectangle);
if (!((resizeAction != null) && (resizeAction.IsResizing)))
document.DrawSelections(g, e.ClipRectangle);
if ((isMultiSelection) || (isAddSelection))
DrawSelectionRectangle(g);
if (isAddLink)
{
linkLine.CalcLink();
linkLine.Draw(g);
}
if ((resizeAction != null) && (!((moveAction != null) && (moveAction.IsMoving))))
resizeAction.DrawResizeCorner(g);
if (mousePointerElement != null)
{
if (mousePointerElement is IControllable)
{
IController ctrl = ((IControllable)mousePointerElement).GetController();
ctrl.DrawSelection(g);
}
}
g.EndContainer(gc);
g.Transform = mtx;
base.OnPaint(e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
Graphics g = e.Graphics;
GraphicsContainer gc;
Matrix mtx;
g.PageUnit = GraphicsUnit.Pixel;
mtx = g.Transform;
gc = g.BeginContainer();
Rectangle clipRectangle = Gsc2Goc(e.ClipRectangle);
document.DrawGrid(g, clipRectangle);
g.EndContainer(gc);
g.Transform = mtx;
}
protected override void OnKeyDown(KeyEventArgs e)
{
//Delete element
if (e.KeyCode == Keys.Delete)
{
DeleteSelectedElements();
EndGeneralAction();
base.Invalidate();
}
//Undo
if (e.Control && e.KeyCode == Keys.Z)
{
if (undo.CanUndo)
Undo();
}
//Copy
if ((e.Control) && (e.KeyCode == Keys.C))
{
this.Copy();
}
//Paste
if ((e.Control) && (e.KeyCode == Keys.V))
{
this.Paste();
}
//Cut
if ((e.Control) && (e.KeyCode == Keys.X))
{
this.Cut();
}
base.OnKeyDown(e);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
document.WindowSize = this.Size;
}
#region Mouse Events
protected override void OnMouseDown(MouseEventArgs e)
{
Point mousePoint;
//ShowSelectionCorner((document.Action==DesignerAction.Select));
switch (document.Action)
{
// SELECT
case DesignerAction.Connect:
case DesignerAction.Select:
if (e.Button == MouseButtons.Left)
{
mousePoint = Gsc2Goc(new Point(e.X, e.Y));
//Verify resize action
StartResizeElement(mousePoint);
if ((resizeAction != null) && (resizeAction.IsResizing)) break;
//Verify label editing
if (isEditLabel)
{
EndEditLabel();
}
// Search element by click
selectedElement = document.FindElement(mousePoint);
if (selectedElement != null)
{
//Events
ElementMouseEventArgs eventMouseDownArg = new ElementMouseEventArgs(selectedElement, e.X, e.Y);
OnElementMouseDown(eventMouseDownArg);
// Double-click to edit Label
if ((e.Clicks == 2) && (selectedElement is ILabelElement))
{
selectedLabel = ((ILabelElement)selectedElement).Label;
StartEditLabel();
break;
}
// Element selected
if (selectedElement is ConnectorElement)
{
StartAddLink((ConnectorElement)selectedElement, mousePoint);
selectedElement = null;
}
else
StartSelectElements(selectedElement, mousePoint);
}
else
{
// If click is on neutral area, clear selection
document.ClearSelection();
Point p = Gsc2Goc(new Point(e.X, e.Y)); ;
isMultiSelection = true;
selectionArea.Visible = true;
selectionArea.Location = p;
selectionArea.Size = new Size(0, 0);
if (resizeAction != null)
resizeAction.ShowResizeCorner(false);
}
base.Invalidate();
}
break;
// ADD
case DesignerAction.Add:
if (e.Button == MouseButtons.Left)
{
mousePoint = Gsc2Goc(new Point(e.X, e.Y));
StartAddElement(mousePoint);
}
break;
// DELETE
case DesignerAction.Delete:
if (e.Button == MouseButtons.Left)
{
mousePoint = Gsc2Goc(new Point(e.X, e.Y));
DeleteElement(mousePoint);
}
break;
}
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.None)
{
this.Cursor = Cursors.Arrow;
Point mousePoint = Gsc2Goc(new Point(e.X, e.Y));
if ((resizeAction != null)
&& ((document.Action == DesignerAction.Select)
|| ((document.Action == DesignerAction.Connect)
&& (resizeAction.IsResizingLink))))
{
this.Cursor = resizeAction.UpdateResizeCornerCursor(mousePoint);
}
if (document.Action == DesignerAction.Connect)
{
BaseElement mousePointerElementTMP = document.FindElement(mousePoint);
if (mousePointerElement != mousePointerElementTMP)
{
if (mousePointerElementTMP is ConnectorElement)
{
mousePointerElement = mousePointerElementTMP;
mousePointerElement.Invalidate();
this.Invalidate(mousePointerElement, true);
}
else if (mousePointerElement != null)
{
mousePointerElement.Invalidate();
this.Invalidate(mousePointerElement, true);
mousePointerElement = null;
}
}
}
else
{
this.Invalidate(mousePointerElement, true);
mousePointerElement = null;
}
}
if (e.Button == MouseButtons.Left)
{
Point dragPoint = Gsc2Goc(new Point(e.X, e.Y));
if ((resizeAction != null) && (resizeAction.IsResizing))
{
resizeAction.Resize(dragPoint);
this.Invalidate();
}
if ((moveAction != null) && (moveAction.IsMoving))
{
moveAction.Move(dragPoint);
this.Invalidate();
}
if ((isMultiSelection) || (isAddSelection))
{
Point p = Gsc2Goc(new Point(e.X, e.Y));
selectionArea.Size = new Size(p.X - selectionArea.Location.X, p.Y - selectionArea.Location.Y);
selectionArea.Invalidate();
this.Invalidate(selectionArea, true);
}
if (isAddLink)
{
selectedElement = document.FindElement(dragPoint);
if ((selectedElement is ConnectorElement)
&& (document.CanAddLink(connStart, (ConnectorElement)selectedElement)))
linkLine.Connector2 = (ConnectorElement)selectedElement;
else
linkLine.Connector2 = connEnd;
IMoveController ctrl = (IMoveController)((IControllable)connEnd).GetController();
ctrl.Move(dragPoint);
//this.Invalidate(linkLine, true); //TODO
base.Invalidate();
}
}
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
Rectangle selectionRectangle = selectionArea.GetUnsignedRectangle();
if ((moveAction != null) && (moveAction.IsMoving))
{
ElementEventArgs eventClickArg = new ElementEventArgs(selectedElement);
OnElementClick(eventClickArg);
moveAction.End();
moveAction = null;
ElementMouseEventArgs eventMouseUpArg = new ElementMouseEventArgs(selectedElement, e.X, e.Y);
OnElementMouseUp(eventMouseUpArg);
if (changed)
AddUndo();
}
// Select
if (isMultiSelection)
{
EndSelectElements(selectionRectangle);
}
// Add element
else if (isAddSelection)
{
EndAddElement(selectionRectangle);
}
// Add link
else if (isAddLink)
{
Point mousePoint = Gsc2Goc(new Point(e.X, e.Y));
EndAddLink();
AddUndo();
}
// Resize
if (resizeAction != null)
{
if (resizeAction.IsResizing)
{
Point mousePoint = Gsc2Goc(new Point(e.X, e.Y));
resizeAction.End(mousePoint);
AddUndo();
}
resizeAction.UpdateResizeCorner();
}
RestartInitValues();
base.Invalidate();
base.OnMouseUp(e);
}
#endregion
#endregion
#region Events Raising
// element handler
public delegate void ElementEventHandler(object sender, ElementEventArgs e);
#region Element Mouse Events
// CLICK
[Category("Element")]
public event ElementEventHandler ElementClick;
protected virtual void OnElementClick(ElementEventArgs e)
{
if (ElementClick != null)
{
ElementClick(this, e);
}
}
// mouse handler
public delegate void ElementMouseEventHandler(object sender, ElementMouseEventArgs e);
// MOUSE DOWN
[Category("Element")]
public event ElementMouseEventHandler ElementMouseDown;
protected virtual void OnElementMouseDown(ElementMouseEventArgs e)
{
if (ElementMouseDown != null)
{
ElementMouseDown(this, e);
}
}
// MOUSE UP
[Category("Element")]
public event ElementMouseEventHandler ElementMouseUp;
protected virtual void OnElementMouseUp(ElementMouseEventArgs e)
{
if (ElementMouseUp != null)
{
ElementMouseUp(this, e);
}
}
#endregion
#region Element Move Events
// Before Move
[Category("Element")]
public event ElementEventHandler ElementMoving;
protected virtual void OnElementMoving(ElementEventArgs e)
{
if (ElementMoving != null)
{
ElementMoving(this, e);
}
}
// After Move
[Category("Element")]
public event ElementEventHandler ElementMoved;
protected virtual void OnElementMoved(ElementEventArgs e)
{
if (ElementMoved != null)
{
ElementMoved(this, e);
}
}
#endregion
#region Element Resize Events
// Before Resize
[Category("Element")]
public event ElementEventHandler ElementResizing;
protected virtual void OnElementResizing(ElementEventArgs e)
{
if (ElementResizing != null)
{
ElementResizing(this, e);
}
}
// After Resize
[Category("Element")]
public event ElementEventHandler ElementResized;
protected virtual void OnElementResized(ElementEventArgs e)
{
if (ElementResized != null)
{
ElementResized(this, e);
}
}
#endregion
#region Element Connect Events
// connect handler
public delegate void ElementConnectEventHandler(object sender, ElementConnectEventArgs e);
// Before Connect
[Category("Element")]
public event ElementConnectEventHandler ElementConnecting;
protected virtual void OnElementConnecting(ElementConnectEventArgs e)
{
if (ElementConnecting != null)
{
ElementConnecting(this, e);
}
}
// After Connect
[Category("Element")]
public event ElementConnectEventHandler ElementConnected;
protected virtual void OnElementConnected(ElementConnectEventArgs e)
{
if (ElementConnected != null)
{
ElementConnected(this, e);
}
}
#endregion
#region Element Selection Events
// connect handler
public delegate void ElementSelectionEventHandler(object sender, ElementSelectionEventArgs e);
// Selection
[Category("Element")]
public event ElementSelectionEventHandler ElementSelection;
protected virtual void OnElementSelection(ElementSelectionEventArgs e)
{
if (ElementSelection != null)
{
ElementSelection(this, e);
}
}
#endregion
#endregion
#region Events Handling
private void document_PropertyChanged(object sender, EventArgs e)
{
if (!IsChanging())
{
base.Invalidate();
}
}
private void document_AppearancePropertyChanged(object sender, EventArgs e)
{
if (!IsChanging())
{
AddUndo();
base.Invalidate();
}
}
private void document_ElementPropertyChanged(object sender, EventArgs e)
{
changed = true;
if (!IsChanging())
{
AddUndo();
base.Invalidate();
}
}
private void document_ElementSelection(object sender, ElementSelectionEventArgs e)
{
OnElementSelection(e);
}
#endregion
#region Properties
public Document Document
{
get
{
return document;
}
}
public bool CanUndo
{
get
{
return undo.CanUndo;
}
}
public bool CanRedo
{
get
{
return undo.CanRedo;
}
}
private bool IsChanging()
{
return (
((moveAction != null) && (moveAction.IsMoving)) //isDragging
|| isAddLink || isMultiSelection ||
((resizeAction != null) && (resizeAction.IsResizing)) //isResizing
);
}
#endregion
#region Draw Methods
/// <summary>
/// Graphic surface coordinates to graphic object coordinates.
/// </summary>
/// <param name="p">Graphic surface point.</param>
/// <returns></returns>
public Point Gsc2Goc(Point gsp)
{
float zoom = document.Zoom;
gsp.X = (int)((gsp.X - this.AutoScrollPosition.X) / zoom);
gsp.Y = (int)((gsp.Y - this.AutoScrollPosition.Y) / zoom);
return gsp;
}
public Rectangle Gsc2Goc(Rectangle gsr)
{
float zoom = document.Zoom;
gsr.X = (int)((gsr.X - this.AutoScrollPosition.X) / zoom);
gsr.Y = (int)((gsr.Y - this.AutoScrollPosition.Y) / zoom);
gsr.Width = (int)(gsr.Width / zoom);
gsr.Height = (int)(gsr.Height / zoom);
return gsr;
}
public Rectangle Goc2Gsc(Rectangle gsr)
{
float zoom = document.Zoom;
gsr.X = (int)((gsr.X + this.AutoScrollPosition.X) * zoom);
gsr.Y = (int)((gsr.Y + this.AutoScrollPosition.Y) * zoom);
gsr.Width = (int)(gsr.Width * zoom);
gsr.Height = (int)(gsr.Height * zoom);
return gsr;
}
internal void DrawSelectionRectangle(Graphics g)
{
selectionArea.Draw(g);
}
#endregion
#region Open/Save File
public void Save(string fileName)
{
IFormatter formatter = new BinaryFormatter() { AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple };
Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, document);
stream.Close();
}
public void Open(string fileName)
{
IFormatter formatter = new BinaryFormatter() { AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple };
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
document = (Document) formatter.Deserialize(stream);
stream.Close();
RecreateEventsHandlers();
}
public void Save(System.IO.MemoryStream ms)
{
IFormatter formatter = new BinaryFormatter() { AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple };
formatter.Serialize(ms, document);
}
public void Open( System.IO.MemoryStream ms)
{
IFormatter formatter = new BinaryFormatter() { AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple };
document = (Document)formatter.Deserialize(ms);
RecreateEventsHandlers();
}
public void Save(out byte[] buffer)
{
var ms = new System.IO.MemoryStream();
Save(ms);
buffer = ms.ToArray();
}
public void Open(byte[] buffer)
{
Open(new MemoryStream(buffer));
}
#endregion
#region Copy/Paste
public void Copy()
{
if (document.SelectedElements.Count == 0) return;
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, document.SelectedElements.GetArray());
DataObject data = new DataObject(DataFormats.GetFormat("Diagram.NET Element Collection").Name,
stream);
Clipboard.SetDataObject(data);
}
public void Paste()
{
const int pasteStep = 20;
undo.Enabled = false;
IDataObject iData = Clipboard.GetDataObject();
DataFormats.Format format = DataFormats.GetFormat("Diagram.NET Element Collection");
if (iData.GetDataPresent(format.Name))
{
IFormatter formatter = new BinaryFormatter();
Stream stream = (MemoryStream) iData.GetData(format.Name);
BaseElement[] elCol = (BaseElement[]) formatter.Deserialize(stream);
stream.Close();
foreach(BaseElement el in elCol)
{
el.Location = new Point(el.Location.X + pasteStep, el.Location.Y + pasteStep);
}
document.AddElements(elCol);
document.ClearSelection();
document.SelectElements(elCol);
}
undo.Enabled = true;
AddUndo();
EndGeneralAction();
}
public void Cut()
{
this.Copy();
DeleteSelectedElements();
EndGeneralAction();
}
#endregion
#region Start/End Actions and General Functions
#region General
private void EndGeneralAction()
{
RestartInitValues();
if (resizeAction != null) resizeAction.ShowResizeCorner(false);
}
private void RestartInitValues()
{
// Reinitialize status
moveAction = null;
isMultiSelection = false;
isAddSelection = false;
isAddLink = false;
changed = false;
connStart = null;
selectionArea.FillColor1 = SystemColors.Control;
selectionArea.BorderColor = SystemColors.Control;
selectionArea.Visible = false;
document.CalcWindow(true);
}
#endregion
#region Selection
private void StartSelectElements(BaseElement selectedElement, Point mousePoint)
{
// Vefiry if element is in selection
if (!document.SelectedElements.Contains(selectedElement))
{
//Clear selection and add new element to selection
document.ClearSelection();
document.SelectElement(selectedElement);
}
changed = false;
moveAction = new MoveAction();
MoveAction.OnElementMovingDelegate onElementMovingDelegate = new Dalssoft.DiagramNet.MoveAction.OnElementMovingDelegate(OnElementMoving);
moveAction.Start(mousePoint, document, onElementMovingDelegate);
// Get Controllers
controllers = new IController[document.SelectedElements.Count];
for(int i = document.SelectedElements.Count - 1; i >= 0; i--)
{
if (document.SelectedElements[i] is IControllable)
{
// Get General Controller
controllers[i] = ((IControllable) document.SelectedElements[i]).GetController();
}
else
{
controllers[i] = null;
}
}
resizeAction = new ResizeAction();
resizeAction.Select(document);
}
private void EndSelectElements(Rectangle selectionRectangle)
{
document.SelectElements(selectionRectangle);
}
#endregion
#region Resize
private void StartResizeElement(Point mousePoint)
{
if ((resizeAction != null)
&& ((document.Action == DesignerAction.Select)
|| ((document.Action == DesignerAction.Connect)
&& (resizeAction.IsResizingLink))))
{
ResizeAction.OnElementResizingDelegate onElementResizingDelegate = new ResizeAction.OnElementResizingDelegate(OnElementResizing);
resizeAction.Start(mousePoint, onElementResizingDelegate);
if (!resizeAction.IsResizing)
resizeAction = null;
}
}
#endregion
#region Link
private void StartAddLink(ConnectorElement connStart, Point mousePoint)
{
if (document.Action == DesignerAction.Connect)
{
this.connStart = connStart;
this.connEnd = new ConnectorElement(connStart.ParentElement);
connEnd.Location = connStart.Location;
IMoveController ctrl = (IMoveController) ((IControllable) connEnd).GetController();
ctrl.Start(mousePoint);
isAddLink = true;
switch(document.LinkType)
{
case (LinkType.Straight):
linkLine = new StraightLinkElement(connStart, connEnd);
break;
case (LinkType.RightAngle):
linkLine = new RightAngleLinkElement(connStart, connEnd);
break;
}
linkLine.Visible = true;
linkLine.BorderColor = Color.FromArgb(150, Color.Black);
linkLine.BorderWidth = 1;
this.Invalidate(linkLine, true);
OnElementConnecting(new ElementConnectEventArgs(connStart.ParentElement, null, linkLine));
}
}
private void EndAddLink()
{
if (connEnd != linkLine.Connector2)
{
linkLine.Connector1.RemoveLink(linkLine);
linkLine = document.AddLink(linkLine.Connector1, linkLine.Connector2);
OnElementConnected(new ElementConnectEventArgs(linkLine.Connector1.ParentElement, linkLine.Connector2.ParentElement, linkLine));
}
connStart = null;
connEnd = null;
linkLine = null;
}
#endregion
#region Add Element
private void StartAddElement(Point mousePoint)
{
document.ClearSelection();
//Change Selection Area Color
selectionArea.FillColor1 = Color.LightSteelBlue;
selectionArea.BorderColor = Color.WhiteSmoke;
isAddSelection = true;
selectionArea.Visible = true;
selectionArea.Location = mousePoint;
selectionArea.Size = new Size(0, 0);
}
private void EndAddElement(Rectangle selectionRectangle)
{
BaseElement el;
switch (document.ElementType)
{
case ElementType.Rectangle:
el = new RectangleElement(selectionRectangle);
break;
case ElementType.RectangleNode:
el = new RectangleNode(selectionRectangle);
break;
case ElementType.Elipse:
el = new ElipseElement(selectionRectangle);
break;
case ElementType.ElipseNode:
el = new ElipseNode(selectionRectangle);
break;
case ElementType.CommentBox:
el = new CommentBoxElement(selectionRectangle);
break;
case ElementType.CommentBoxNode:
el = new CommentBoxNode(selectionRectangle);
break;
default:
el = new RectangleNode(selectionRectangle);
break;
}
document.AddElement(el);
document.Action = DesignerAction.Select;
}
#endregion
#region Edit Label
private void StartEditLabel()
{
isEditLabel = true;
// Disable resize
if (resizeAction != null)
{
resizeAction.ShowResizeCorner(false);
resizeAction = null;
}
editLabelAction = new EditLabelAction();
editLabelAction.StartEdit(selectedElement, labelTextBox);
}
private void EndEditLabel()
{
if (editLabelAction != null)
{
editLabelAction.EndEdit();
editLabelAction = null;
}
isEditLabel = false;
}
#endregion
#region Delete
private void DeleteElement(Point mousePoint)
{
document.DeleteElement(mousePoint);
selectedElement = null;
document.Action = DesignerAction.Select;
}
private void DeleteSelectedElements()
{
document.DeleteSelectedElements();
}
#endregion
#endregion
#region Undo/Redo
public void Undo()
{
document = (Document) undo.Undo();
RecreateEventsHandlers();
if (resizeAction != null) resizeAction.UpdateResizeCorner();
base.Invalidate();
}
public void Redo()
{
document = (Document) undo.Redo();
RecreateEventsHandlers();
if (resizeAction != null) resizeAction.UpdateResizeCorner();
base.Invalidate();
}
private void AddUndo()
{
undo.AddUndo(document);
}
#endregion
private void RecreateEventsHandlers()
{
document.PropertyChanged += new EventHandler(document_PropertyChanged);
document.AppearancePropertyChanged+=new EventHandler(document_AppearancePropertyChanged);
document.ElementPropertyChanged += new EventHandler(document_ElementPropertyChanged);
document.ElementSelection += new Document.ElementSelectionEventHandler(document_ElementSelection);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable queue.
/// </summary>
/// <typeparam name="T">The type of elements stored in the queue.</typeparam>
[DebuggerDisplay("IsEmpty = {IsEmpty}")]
[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableQueue<T> : IImmutableQueue<T>
{
/// <summary>
/// The singleton empty queue.
/// </summary>
/// <remarks>
/// Additional instances representing the empty queue may exist on deserialized instances.
/// Actually since this queue is a struct, instances don't even apply and there are no singletons.
/// </remarks>
private static readonly ImmutableQueue<T> s_EmptyField = new ImmutableQueue<T>(ImmutableStack<T>.Empty, ImmutableStack<T>.Empty);
/// <summary>
/// The end of the queue that enqueued elements are pushed onto.
/// </summary>
private readonly ImmutableStack<T> _backwards;
/// <summary>
/// The end of the queue from which elements are dequeued.
/// </summary>
private readonly ImmutableStack<T> _forwards;
/// <summary>
/// Backing field for the <see cref="BackwardsReversed"/> property.
/// </summary>
private ImmutableStack<T> _backwardsReversed;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableQueue{T}"/> class.
/// </summary>
/// <param name="forwards">The forwards stack.</param>
/// <param name="backwards">The backwards stack.</param>
internal ImmutableQueue(ImmutableStack<T> forwards, ImmutableStack<T> backwards)
{
Debug.Assert(forwards != null);
Debug.Assert(backwards != null);
_forwards = forwards;
_backwards = backwards;
}
/// <summary>
/// Gets the empty queue.
/// </summary>
public ImmutableQueue<T> Clear()
{
Debug.Assert(s_EmptyField.IsEmpty);
return Empty;
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get
{
Debug.Assert(!_forwards.IsEmpty || _backwards.IsEmpty);
return _forwards.IsEmpty;
}
}
/// <summary>
/// Gets the empty queue.
/// </summary>
public static ImmutableQueue<T> Empty
{
get
{
Debug.Assert(s_EmptyField.IsEmpty);
return s_EmptyField;
}
}
/// <summary>
/// Gets an empty queue.
/// </summary>
IImmutableQueue<T> IImmutableQueue<T>.Clear()
{
Debug.Assert(s_EmptyField.IsEmpty);
return this.Clear();
}
/// <summary>
/// Gets the reversed <see cref="_backwards"/> stack.
/// </summary>
private ImmutableStack<T> BackwardsReversed
{
get
{
// Although this is a lazy-init pattern, no lock is required because
// this instance is immutable otherwise, and a double-assignment from multiple
// threads is harmless.
if (_backwardsReversed == null)
{
_backwardsReversed = _backwards.Reverse();
}
Debug.Assert(_backwardsReversed != null);
return _backwardsReversed;
}
}
/// <summary>
/// Gets the element at the front of the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return _forwards.Peek();
}
#if !NETSTANDARD10
/// <summary>
/// Gets a read-only reference to the element at the front of the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
public ref readonly T PeekRef()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return ref _forwards.PeekRef();
}
#endif
/// <summary>
/// Adds an element to the back of the queue.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// The new queue.
/// </returns>
[Pure]
public ImmutableQueue<T> Enqueue(T value)
{
if (this.IsEmpty)
{
return new ImmutableQueue<T>(ImmutableStack.Create(value), ImmutableStack<T>.Empty);
}
else
{
return new ImmutableQueue<T>(_forwards, _backwards.Push(value));
}
}
/// <summary>
/// Adds an element to the back of the queue.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// The new queue.
/// </returns>
[Pure]
IImmutableQueue<T> IImmutableQueue<T>.Enqueue(T value)
{
return this.Enqueue(value);
}
/// <summary>
/// Returns a queue that is missing the front element.
/// </summary>
/// <returns>A queue; never <c>null</c>.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
public ImmutableQueue<T> Dequeue()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
ImmutableStack<T> f = _forwards.Pop();
if (!f.IsEmpty)
{
return new ImmutableQueue<T>(f, _backwards);
}
else if (_backwards.IsEmpty)
{
return ImmutableQueue<T>.Empty;
}
else
{
return new ImmutableQueue<T>(this.BackwardsReversed, ImmutableStack<T>.Empty);
}
}
/// <summary>
/// Retrieves the item at the head of the queue, and returns a queue with the head element removed.
/// </summary>
/// <param name="value">Receives the value from the head of the queue.</param>
/// <returns>The new queue with the head element removed.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
[Pure]
public ImmutableQueue<T> Dequeue(out T value)
{
value = this.Peek();
return this.Dequeue();
}
/// <summary>
/// Returns a queue that is missing the front element.
/// </summary>
/// <returns>A queue; never <c>null</c>.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
IImmutableQueue<T> IImmutableQueue<T>.Dequeue()
{
return this.Dequeue();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="Enumerator"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.IsEmpty ?
Enumerable.Empty<T>().GetEnumerator() :
new EnumeratorObject(this);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator IEnumerable.GetEnumerator()
{
return new EnumeratorObject(this);
}
}
}
| |
using LavaLeak.Diplomata.Dictionaries;
using LavaLeak.Diplomata.Editor.Controllers;
using LavaLeak.Diplomata.Editor.Helpers;
using LavaLeak.Diplomata.Helpers;
using LavaLeak.Diplomata.Models;
using UnityEditor;
using UnityEngine;
namespace LavaLeak.Diplomata.Editor.Windows
{
public class CharacterEditor : EditorWindow
{
private Vector2 scrollPos = new Vector2(0, 0);
private string characterName = "";
public static Character character;
public enum State
{
None = 0,
Create = 1,
Edit = 2,
Close = 3
}
private static State state;
public static void Init(State state = State.None)
{
CharacterEditor.state = state;
GUIHelper.focusOnStart = true;
CharacterEditor window = (CharacterEditor) GetWindow(typeof(CharacterEditor), false, "Character", true);
if (state == State.Create)
{
window.minSize = new Vector2(GUIHelper.WINDOW_MIN_WIDTH, 100);
}
else
{
window.minSize = new Vector2(GUIHelper.WINDOW_MIN_WIDTH, 390);
}
if (state == State.Close)
{
window.Close();
}
else
{
window.Show();
}
}
public void OnDisable()
{
if (state == State.Edit && character != null)
{
Save();
}
}
public static void OpenCreate()
{
character = null;
Init(State.Create);
}
public static void Edit(Character currentCharacter)
{
character = currentCharacter;
Init(State.Edit);
}
public static void Reset(string characterName)
{
if (character != null)
{
if (character.name == characterName)
{
character = null;
Init(State.Close);
}
}
}
public void OnGUI()
{
GUIHelper.Init();
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
GUILayout.BeginVertical(GUIHelper.windowStyle);
switch (state)
{
case State.None:
Init(State.Close);
break;
case State.Create:
DrawCreateWindow();
break;
case State.Edit:
DrawEditWindow();
break;
}
GUILayout.EndVertical();
EditorGUILayout.EndScrollView();
}
public void DrawCreateWindow()
{
GUILayout.Label("Name: ");
GUI.SetNextControlName("name");
characterName = EditorGUILayout.TextField(characterName);
GUIHelper.Focus("name");
EditorGUILayout.Separator();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Create", GUILayout.Height(GUIHelper.BUTTON_HEIGHT)))
{
Create();
}
if (GUILayout.Button("Cancel", GUILayout.Height(GUIHelper.BUTTON_HEIGHT)))
{
Close();
}
GUILayout.EndHorizontal();
if (focusedWindow != null)
{
if (focusedWindow.ToString() == " (Diplomata.Editor.Windows.CharacterEditor)")
{
if (Event.current.keyCode == KeyCode.Return)
{
Create();
}
}
}
}
public void Create()
{
if (characterName != "")
{
CharactersController.AddCharacter(characterName, Controller.Instance.Options, Controller.Instance.Characters);
}
else
{
Debug.LogError("Character name was empty.");
}
Close();
}
public void DrawEditWindow()
{
GUILayout.Label(string.Format("Name: {0}", character.name));
GUIHelper.Separator();
var description = DictionariesHelper.ContainsKey(character.description, Controller.Instance.Options.currentLanguage);
if (description == null)
{
character.description = ArrayHelper.Add(character.description, new LanguageDictionary(Controller.Instance.Options.currentLanguage, ""));
description = DictionariesHelper.ContainsKey(character.description, Controller.Instance.Options.currentLanguage);
}
GUIHelper.textContent.text = description.value;
var height = GUIHelper.textAreaStyle.CalcHeight(GUIHelper.textContent, position.width - (2 * GUIHelper.MARGIN));
GUILayout.Label("Description: ");
description.value = EditorGUILayout.TextArea(description.value, GUIHelper.textAreaStyle, GUILayout.Height(height));
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
var player = false;
if (Controller.Instance.Options.playerCharacterName == character.name)
{
player = true;
}
player = GUILayout.Toggle(player, " Is player");
if (player)
{
Controller.Instance.Options.playerCharacterName = character.name;
}
EditorGUILayout.EndHorizontal();
if (character.name != Controller.Instance.Options.playerCharacterName)
{
GUIHelper.Separator();
GUILayout.Label("Character attributes (influenceable by): ");
foreach (string attrName in Controller.Instance.Options.attributes)
{
if (character.attributes.Length == 0)
{
character.attributes = ArrayHelper.Add(character.attributes, new AttributeDictionary(attrName));
}
else
{
for (int i = 0; i < character.attributes.Length; i++)
{
if (character.attributes[i].key == attrName)
{
break;
}
else if (i == character.attributes.Length - 1)
{
character.attributes = ArrayHelper.Add(character.attributes, new AttributeDictionary(attrName));
}
}
}
}
for (int i = 0; i < character.attributes.Length; i++)
{
if (ArrayHelper.Contains(Controller.Instance.Options.attributes, character.attributes[i].key))
{
character.attributes[i].value = (byte) EditorGUILayout.Slider(character.attributes[i].key, character.attributes[i].value, 0, 100);
}
}
GUIHelper.Separator();
}
else
{
EditorGUILayout.Separator();
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Save", GUILayout.Height(GUIHelper.BUTTON_HEIGHT)))
{
Save();
Close();
}
if (GUILayout.Button("Close", GUILayout.Height(GUIHelper.BUTTON_HEIGHT)))
{
Save();
Close();
}
GUILayout.EndHorizontal();
}
public void Save()
{
CharactersController.Save(character, Controller.Instance.Options.jsonPrettyPrint);
OptionsController.Save(Controller.Instance.Options, Controller.Instance.Options.jsonPrettyPrint);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapAttributeSchema.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using LdapObjectClassSchema = Novell.Directory.Ldap.LdapObjectClassSchema;
using LdapAttributeSchema = Novell.Directory.Ldap.LdapAttributeSchema;
namespace Novell.Directory.Ldap.Utilclass
{
public class SchemaParser
{
private void InitBlock()
{
usage = LdapAttributeSchema.USER_APPLICATIONS;
qualifiers = new System.Collections.ArrayList();
}
virtual public string RawString
{
get
{
return rawString;
}
set
{
rawString = value;
}
}
virtual public string[] Names
{
get
{
return names;
}
}
virtual public System.Collections.IEnumerator Qualifiers
{
get
{
return new ArrayEnumeration(qualifiers.ToArray());
}
}
virtual public string ID
{
get
{
return id;
}
}
virtual public string Description
{
get
{
return description;
}
}
virtual public string Syntax
{
get
{
return syntax;
}
}
virtual public string Superior
{
get
{
return superior;
}
}
virtual public bool Single
{
get
{
return single;
}
}
virtual public bool Obsolete
{
get
{
return obsolete;
}
}
virtual public string Equality
{
get
{
return equality;
}
}
virtual public string Ordering
{
get
{
return ordering;
}
}
virtual public string Substring
{
get
{
return substring;
}
}
virtual public bool Collective
{
get
{
return collective;
}
}
virtual public bool UserMod
{
get
{
return userMod;
}
}
virtual public int Usage
{
get
{
return usage;
}
}
virtual public int Type
{
get
{
return type;
}
}
virtual public string[] Superiors
{
get
{
return superiors;
}
}
virtual public string[] Required
{
get
{
return required;
}
}
virtual public string[] Optional
{
get
{
return optional;
}
}
virtual public string[] Auxiliary
{
get
{
return auxiliary;
}
}
virtual public string[] Precluded
{
get
{
return precluded;
}
}
virtual public string[] Applies
{
get
{
return applies;
}
}
virtual public string NameForm
{
get
{
return nameForm;
}
}
virtual public string ObjectClass
{
get
{
return nameForm;
}
}
internal string rawString;
internal string[] names = null;
internal string id;
internal string description;
internal string syntax;
internal string superior;
internal string nameForm;
internal string objectClass;
internal string[] superiors;
internal string[] required;
internal string[] optional;
internal string[] auxiliary;
internal string[] precluded;
internal string[] applies;
internal bool single = false;
internal bool obsolete = false;
internal string equality;
internal string ordering;
internal string substring;
internal bool collective = false;
internal bool userMod = true;
internal int usage;
internal int type = -1;
internal int result;
internal System.Collections.ArrayList qualifiers;
public SchemaParser(string aString)
{
InitBlock();
int index;
if ((index = aString.IndexOf((Char)'\\')) != -1)
{
/*
* Unless we escape the slash, StreamTokenizer will interpret the
* single slash and convert it assuming octal values.
* Two successive back slashes are intrepreted as one backslash.
*/
System.Text.StringBuilder newString = new System.Text.StringBuilder(aString.Substring(0, (index) - (0)));
for (int i = index; i < aString.Length; i++)
{
newString.Append(aString[i]);
if (aString[i] == '\\')
{
newString.Append('\\');
}
}
rawString = newString.ToString();
}
else
{
rawString = aString;
}
SchemaTokenCreator st2 = new SchemaTokenCreator(new System.IO.StringReader(rawString));
st2.OrdinaryCharacter('.');
st2.OrdinaryCharacters('0', '9');
st2.OrdinaryCharacter('{');
st2.OrdinaryCharacter('}');
st2.OrdinaryCharacter('_');
st2.OrdinaryCharacter(';');
st2.WordCharacters('.', '9');
st2.WordCharacters('{', '}');
st2.WordCharacters('_', '_');
st2.WordCharacters(';', ';');
//First parse out the OID
try
{
string currName;
if ((int)TokenTypes.EOF != st2.nextToken())
{
if (st2.lastttype == '(')
{
if ((int)TokenTypes.WORD == st2.nextToken())
{
id = st2.StringValue;
}
while ((int)TokenTypes.EOF != st2.nextToken())
{
if (st2.lastttype == (int)TokenTypes.WORD)
{
if (st2.StringValue.ToUpper().Equals("NAME".ToUpper()))
{
if (st2.nextToken() == '\'')
{
names = new string[1];
names[0] = st2.StringValue;
}
else
{
if (st2.lastttype == '(')
{
System.Collections.ArrayList nameList = new System.Collections.ArrayList();
while (st2.nextToken() == '\'')
{
if ((object)st2.StringValue != null)
{
nameList.Add(st2.StringValue);
}
}
if (nameList.Count > 0)
{
names = new string[nameList.Count];
SupportClass.ArrayListSupport.ToArray(nameList, names);
}
}
}
continue;
}
if (st2.StringValue.ToUpper().Equals("DESC".ToUpper()))
{
if (st2.nextToken() == '\'')
{
description = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SYNTAX".ToUpper()))
{
result = st2.nextToken();
if ((result == (int)TokenTypes.WORD) || (result == '\''))
//Test for non-standard schema
{
syntax = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("EQUALITY".ToUpper()))
{
if (st2.nextToken() == (int)TokenTypes.WORD)
{
equality = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("ORDERING".ToUpper()))
{
if (st2.nextToken() == (int)TokenTypes.WORD)
{
ordering = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SUBSTR".ToUpper()))
{
if (st2.nextToken() == (int)TokenTypes.WORD)
{
substring = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("FORM".ToUpper()))
{
if (st2.nextToken() == (int)TokenTypes.WORD)
{
nameForm = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("OC".ToUpper()))
{
if (st2.nextToken() == (int)TokenTypes.WORD)
{
objectClass = st2.StringValue;
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SUP".ToUpper()))
{
System.Collections.ArrayList values = new System.Collections.ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
superior = st2.StringValue;
}
if (values.Count > 0)
{
superiors = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, superiors);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("SINGLE-VALUE".ToUpper()))
{
single = true;
continue;
}
if (st2.StringValue.ToUpper().Equals("OBSOLETE".ToUpper()))
{
obsolete = true;
continue;
}
if (st2.StringValue.ToUpper().Equals("COLLECTIVE".ToUpper()))
{
collective = true;
continue;
}
if (st2.StringValue.ToUpper().Equals("NO-USER-MODIFICATION".ToUpper()))
{
userMod = false;
continue;
}
if (st2.StringValue.ToUpper().Equals("MUST".ToUpper()))
{
System.Collections.ArrayList values = new System.Collections.ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
required = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, required);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("MAY".ToUpper()))
{
System.Collections.ArrayList values = new System.Collections.ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
optional = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, optional);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("NOT".ToUpper()))
{
System.Collections.ArrayList values = new System.Collections.ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
precluded = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, precluded);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("AUX".ToUpper()))
{
System.Collections.ArrayList values = new System.Collections.ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
auxiliary = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, auxiliary);
}
continue;
}
if (st2.StringValue.ToUpper().Equals("ABSTRACT".ToUpper()))
{
type = LdapObjectClassSchema.ABSTRACT;
continue;
}
if (st2.StringValue.ToUpper().Equals("STRUCTURAL".ToUpper()))
{
type = LdapObjectClassSchema.STRUCTURAL;
continue;
}
if (st2.StringValue.ToUpper().Equals("AUXILIARY".ToUpper()))
{
type = LdapObjectClassSchema.AUXILIARY;
continue;
}
if (st2.StringValue.ToUpper().Equals("USAGE".ToUpper()))
{
if (st2.nextToken() == (int)TokenTypes.WORD)
{
currName = st2.StringValue;
if (currName.ToUpper().Equals("directoryOperation".ToUpper()))
{
usage = LdapAttributeSchema.DIRECTORY_OPERATION;
}
else if (currName.ToUpper().Equals("distributedOperation".ToUpper()))
{
usage = LdapAttributeSchema.DISTRIBUTED_OPERATION;
}
else if (currName.ToUpper().Equals("dSAOperation".ToUpper()))
{
usage = LdapAttributeSchema.DSA_OPERATION;
}
else if (currName.ToUpper().Equals("userApplications".ToUpper()))
{
usage = LdapAttributeSchema.USER_APPLICATIONS;
}
}
continue;
}
if (st2.StringValue.ToUpper().Equals("APPLIES".ToUpper()))
{
System.Collections.ArrayList values = new System.Collections.ArrayList();
st2.nextToken();
if (st2.lastttype == '(')
{
st2.nextToken();
while (st2.lastttype != ')')
{
if (st2.lastttype != '$')
{
values.Add(st2.StringValue);
}
st2.nextToken();
}
}
else
{
values.Add(st2.StringValue);
}
if (values.Count > 0)
{
applies = new string[values.Count];
SupportClass.ArrayListSupport.ToArray(values, applies);
}
continue;
}
currName = st2.StringValue;
AttributeQualifier q = parseQualifier(st2, currName);
if (q != null)
{
qualifiers.Add(q);
}
continue;
}
}
}
}
}
catch (System.IO.IOException e)
{
throw e;
}
}
private AttributeQualifier parseQualifier(SchemaTokenCreator st, string name)
{
System.Collections.ArrayList values = new System.Collections.ArrayList(5);
try
{
if (st.nextToken() == '\'')
{
values.Add(st.StringValue);
}
else
{
if (st.lastttype == '(')
{
while (st.nextToken() == '\'')
{
values.Add(st.StringValue);
}
}
}
}
catch (System.IO.IOException e)
{
throw e;
}
string[] valArray = new string[values.Count];
valArray = (string[])SupportClass.ArrayListSupport.ToArray(values, valArray);
return new AttributeQualifier(name, valArray);
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using AspNetCore.Identity.MongoDB;
using IdentitySample.Models;
using IdentitySample.Models.ManageViewModels;
using IdentitySample.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace IdentitySamples.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<MongoIdentityUser> _userManager;
private readonly SignInManager<MongoIdentityUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<MongoIdentityUser> userManager,
SignInManager<MongoIdentityUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user),
AuthenticatorKey = await _userManager.GetAuthenticatorKeyAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/ResetAuthenticatorKey
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetAuthenticatorKey()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.ResetAuthenticatorKeyAsync(user);
_logger.LogInformation(1, "User reset authenticator key.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/GenerateRecoveryCode
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GenerateRecoveryCode()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var codes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 5);
_logger.LogInformation(1, "User generated new recovery code.");
return View("DisplayRecoveryCodes", new DisplayRecoveryCodesViewModel { Codes = codes });
}
return View("Error");
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// GET: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync();
var otherLogins = schemes.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<MongoIdentityUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
using System;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.View;
using Android.Support.V4.Widget;
using Android.Util;
using Android.Views;
using Android.Views.Accessibility;
using Java.Interop;
namespace Cheesebaron.SlidingUpPanel
{
public class SlidingUpPanelLayout : ViewGroup
{
private new const string Tag = "SlidingUpPanelLayout";
private const int DefaultPanelHeight = 68;
private const int DefaultShadowHeight = 4;
private const int DefaultMinFlingVelocity = 400;
private static readonly Color DefaultFadeColor = new Color(0, 0, 0, 99);
private static readonly int[] DefaultAttrs = { Android.Resource.Attribute.Gravity };
private readonly int _minFlingVelocity = DefaultMinFlingVelocity;
private Color _coveredFadeColor = DefaultFadeColor;
private readonly Paint _coveredFadePaint = new Paint();
private int _panelHeight = -1;
private readonly int _shadowHeight = -1;
private readonly bool _isSlidingUp;
private bool _canSlide;
private View _dragView;
private readonly int _dragViewResId = -1;
private View _slideableView;
private SlideState _slideState = SlideState.Collapsed;
private float _slideOffset;
private int _slideRange;
private bool _isUnableToDrag;
private readonly int _scrollTouchSlop;
private float _initialMotionX;
private float _initialMotionY;
private float _anchorPoint;
private readonly ViewDragHelper _dragHelper;
private bool _firstLayout = true;
private readonly Rect _tmpRect = new Rect();
public event SlidingUpPanelSlideEventHandler PanelSlide;
public event SlidingUpPanelEventHandler PanelCollapsed;
public event SlidingUpPanelEventHandler PanelExpanded;
public event SlidingUpPanelEventHandler PanelAnchored;
public bool IsExpanded
{
get { return _slideState == SlideState.Expanded; }
}
public bool IsAnchored
{
get { return _slideState == SlideState.Anchored; }
}
public bool IsSlideable
{
get { return _canSlide; }
}
public Color CoveredFadeColor
{
get { return _coveredFadeColor; }
set
{
_coveredFadeColor = value;
Invalidate();
}
}
public int PanelHeight
{
get { return _panelHeight; }
set
{
_panelHeight = value;
RequestLayout();
}
}
public View DragView
{
get { return _dragView; }
set { _dragView = value; }
}
public float AnchorPoint
{
get { return _anchorPoint; }
set
{
if (value > 0 && value < 1)
_anchorPoint = value;
}
}
public Drawable ShadowDrawable { get; set; }
public bool SlidingEnabled { get; set; }
public bool IsUsingDragViewTouchEvents { get; set; }
private int SlidingTop
{
get
{
if (_slideableView != null)
{
return _isSlidingUp
? MeasuredHeight - PaddingBottom - _slideableView.MeasuredHeight
: MeasuredHeight - PaddingBottom - (_slideableView.MeasuredHeight * 2);
}
return MeasuredHeight - PaddingBottom;
}
}
public bool PaneVisible
{
get
{
if (ChildCount < 2)
return false;
var slidingPane = GetChildAt(1);
return slidingPane.Visibility == ViewStates.Visible;
}
}
public SlidingUpPanelLayout(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer) { }
public SlidingUpPanelLayout(Context context)
: this(context, null) { }
public SlidingUpPanelLayout(Context context, IAttributeSet attrs)
: this(context, attrs, 0) { }
public SlidingUpPanelLayout(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
if (attrs != null)
{
var defAttrs = context.ObtainStyledAttributes(attrs, DefaultAttrs);
if (defAttrs.Length() > 0)
{
var gravity = defAttrs.GetInt(0, (int)GravityFlags.NoGravity);
var gravityFlag = (GravityFlags) gravity;
if (gravityFlag != GravityFlags.Top && gravityFlag != GravityFlags.Bottom)
throw new ArgumentException("layout_gravity must be set to either top or bottom");
_isSlidingUp = gravityFlag == GravityFlags.Bottom;
}
defAttrs.Recycle();
var ta = context.ObtainStyledAttributes(attrs, Resource.Styleable.SlidingUpPanelLayout);
if (ta.Length() > 0)
{
_panelHeight = ta.GetDimensionPixelSize(Resource.Styleable.SlidingUpPanelLayout_collapsedHeight, -1);
_shadowHeight = ta.GetDimensionPixelSize(Resource.Styleable.SlidingUpPanelLayout_shadowHeight, -1);
_minFlingVelocity = ta.GetInt(Resource.Styleable.SlidingUpPanelLayout_flingVelocity,
DefaultMinFlingVelocity);
_coveredFadeColor = ta.GetColor(Resource.Styleable.SlidingUpPanelLayout_fadeColor, DefaultFadeColor);
_dragViewResId = ta.GetResourceId(Resource.Styleable.SlidingUpPanelLayout_dragView, -1);
}
ta.Recycle();
}
var density = context.Resources.DisplayMetrics.Density;
if (_panelHeight == -1)
_panelHeight = (int) (DefaultPanelHeight * density + 0.5f);
if (_shadowHeight == -1)
_shadowHeight = (int) (DefaultShadowHeight * density + 0.5f);
SetWillNotDraw(false);
_dragHelper = ViewDragHelper.Create(this, 0.5f, new DragHelperCallback(this));
_dragHelper.MinVelocity = _minFlingVelocity * density;
_canSlide = true;
SlidingEnabled = true;
var vc = ViewConfiguration.Get(context);
_scrollTouchSlop = vc.ScaledTouchSlop;
}
protected override void OnFinishInflate()
{
base.OnFinishInflate();
if (_dragViewResId != -1)
_dragView = FindViewById(_dragViewResId);
}
private void OnPanelSlide(View panel)
{
if (PanelSlide != null)
PanelSlide(this, new SlidingUpPanelSlideEventArgs {Panel = panel, SlideOffset = _slideOffset});
}
private void OnPanelCollapsed(View panel)
{
if (PanelCollapsed != null)
PanelCollapsed(this, new SlidingUpPanelEventArgs { Panel = panel });
SendAccessibilityEvent(EventTypes.WindowStateChanged);
}
private void OnPanelAnchored(View panel)
{
if (PanelAnchored != null)
PanelAnchored(this, new SlidingUpPanelEventArgs { Panel = panel });
SendAccessibilityEvent(EventTypes.WindowStateChanged);
}
private void OnPanelExpanded(View panel)
{
if (PanelExpanded != null)
PanelExpanded(this, new SlidingUpPanelEventArgs { Panel = panel });
SendAccessibilityEvent(EventTypes.WindowStateChanged);
}
private void UpdateObscuredViewVisibility()
{
if (ChildCount == 0) return;
var leftBound = PaddingLeft;
var rightBound = Width - PaddingLeft;
var topBound = PaddingTop;
var bottomBound = Height - PaddingBottom;
int left;
int right;
int top;
int bottom;
if (_slideableView != null && HasOpaqueBackground(_slideableView))
{
left = _slideableView.Left;
right = _slideableView.Right;
top = _slideableView.Top;
bottom = _slideableView.Bottom;
}
else
left = right = top = bottom = 0;
var child = GetChildAt(0);
var clampedChildLeft = Math.Max(leftBound, child.Left);
var clampedChildTop = Math.Max(topBound, child.Top);
var clampedChildRight = Math.Max(rightBound, child.Right);
var clampedChildBottom = Math.Max(bottomBound, child.Bottom);
ViewStates vis;
if (clampedChildLeft >= left && clampedChildTop >= top &&
clampedChildRight <= right && clampedChildBottom <= bottom)
vis = ViewStates.Invisible;
else
vis = ViewStates.Visible;
child.Visibility = vis;
}
private void SetAllChildrenVisible()
{
for (var i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
if (child.Visibility == ViewStates.Invisible)
child.Visibility = ViewStates.Visible;
}
}
private static bool HasOpaqueBackground(View view)
{
var bg = view.Background;
if (bg != null)
return bg.Opacity == (int) Format.Opaque;
return false;
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
_firstLayout = true;
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
_firstLayout = true;
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
var widthMode = MeasureSpec.GetMode(widthMeasureSpec);
var widthSize = MeasureSpec.GetSize(widthMeasureSpec);
var heightMode = MeasureSpec.GetMode(heightMeasureSpec);
var heightSize = MeasureSpec.GetSize(heightMeasureSpec);
if (widthMode != MeasureSpecMode.Exactly)
throw new InvalidOperationException("Width must have an exact value or match_parent");
if (heightMode != MeasureSpecMode.Exactly)
throw new InvalidOperationException("Height must have an exact value or match_parent");
var layoutHeight = heightSize - PaddingTop - PaddingBottom;
var panelHeight = _panelHeight;
if (ChildCount > 2)
Log.Error(Tag, "OnMeasure: More than two child views are not supported.");
else
panelHeight = 0;
_slideableView = null;
_canSlide = false;
for (var i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
var lp = (LayoutParams) child.LayoutParameters;
var height = layoutHeight;
if (child.Visibility == ViewStates.Gone)
{
lp.DimWhenOffset = false;
continue;
}
if (i == 1)
{
lp.Slideable = true;
lp.DimWhenOffset = true;
_slideableView = child;
_canSlide = true;
}
else
{
height -= panelHeight;
}
int childWidthSpec;
if (lp.Width == ViewGroup.LayoutParams.WrapContent)
childWidthSpec = MeasureSpec.MakeMeasureSpec(widthSize, MeasureSpecMode.AtMost);
else if (lp.Width == ViewGroup.LayoutParams.MatchParent)
childWidthSpec = MeasureSpec.MakeMeasureSpec(widthSize, MeasureSpecMode.Exactly);
else
childWidthSpec = MeasureSpec.MakeMeasureSpec(lp.Width, MeasureSpecMode.Exactly);
int childHeightSpec;
if (lp.Height == ViewGroup.LayoutParams.WrapContent)
childHeightSpec = MeasureSpec.MakeMeasureSpec(height, MeasureSpecMode.AtMost);
else if (lp.Height == ViewGroup.LayoutParams.MatchParent)
childHeightSpec = MeasureSpec.MakeMeasureSpec(height, MeasureSpecMode.Exactly);
else
childHeightSpec = MeasureSpec.MakeMeasureSpec(lp.Height, MeasureSpecMode.Exactly);
child.Measure(childWidthSpec, childHeightSpec);
}
SetMeasuredDimension(widthSize, heightSize);
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
if (_firstLayout)
{
switch (_slideState)
{
case SlideState.Expanded:
_slideOffset = _canSlide ? 0.0f : 1.0f;
break;
case SlideState.Anchored:
_slideOffset = _canSlide ? _anchorPoint : 1.0f;
break;
case SlideState.Collapsed:
_slideOffset = 1.0f;
break;
}
}
for (var i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
if (child.Visibility == ViewStates.Gone)
continue;
var lp = (LayoutParams) child.LayoutParameters;
var childHeight = child.MeasuredHeight;
if (lp.Slideable)
_slideRange = childHeight - _panelHeight;
int childTop;
if (_isSlidingUp)
childTop = lp.Slideable ? SlidingTop + (int) (_slideRange * _slideOffset) : PaddingTop;
else
childTop = lp.Slideable ? SlidingTop - (int)(_slideRange * _slideOffset) : PaddingTop + PanelHeight;
var childBottom = childTop + childHeight;
var childLeft = PaddingLeft;
var childRight = childLeft + child.MeasuredWidth;
child.Layout(childLeft, childTop, childRight, childBottom);
}
if (_firstLayout)
UpdateObscuredViewVisibility();
_firstLayout = false;
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged(w, h, oldw, oldh);
if (h != oldh)
_firstLayout = true;
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
var action = MotionEventCompat.GetActionMasked(ev);
if (!_canSlide || !SlidingEnabled || (_isUnableToDrag && action != (int) MotionEventActions.Down))
{
_dragHelper.Cancel();
return base.OnInterceptTouchEvent(ev);
}
if (action == (int) MotionEventActions.Cancel || action == (int) MotionEventActions.Up)
{
_dragHelper.Cancel();
return false;
}
var x = ev.GetX();
var y = ev.GetY();
var interceptTap = false;
switch (action)
{
case (int)MotionEventActions.Down:
_isUnableToDrag = false;
_initialMotionX = x;
_initialMotionY = y;
if (IsDragViewUnder((int) x, (int) y) && !IsUsingDragViewTouchEvents)
interceptTap = true;
break;
case (int)MotionEventActions.Move:
var adx = Math.Abs(x - _initialMotionX);
var ady = Math.Abs(y - _initialMotionY);
var dragSlop = _dragHelper.TouchSlop;
if (IsUsingDragViewTouchEvents)
{
if (adx > _scrollTouchSlop && ady < _scrollTouchSlop)
return base.OnInterceptTouchEvent(ev);
if (ady > _scrollTouchSlop)
interceptTap = IsDragViewUnder((int) x, (int) y);
}
if ((ady > dragSlop && adx > ady) || !IsDragViewUnder((int) x, (int) y))
{
_dragHelper.Cancel();
_isUnableToDrag = true;
return false;
}
break;
}
var interceptForDrag = _dragHelper.ShouldInterceptTouchEvent(ev);
return interceptForDrag || interceptTap;
}
public override bool OnTouchEvent(MotionEvent ev)
{
if (!_canSlide || !SlidingEnabled)
return base.OnTouchEvent(ev);
_dragHelper.ProcessTouchEvent(ev);
var action = (int)ev.Action;
switch (action & MotionEventCompat.ActionMask)
{
case (int)MotionEventActions.Down:
{
var x = ev.GetX();
var y = ev.GetY();
_initialMotionX = x;
_initialMotionY = y;
break;
}
case (int)MotionEventActions.Up:
{
var x = ev.GetX();
var y = ev.GetY();
var dx = x - _initialMotionX;
var dy = y - _initialMotionY;
var slop = _dragHelper.TouchSlop;
var dragView = _dragView ?? _slideableView;
if (dx * dx + dy * dy < slop * slop && IsDragViewUnder((int)x, (int)y))
{
dragView.PlaySoundEffect(SoundEffects.Click);
if (!IsExpanded && !IsAnchored)
ExpandPane(_anchorPoint);
else
CollapsePane();
}
break;
}
}
return true;
}
private bool IsDragViewUnder(int x, int y)
{
var dragView = _dragView ?? _slideableView;
if (dragView == null) return false;
var viewLocation = new int[2];
dragView.GetLocationOnScreen(viewLocation);
var parentLocation = new int[2];
GetLocationOnScreen(parentLocation);
var screenX = parentLocation[0] + x;
var screenY = parentLocation[1] + y;
return screenX >= viewLocation[0] && screenX < viewLocation[0] + dragView.Width &&
screenY >= viewLocation[1] && screenY < viewLocation[1] + dragView.Height;
}
public bool CollapsePane()
{
if (_firstLayout || SmoothSlideTo(1.0f))
return true;
return false;
}
public bool ExpandPane()
{
return ExpandPane(0);
}
public bool ExpandPane(float slideOffset)
{
if (!PaneVisible)
ShowPane();
return _firstLayout || SmoothSlideTo(slideOffset);
}
public void ShowPane()
{
if (ChildCount < 2) return;
var slidingPane = GetChildAt(1);
slidingPane.Visibility = ViewStates.Visible;
RequestLayout();
}
public void HidePane()
{
if (_slideableView == null) return;
_slideableView.Visibility = ViewStates.Gone;
RequestLayout();
}
private void OnPanelDragged(int newTop)
{
_slideOffset = _isSlidingUp
? (float) (newTop - SlidingTop) / _slideRange
: (float) (SlidingTop - newTop) / _slideRange;
OnPanelSlide(_slideableView);
}
protected override bool DrawChild(Canvas canvas, View child, long drawingTime)
{
var lp = (LayoutParams) child.LayoutParameters;
var save = canvas.Save(SaveFlags.Clip);
var drawScrim = false;
if (_canSlide && !lp.Slideable && _slideableView != null)
{
canvas.GetClipBounds(_tmpRect);
if (_isSlidingUp)
_tmpRect.Bottom = Math.Min(_tmpRect.Bottom, _slideableView.Top);
else
_tmpRect.Top = Math.Max(_tmpRect.Top, _slideableView.Bottom);
canvas.ClipRect(_tmpRect);
if (_slideOffset < 1)
drawScrim = true;
}
var result = base.DrawChild(canvas, child, drawingTime);
canvas.RestoreToCount(save);
if (drawScrim)
{
var baseAlpha = (_coveredFadeColor.ToArgb() & 0xff000000) >> 24;
var imag = (int) (baseAlpha * (1 - _slideOffset));
var color = imag << 24 | (_coveredFadeColor.ToArgb() & 0xffffff);
_coveredFadePaint.Color = new Color(color);
canvas.DrawRect(_tmpRect, _coveredFadePaint);
}
return result;
}
private bool SmoothSlideTo(float slideOffset)
{
if (!_canSlide) return false;
var y = _isSlidingUp
? (int) (SlidingTop + slideOffset * _slideRange)
: (int) (SlidingTop - slideOffset * _slideRange);
if (!_dragHelper.SmoothSlideViewTo(_slideableView, _slideableView.Left, y)) return false;
SetAllChildrenVisible();
ViewCompat.PostInvalidateOnAnimation(this);
return true;
}
public override void ComputeScroll()
{
if (!_dragHelper.ContinueSettling(true)) return;
if (!_canSlide)
{
_dragHelper.Abort();
return;
}
ViewCompat.PostInvalidateOnAnimation(this);
}
public override void Draw(Canvas canvas)
{
base.Draw(canvas);
if (_slideableView == null) return;
if (ShadowDrawable == null) return;
var right = _slideableView.Right;
var left = _slideableView.Left;
int top;
int bottom;
if (_isSlidingUp)
{
top = _slideableView.Top - _shadowHeight;
bottom = _slideableView.Top;
}
else
{
top = _slideableView.Bottom;
bottom = _slideableView.Bottom + _shadowHeight;
}
ShadowDrawable.SetBounds(left, top, right, bottom);
ShadowDrawable.Draw(canvas);
}
protected bool CanScroll(View view, bool checkV, int dx, int x, int y)
{
var viewGroup = view as ViewGroup;
if (viewGroup == null) return checkV && ViewCompat.CanScrollHorizontally(view, -dx);
var scrollX = viewGroup.ScrollX;
var scrollY = viewGroup.ScrollY;
var count = viewGroup.ChildCount;
for (var i = count - 1; i >= 0; i--)
{
var child = viewGroup.GetChildAt(i);
if (x + scrollX >= child.Left && x + scrollX < child.Right &&
y + scrollY >= child.Top && y + scrollY < child.Bottom &&
CanScroll(child, true, dx, x + scrollX - child.Left, y + scrollY - child.Top))
return true;
}
return checkV && ViewCompat.CanScrollHorizontally(view, -dx);
}
protected override ViewGroup.LayoutParams GenerateDefaultLayoutParams()
{
return new LayoutParams();
}
protected override ViewGroup.LayoutParams GenerateLayoutParams(ViewGroup.LayoutParams p)
{
var param = p as MarginLayoutParams;
return param != null ? new LayoutParams(param) : new LayoutParams(p);
}
protected override bool CheckLayoutParams(ViewGroup.LayoutParams p)
{
var param = p as LayoutParams;
return param != null && base.CheckLayoutParams(p);
}
public override ViewGroup.LayoutParams GenerateLayoutParams(IAttributeSet attrs)
{
return new LayoutParams(Context, attrs);
}
public new class LayoutParams : MarginLayoutParams
{
private static readonly int[] Attrs = {
Android.Resource.Attribute.LayoutWidth
};
public bool Slideable { get; set; }
public bool DimWhenOffset { get; set; }
public Paint DimPaint { get; set; }
public LayoutParams()
: base(MatchParent, MatchParent) { }
public LayoutParams(int width, int height)
: base(width, height) { }
public LayoutParams(ViewGroup.LayoutParams source)
: base(source) { }
public LayoutParams(MarginLayoutParams source)
: base(source) { }
public LayoutParams(LayoutParams source)
: base(source) { }
public LayoutParams(Context c, IAttributeSet attrs)
: base(c, attrs)
{
var a = c.ObtainStyledAttributes(attrs, Attrs);
a.Recycle();
}
}
private class DragHelperCallback : ViewDragHelper.Callback
{
//This class is a bit nasty, as C# does not allow calling variables directly
//like stupid Java does.
private readonly SlidingUpPanelLayout _panelLayout;
public DragHelperCallback(SlidingUpPanelLayout layout)
{
_panelLayout = layout;
}
public override bool TryCaptureView(View child, int pointerId)
{
return !_panelLayout._isUnableToDrag && ((LayoutParams) child.LayoutParameters).Slideable;
}
public override void OnViewDragStateChanged(int state)
{
var anchoredTop = (int) (_panelLayout._anchorPoint * _panelLayout._slideRange);
if (_panelLayout._dragHelper.ViewDragState == ViewDragHelper.StateIdle)
{
if (_panelLayout._slideOffset == 0)
{
if (_panelLayout._slideState != SlideState.Expanded)
{
_panelLayout.UpdateObscuredViewVisibility();
_panelLayout.OnPanelExpanded(_panelLayout._slideableView);
_panelLayout._slideState = SlideState.Expanded;
}
}
else if (_panelLayout._slideOffset == (float) anchoredTop / _panelLayout._slideRange)
{
if (_panelLayout._slideState != SlideState.Anchored)
{
_panelLayout.UpdateObscuredViewVisibility();
_panelLayout.OnPanelAnchored(_panelLayout._slideableView);
_panelLayout._slideState = SlideState.Anchored;
}
}
else if (_panelLayout._slideState != SlideState.Collapsed)
{
_panelLayout.OnPanelCollapsed(_panelLayout._slideableView);
_panelLayout._slideState = SlideState.Collapsed;
}
}
}
public override void OnViewCaptured(View capturedChild, int activePointerId)
{
_panelLayout.SetAllChildrenVisible();
}
public override void OnViewPositionChanged(View changedView, int left, int top, int dx, int dy)
{
_panelLayout.OnPanelDragged(top);
_panelLayout.Invalidate();
}
public override void OnViewReleased(View releasedChild, float xvel, float yvel)
{
var top = _panelLayout._isSlidingUp
? _panelLayout.SlidingTop
: _panelLayout.SlidingTop - _panelLayout._slideRange;
if (_panelLayout._anchorPoint != 0)
{
int anchoredTop;
float anchorOffset;
if (_panelLayout._isSlidingUp)
{
anchoredTop = (int) (_panelLayout._anchorPoint * _panelLayout._slideRange);
anchorOffset = (float) anchoredTop / _panelLayout._slideRange;
}
else
{
anchoredTop = _panelLayout._panelHeight -
(int) (_panelLayout._anchorPoint * _panelLayout._slideRange);
anchorOffset = (float)(_panelLayout._panelHeight - anchoredTop) / _panelLayout._slideRange;
}
if (yvel > 0 || (yvel == 0 && _panelLayout._slideOffset >= (1f + anchorOffset) / 2))
top += _panelLayout._slideRange;
else if (yvel == 0 && _panelLayout._slideOffset < (1f + anchorOffset) / 2 &&
_panelLayout._slideOffset >= anchorOffset / 2)
top += (int) (_panelLayout._slideRange * _panelLayout._anchorPoint);
} else if (yvel > 0 || (yvel == 0 && _panelLayout._slideOffset > 0.5f))
top += _panelLayout._slideRange;
_panelLayout._dragHelper.SettleCapturedViewAt(releasedChild.Left, top);
_panelLayout.Invalidate();
}
public override int GetViewVerticalDragRange(View child)
{
return _panelLayout._slideRange;
}
public override int ClampViewPositionVertical(View child, int top, int dy)
{
int topBound;
int bottomBound;
if (_panelLayout._isSlidingUp)
{
topBound = _panelLayout.SlidingTop;
bottomBound = topBound + _panelLayout._slideRange;
}
else
{
bottomBound = _panelLayout.PaddingTop;
topBound = bottomBound - _panelLayout._slideRange;
}
return Math.Min(Math.Max(top, topBound), bottomBound);
}
}
protected override IParcelable OnSaveInstanceState()
{
var superState = base.OnSaveInstanceState();
var savedState = new SavedState(superState, _slideState);
return savedState;
}
protected override void OnRestoreInstanceState(IParcelable state)
{
try
{
var savedState = (SavedState) state;
base.OnRestoreInstanceState(savedState.SuperState);
_slideState = savedState.State;
}
catch
{
base.OnRestoreInstanceState(state);
}
}
public class SavedState : BaseSavedState
{
public SlideState State { get; private set; }
public SavedState(IParcelable superState, SlideState item)
: base(superState)
{
State = item;
}
public SavedState(Parcel parcel)
: base(parcel)
{
try
{
State = (SlideState) parcel.ReadInt();
}
catch
{
State = SlideState.Collapsed;
}
}
public override void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
base.WriteToParcel(dest, flags);
dest.WriteInt((int)State);
}
[ExportField("CREATOR")]
static SavedStateCreator InitializeCreator()
{
return new SavedStateCreator();
}
class SavedStateCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
return new SavedState(source);
}
public Java.Lang.Object[] NewArray(int size)
{
return new SavedState[size];
}
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Ruzzie.Common.Numerics;
using Ruzzie.Common.Threading;
//since volatile is used with interlocking, disable the warning.
#pragma warning disable 420
namespace Ruzzie.Common.Collections
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IConcurrentCircularOverwriteBuffer<T>
{
/// <summary>
/// Copies current buffer to target array starting at the specified destination array index.
/// </summary>
/// <param name="array">The one-dimensional array that is the destination of the elements copied from the current buffer.</param>
/// <param name="index">A 32-bit integer that represents the index in <paramref name="array" /> at which copying begins.</param>
/// <remarks>
/// This method uses the <see cref="Array.CopyTo(Array,int)" /> method to copy the current buffer to destination
/// array. (this is a shallow copy)
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="array" /> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index" /> is less than the lower bound of
/// <paramref name="array" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="array" /> is multidimensional.-or-The number of elements in the
/// source array is greater than the available number of elements from <paramref name="index" /> to the end of the
/// destination <paramref name="array" />.
/// </exception>
/// <exception cref="ArrayTypeMismatchException">
/// The type of the source <see cref="T:System.Array" /> cannot be cast
/// automatically to the type of the destination <paramref name="array" />.
/// </exception>
/// <exception cref="RankException">The source array is multidimensional.</exception>
/// <exception cref="InvalidCastException">
/// At least one element in the source <see cref="T:System.Array" /> cannot be cast
/// to the type of destination <paramref name="array" />.
/// </exception>
void CopyTo(in Array array, in int index);
/// <summary>
/// Writes a value to the buffer.
/// </summary>
/// <param name="value">The value to write</param>
void WriteNext(in T value);
/// <summary>
/// Reads the next value from the buffer.
/// </summary>
/// <returns>The value read. if no value is present an <see cref="InvalidOperationException" /> will be thrown.</returns>
/// <exception cref="System.InvalidOperationException">Error there is no next value.</exception>
/// <exception cref="InvalidOperationException">There is no next value.</exception>
T ReadNext();
/// <summary>
/// Reads the next value from the buffer.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>true if a value could be read. If no next value is present false will be returned.</returns>
bool ReadNext(out T value);
/// <summary>
/// Gets the capacity in number of items of the buffer.
/// </summary>
/// <value>
/// The capacity.
/// </value>
int Capacity { get; }
}
/// <inheritdoc />
/// <summary>
/// Circular buffer that overwrites values when the capacity is reached.
/// This buffer is thread-safe when <b>not</b> using an many readers many writers strategy.
/// </summary>
/// <typeparam name="T">The type of the values to buffer.</typeparam>
public class ConcurrentCircularOverwriteBuffer<T> : IConcurrentCircularOverwriteBuffer<T>
{
private const int DefaultBufferSize = 1024;
private readonly int _capacity;
private readonly T[] _buffer;
private readonly long _indexMask;
private VolatileLong _writeHeader;
private VolatileLong _readHeader;
/// <summary>
/// Returns the number of values in the buffer.
/// </summary>
/// <value>
/// The current item count of the buffer.
/// </value>
public long Count
{
get
{
unchecked
{
long itemCount = (_writeHeader.CompilerFencedValue + 1) - (_readHeader.CompilerFencedValue + 1);
if (itemCount == 0)
{
return 0;
}
long remainder = (itemCount % _capacity);
if (remainder > 0)
{
return itemCount / _capacity + remainder;
}
return _capacity;
}
}
}
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:Ruzzie.Common.Collections.ConcurrentCircularOverwriteBuffer`1" /> class. With default buffer
/// size of <see cref="F:Ruzzie.Common.Collections.ConcurrentCircularOverwriteBuffer`1.DefaultBufferSize" />.
/// </summary>
[SuppressMessage("ReSharper", "RedundantArgumentDefaultValue", Justification = "Required for CA1026")]
public ConcurrentCircularOverwriteBuffer() : this(DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentCircularOverwriteBuffer{T}" /> class.
/// </summary>
/// <param name="capacity">
/// The desired size. Internally this will always be set to a power of 2 for performance. Default is
/// <see cref="DefaultBufferSize" />
/// </param>
/// <exception cref="ArgumentOutOfRangeException">size;Size has to be greater or equal to 2.</exception>
public ConcurrentCircularOverwriteBuffer(in int capacity = DefaultBufferSize)
{
if (capacity < 2)
{
throw new ArgumentOutOfRangeException(nameof(capacity), "Size has to be greater or equal to 2.");
}
_capacity = capacity.FindNearestPowerOfTwoEqualOrGreaterThan();
_buffer = new T[_capacity];
_indexMask = _capacity - 1;
_writeHeader = 0;
_readHeader = 0;
}
/// <inheritdoc />
/// <summary>
/// Copies current buffer to target array starting at the specified destination array index.
/// </summary>
/// <param name="array">The one-dimensional array that is the destination of the elements copied from the current buffer.</param>
/// <param name="index">A 32-bit integer that represents the index in <paramref name="array" /> at which copying begins.</param>
/// <remarks>
/// This method uses the <see cref="M:System.Array.CopyTo(System.Array,System.Int32)" /> method to copy the current buffer to destination
/// array. (this is a shallow copy)
/// </remarks>
/// <exception cref="T:System.ArgumentNullException"><paramref name="array" /> is null.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> is less than the lower bound of
/// <paramref name="array" />.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="array" /> is multidimensional.-or-The number of elements in the
/// source array is greater than the available number of elements from <paramref name="index" /> to the end of the
/// destination <paramref name="array" />.
/// </exception>
/// <exception cref="T:System.ArrayTypeMismatchException">
/// The type of the source <see cref="T:System.Array" /> cannot be cast
/// automatically to the type of the destination <paramref name="array" />.
/// </exception>
/// <exception cref="T:System.RankException">The source array is multidimensional.</exception>
/// <exception cref="T:System.InvalidCastException">
/// At least one element in the source <see cref="T:System.Array" /> cannot be cast
/// to the type of destination <paramref name="array" />.
/// </exception>
public void CopyTo(in Array array, in int index)
{
_buffer.CopyTo(array, index);
}
/// <summary>
/// Writes a value to the buffer.
/// </summary>
/// <param name="value">The value to write</param>
public void WriteNext(in T value)
{
long nextWriteIndex = _writeHeader.AtomicIncrement();
long currentWriteIndex = nextWriteIndex - 1;
// Interlocked.Exchange(ref _buffer[currentWriteIndex & _indexMask], value);
_buffer[currentWriteIndex & _indexMask] = value;
}
/// <inheritdoc />
/// <summary>
/// Reads the next value from the buffer.
/// </summary>
/// <returns>The value read. if no value is present an <see cref="T:System.InvalidOperationException" /> will be thrown.</returns>
/// <exception cref="T:System.InvalidOperationException">Error there is no next value.</exception>
/// <exception cref="T:System.InvalidOperationException">There is no next value.</exception>
public T ReadNext()
{
if (ReadNext(out var value))
{
return value;
}
throw new InvalidOperationException("Error there is no next value.");
}
/// <inheritdoc />
/// <summary>
/// Reads the next value from the buffer.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>true if a value could be read. If no next value is present false will be returned.</returns>
public bool ReadNext(out T value)
{
if (!HasNext(_readHeader.ReadUnfenced(), _writeHeader.ReadUnfenced()))
{
value = default!;
return false;
}
long nextReadIndex = _readHeader.AtomicIncrement();
long currentReadIndex = nextReadIndex - 1;
value = _buffer[currentReadIndex & _indexMask];
return true;
}
/// <summary>
/// Gets the capacity in number of items of the buffer.
/// </summary>
/// <value>
/// The capacity.
/// </value>
public int Capacity
{
get { return _capacity; }
}
#if HAVE_METHODINLINING
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
internal static bool HasNext(in long readHeader, in long writeHeader)
{
ulong writeHeaderUL = (ulong) writeHeader;
ulong readHeaderUL = (ulong) readHeader;
return writeHeaderUL - readHeaderUL > 0 && writeHeaderUL > readHeaderUL;
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public static class MARSTest
{
private static readonly string _connStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString;
#if DEBUG
[CheckConnStrSetupFact]
public static void MARSAsyncTimeoutTest()
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
connection.Open();
SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command.CommandTimeout = 1;
Task<object> result = command.ExecuteScalarAsync();
Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after one second, but no results after 30 seconds");
Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));
Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));
Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);
Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");
field.SetValue(null, true);
try
{
SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command2.CommandTimeout = 1;
result = command2.ExecuteScalarAsync();
Assert.True(((IAsyncResult)result).AsyncWaitHandle.WaitOne(30 * 1000), "Expected timeout after six or so seconds, but no results after 30 seconds");
Assert.True(result.IsFaulted, string.Format("Expected task result to be faulted, but instead it was {0}", result.Status));
// Pause here to ensure that the async closing is completed
Thread.Sleep(200);
Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
}
finally
{
field.SetValue(null, false);
}
}
}
[CheckConnStrSetupFact]
public static void MARSSyncTimeoutTest()
{
using (SqlConnection connection = new SqlConnection(_connStr))
{
connection.Open();
SqlCommand command = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command.CommandTimeout = 1;
bool hitException = false;
try
{
object result = command.ExecuteScalar();
}
catch (Exception e)
{
Assert.True(e is SqlException, "Expected SqlException but found " + e);
hitException = true;
}
Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");
Assert.True(connection.State == ConnectionState.Open, string.Format("Expected connection to be open after soft timeout, but it was {0}", connection.State));
Type type = typeof(SqlDataReader).GetTypeInfo().Assembly.GetType("System.Data.SqlClient.TdsParserStateObject");
FieldInfo field = type.GetField("_skipSendAttention", BindingFlags.NonPublic | BindingFlags.Static);
Assert.True(field != null, "Error: This test cannot succeed on retail builds because it uses the _skipSendAttention test hook");
field.SetValue(null, true);
hitException = false;
try
{
SqlCommand command2 = new SqlCommand("WAITFOR DELAY '01:00:00';SELECT 1", connection);
command2.CommandTimeout = 1;
try
{
object result = command2.ExecuteScalar();
}
catch (Exception e)
{
Assert.True(e is SqlException, "Expected SqlException but found " + e);
hitException = true;
}
Assert.True(hitException, "Expected a timeout exception but ExecutScalar succeeded");
Assert.True(connection.State == ConnectionState.Closed, string.Format("Expected connection to be closed after hard timeout, but it was {0}", connection.State));
}
finally
{
field.SetValue(null, false);
}
}
}
#endif
[CheckConnStrSetupFact]
public static void MARSSyncBusyReaderTest()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
int rows1 = 0;
while (reader1.Read())
{
rows1++;
if (rows1 == 415)
break;
}
Assert.True(rows1 == 415, "MARSSyncBusyReaderTest Failure, #1");
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
int rows2 = 0;
while (reader2.Read())
{
rows2++;
if (rows2 == 415)
break;
}
Assert.True(rows2 == 415, "MARSSyncBusyReaderTest Failure, #2");
for (int i = 415; i < 830; i++)
{
Assert.True(reader1.Read() && reader2.Read(), "MARSSyncBusyReaderTest Failure #3");
Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0),
"MARSSyncBusyReaderTest, Failure #4" + "\n" +
"reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" +
"reader2.GetInt32(0): " + reader2.GetInt32(0));
}
Assert.False(reader1.Read() || reader2.Read(), "MARSSyncBusyReaderTest, Failure #5");
}
}
}
}
[CheckConnStrSetupFact]
public static void MARSSyncExecuteNonQueryTest()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlCommand comm1 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm2 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm3 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm4 = new SqlCommand("select * from Orders", conn))
using (SqlCommand comm5 = new SqlCommand("select * from Orders", conn))
{
comm1.ExecuteNonQuery();
comm2.ExecuteNonQuery();
comm3.ExecuteNonQuery();
comm4.ExecuteNonQuery();
comm5.ExecuteNonQuery();
}
}
}
[CheckConnStrSetupFact]
public static void MARSSyncExecuteReaderTest1()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
int rows = 0;
while (reader1.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #1");
rows = 0;
while (reader2.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #2");
rows = 0;
while (reader3.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #3");
rows = 0;
while (reader4.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #4");
rows = 0;
while (reader5.Read())
{
rows++;
}
Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #5");
}
}
}
[CheckConnStrSetupFact]
public static void MARSSyncExecuteReaderTest2()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
for (int i = 0; i < 830; i++)
{
Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #1");
}
Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #2");
}
}
}
[CheckConnStrSetupFact]
public static void MARSSyncExecuteReaderTest3()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader())
{
for (int i = 0; i < 830; i++)
{
Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #1");
// All reads succeeded - check values.
Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0) &&
reader2.GetInt32(0) == reader3.GetInt32(0) &&
reader3.GetInt32(0) == reader4.GetInt32(0) &&
reader4.GetInt32(0) == reader5.GetInt32(0),
"MARSSyncExecuteReaderTest3, Failure #2" + "\n" +
"reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" +
"reader2.GetInt32(0): " + reader2.GetInt32(0) + "\n" +
"reader3.GetInt32(0): " + reader3.GetInt32(0) + "\n" +
"reader4.GetInt32(0): " + reader4.GetInt32(0) + "\n" +
"reader5.GetInt32(0): " + reader5.GetInt32(0));
}
Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #3");
}
}
}
[CheckConnStrSetupFact]
public static void MARSSyncExecuteReaderTest4()
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataReader reader1 = (new SqlCommand("select * from Orders where OrderID = 10248", conn)).ExecuteReader())
using (SqlDataReader reader2 = (new SqlCommand("select * from Orders where OrderID = 10249", conn)).ExecuteReader())
using (SqlDataReader reader3 = (new SqlCommand("select * from Orders where OrderID = 10250", conn)).ExecuteReader())
{
Assert.True(reader1.Read() && reader2.Read() && reader3.Read(), "MARSSyncExecuteReaderTest4 failure #1");
Assert.True(reader1.GetInt32(0) == 10248 &&
reader2.GetInt32(0) == 10249 &&
reader3.GetInt32(0) == 10250,
"MARSSyncExecuteReaderTest4 failure #2");
Assert.False(reader1.Read() || reader2.Read() || reader3.Read(), "MARSSyncExecuteReaderTest4 failure #3");
}
}
}
}
}
| |
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2008 June 13
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains definitions of global variables and contants.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
/* An array to map all upper-case characters into their corresponding
** lower-case character.
**
** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
** handle case conversions for the UTF character set since the tables
** involved are nearly as big or bigger than SQLite itself.
*/
/* An array to map all upper-case characters into their corresponding
** lower-case character.
*/
//
// Replaced in C# with sqlite3UpperToLower class
// static int[] sqlite3UpperToLower = new int[] {
//#if SQLITE_ASCII
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
//18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
//36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
//54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
//104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
//122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
//108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
//126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
//144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
//162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
//180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
//198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
//216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
//234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
//252,253,254,255
//#endif
//#if SQLITE_EBCDIC
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
//16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
//32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
//48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
//64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
//80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
//96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
//112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
//128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
//144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
//160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
//176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
//192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
//208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
//224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
//239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
//#endif
//};
/*
** The following 256 byte lookup table is used to support SQLites built-in
** equivalents to the following standard library functions:
**
** isspace() 0x01
** isalpha() 0x02
** isdigit() 0x04
** isalnum() 0x06
** isxdigit() 0x08
** toupper() 0x20
** SQLite identifier character 0x40
**
** Bit 0x20 is set if the mapped character requires translation to upper
** case. i.e. if the character is a lower-case ASCII character.
** If x is a lower-case ASCII character, then its upper-case equivalent
** is (x - 0x20). Therefore toupper() can be implemented as:
**
** (x & ~(map[x]&0x20))
**
** Standard function tolower() is implemented using the sqlite3UpperToLower[]
** array. tolower() is used more often than toupper() by SQLite.
**
** Bit 0x40 is set if the character non-alphanumeric and can be used in an
** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
** non-ASCII UTF character. Hence the test for whether or not a character is
** part of an identifier is 0x46.
**
** SQLite's versions are identical to the standard versions assuming a
** locale of "C". They are implemented as macros in sqliteInt.h.
*/
#if SQLITE_ASCII
private static byte[] sqlite3CtypeMap = new byte[] {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
};
#endif
#if SQLITE_USE_URI
const bool SQLITE_USE_URI = true;
#else
//# define SQLITE_USE_URI 0
private const bool SQLITE_USE_URI = false;
#endif
/*
** The following singleton contains the global configuration for
** the SQLite library.
*/
private static Sqlite3Config sqlite3Config = new Sqlite3Config(
SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
1, /* bCoreMutex */
SQLITE_THREADSAFE != 0, /* bFullMutex */
SQLITE_USE_URI, /* bOpenUri */
0x7ffffffe, /* mxStrlen */
100, /* szLookaside */
500, /* nLookaside */
new sqlite3_mem_methods(), /* m */
new sqlite3_mutex_methods(null, null, null, null, null, null, null, null, null), /* mutex */
new sqlite3_pcache_methods(),/* pcache */
null, /* pHeap */
0, /* nHeap */
0, 0, /* mnHeap, mxHeap */
null, /* pScratch */
0, /* szScratch */
0, /* nScratch */
null, /* pPage */
SQLITE_DEFAULT_PAGE_SIZE, /* szPage */
0, /* nPage */
0, /* mxParserStack */
false, /* sharedCacheEnabled */
/* All the rest should always be initialized to zero */
0, /* isInit */
0, /* inProgress */
0, /* isMutexInit */
0, /* isMallocInit */
0, /* isPCacheInit */
null, /* pInitMutex */
0, /* nRefInitMutex */
null, /* xLog */
0, /* pLogArg */
false /* bLocaltimeFault */
);
/*
** Hash table for global functions - functions common to all
** database connections. After initialization, this table is
** read-only.
*/
private static FuncDefHash sqlite3GlobalFunctions;
/*
** Constant tokens for values 0 and 1.
*/
private static Token[] sqlite3IntTokens = {
new Token( "0", 1 ),
new Token( "1", 1 )
};
/*
** The value of the "pending" byte must be 0x40000000 (1 byte past the
** 1-gibabyte boundary) in a compatible database. SQLite never uses
** the database page that contains the pending byte. It never attempts
** to read or write that page. The pending byte page is set assign
** for use by the VFS layers as space for managing file locks.
**
** During testing, it is often desirable to move the pending byte to
** a different position in the file. This allows code that has to
** deal with the pending byte to run on files that are much smaller
** than 1 GiB. The sqlite3_test_control() interface can be used to
** move the pending byte.
**
** IMPORTANT: Changing the pending byte to any value other than
** 0x40000000 results in an incompatible database file format!
** Changing the pending byte during operating results in undefined
** and dileterious behavior.
*/
#if !SQLITE_OMIT_WSD
private static int sqlite3PendingByte = 0x40000000;
#endif
//#include "opcodes.h"
/*
** Properties of opcodes. The OPFLG_INITIALIZER macro is
** created by mkopcodeh.awk during compilation. Data is obtained
** from the comments following the "case OP_xxxx:" statements in
** the vdbe.c file.
*/
public static int[] sqlite3OpcodeProperty;
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.SPOT.Platform.Test;
using System.Collections;
namespace Microsoft.SPOT.Platform.Tests
{
public class HashtableTests : IMFTestInterface
{
private const int c_MinimumEntries = 10;
private const int c_BareMinimum = 1;
//--//
internal class MyClassTypeEntry
{
public MyClassTypeEntry()
{
m_structValue = Guid.NewGuid();
m_stringValue = "string" + m_structValue.ToString();
m_integralValue = 42;
}
public MyClassTypeEntry(string s, int i, Guid g)
{
m_stringValue = s;
m_integralValue = i;
m_structValue = g;
}
// override Object.GetHashCode
public override int GetHashCode()
{
return base.GetHashCode();
}
// override Object.Equals
public override bool Equals(object obj)
{
try
{
MyClassTypeEntry a = (MyClassTypeEntry)obj;
if (m_stringValue != a.StringValue)
{
return false;
}
if (m_integralValue != a.IntegerValue)
{
return false;
}
if (!m_structValue.Equals(a.GuidValue))
{
return false;
}
return true;
}
catch(Exception e)
{
Log.Exception("Unexpected exception when comparing items", e);
return false;
}
}
public string StringValue
{
get
{
return m_stringValue;
}
}
public int IntegerValue
{
get
{
return m_integralValue;
}
}
public Guid GuidValue
{
get
{
return m_structValue;
}
}
//--//
public static string GetKey(int i, Guid g)
{
return "key_" + i.ToString() + "__" + g.ToString();
}
//--//
private readonly string m_stringValue;
private readonly int m_integralValue;
private readonly Guid m_structValue;
}
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//Test Case Calls
[TestMethod]
public MFTestResults Hashtable_Add_Contains_Remove_Test1()
{
// Enter 5 values with 5 unique keys
// 1) check that the keys are in the table
// 2) check that all keys are present
// 3) check that the items are what they are expected to be through all possible interfaces
// 4) check that we can successfully remove the items
// 5) check that a removed item is no longer in the table, and so its key it is no longer in the table as well
try
{
string key1 = "key1";
string key2 = "key2";
string key3 = "key3";
string key4 = "key4";
string key5 = "key5";
MyClassTypeEntry entry1 = new MyClassTypeEntry("1 (one)", 1, Guid.NewGuid());
MyClassTypeEntry entry2 = new MyClassTypeEntry("2 (two)", 2, Guid.NewGuid());
MyClassTypeEntry entry3 = new MyClassTypeEntry("3 (three)", 3, Guid.NewGuid());
MyClassTypeEntry entry4 = new MyClassTypeEntry("4 (four)", 4, Guid.NewGuid());
MyClassTypeEntry entry5 = new MyClassTypeEntry("5 (five)", 5, Guid.NewGuid());
string[] keys = new string[] { key1, key2, key3, key4, key5 };
MyClassTypeEntry[] entries = new MyClassTypeEntry[] { entry1, entry2, entry3, entry4, entry5 };
Hashtable t = new Hashtable();
// 1) add 5 items with 5 unique keys
t.Add(key1, entry1);
t.Add(key2, entry2);
t.Add(key3, entry3);
t.Add(key4, entry4);
t.Add(key5, entry5);
// 2) check all added keys are present
if (
!t.Contains(key1) ||
!t.Contains(key2) ||
!t.Contains(key3) ||
!t.Contains(key4) ||
!t.Contains(key5)
)
{
return MFTestResults.Fail;
}
// 3) check that the items are what they are expected to be
// check the items reference and value first...
int index = 0;
foreach (String k in keys)
{
// test indexer
MyClassTypeEntry entry = (MyClassTypeEntry)t[k];
// check that the refernce is the same
if (!Object.ReferenceEquals(entry, (entries[index])))
{
return MFTestResults.Fail;
}
// check that the values are the same
if (!entry.Equals(entries[index]))
{
return MFTestResults.Fail;
}
index++;
}
// ... then check the keys
foreach (String k in keys)
{
bool found = false;
ICollection keysCollection = t.Keys;
foreach (string key in keysCollection)
{
if (k == key)
{
found = true;
break;
}
}
if (!found) return MFTestResults.Fail;
}
// 4) checked that we can remove the items
// ... then check the keys
foreach (String k in keys)
{
t.Remove(k);
}
// 4) checked that we can remove the items
// ... then check the keys
foreach (String k in keys)
{
t.Remove(k);
}
// 5) check that a removed item is no longer in the table, and so its key it is no longer in the table as well
// check the items reference and value first...
// test nothing is left in teh Hashtable
if (t.Count != 0)
{
return MFTestResults.Fail;
}
int indexR = 0;
foreach (String k in keys)
{
// test Contains
if (t.Contains(k))
{
return MFTestResults.Fail;
}
// test indexer
MyClassTypeEntry entry = (MyClassTypeEntry)t[k];
if (entry != null)
{
return MFTestResults.Fail;
}
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Hashtable_Add_Clear()
{
try
{
Hashtable t = new Hashtable();
MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries);
if (t.Count != vals.Length)
{
return MFTestResults.Fail;
}
t.Clear();
if (t.Count != 0)
{
return MFTestResults.Fail;
}
ICollection keys = t.Keys;
ICollection values = t.Values;
if (keys.Count != 0)
{
return MFTestResults.Fail;
}
if (values.Count != 0)
{
return MFTestResults.Fail;
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Hashtable_CheckKeys()
{
try
{
Hashtable t = new Hashtable();
MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries);
// check that the hastable contains the keys
foreach (MyClassTypeEntry k in vals)
{
if (!t.Contains(k.StringValue))
{
return MFTestResults.Fail;
}
}
ICollection keys = t.Keys;
foreach(MyClassTypeEntry m in vals)
{
// check that the key collection contains the key
bool found = false;
foreach(string s in keys)
{
if(m.StringValue.Equals(s))
{
found = true; break;
}
}
if (!found)
{
return MFTestResults.Fail;
}
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Hashtable_CheckValues()
{
try
{
Hashtable t = new Hashtable();
MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries);
// check that the hastable contains the keys
foreach (MyClassTypeEntry k in vals)
{
if (!t.Contains(k.StringValue))
{
return MFTestResults.Fail;
}
}
ICollection values = t.Values;
foreach (MyClassTypeEntry m in vals)
{
// check that the key collection contains the key
bool verified = false;
foreach (MyClassTypeEntry mm in values)
{
if (m.Equals(mm))
{
verified = true; break;
}
}
if (!verified)
{
return MFTestResults.Fail;
}
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Hashtable_Count()
{
try
{
Hashtable t = new Hashtable();
MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries);
int count = t.Count;
if (vals.Length != count)
{
return MFTestResults.Fail;
}
t.Add("a new key without a guid, can't exist", new MyClassTypeEntry());
t.Add("a new key without a guid, can't exist again", new MyClassTypeEntry());
t.Add("a new key without a guid, can't exist another time", new MyClassTypeEntry());
if ((count + 3) != t.Count)
{
return MFTestResults.Fail;
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Hashtable_Duplicate()
{
try
{
Hashtable t = new Hashtable();
MyClassTypeEntry[] vals = InsertRandomValues(t, c_MinimumEntries);
//
// find a key and insert a duplicate: must fail
//
MyClassTypeEntry entry = vals[vals.Length / 2];
string key = MyClassTypeEntry.GetKey(entry.IntegerValue, entry.GuidValue);
bool exceptionThrown = false;
try
{
t.Add(key, new MyClassTypeEntry());
}
catch(Exception e)
{
Log.Exception("EXpected exception -- duplicate in Hashtable", e);
exceptionThrown = true;
}
if (!exceptionThrown)
{
return MFTestResults.Fail;
}
// remove the item
t.Remove(key);
// try insert again: must succeeed
exceptionThrown = false;
try
{
t.Add(key, new MyClassTypeEntry());
}
catch
{
exceptionThrown = true;
}
if (exceptionThrown)
{
return MFTestResults.Fail;
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Hashtable_CopyTo()
{
try
{
// TODO TODO TODO
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults Hashtable_Clone()
{
try
{
// TODO TODO TODO
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
//--//
/// <summary>
/// Creates a MyClassEntry type whose string member with the prefix is the key item in the the hashtable
/// </summary>
private MyClassTypeEntry[] InsertRandomValues(Hashtable t, int max)
{
int count = (new Random().Next() % max) + c_BareMinimum; // at least 1
MyClassTypeEntry[] vals = new MyClassTypeEntry[count];
for (int i = 0; i < count; ++i)
{
Guid g = Guid.NewGuid();
string key = MyClassTypeEntry.GetKey(i, g);
vals[i] = new MyClassTypeEntry(key, i, g);
t.Add(key, vals[i]);
}
return vals;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: src/proto/grpc/testing/services.proto
// Original file comments:
// 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.
//
// An integration test service that covers all the method signature permutations
// of unary/streaming requests/responses.
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Grpc.Testing {
public static partial class BenchmarkService
{
static readonly string __ServiceName = "grpc.testing.BenchmarkService";
static readonly grpc::Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom);
static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
grpc::MethodType.Unary,
__ServiceName,
"UnaryCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_StreamingCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"StreamingCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of BenchmarkService</summary>
public abstract partial class BenchmarkServiceBase
{
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task StreamingCall(grpc::IAsyncStreamReader<global::Grpc.Testing.SimpleRequest> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.SimpleResponse> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for BenchmarkService</summary>
public partial class BenchmarkServiceClient : grpc::ClientBase<BenchmarkServiceClient>
{
/// <summary>Creates a new client for BenchmarkService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public BenchmarkServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for BenchmarkService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public BenchmarkServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected BenchmarkServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected BenchmarkServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingCall(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_StreamingCall, null, options);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override BenchmarkServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new BenchmarkServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(BenchmarkServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall)
.AddMethod(__Method_StreamingCall, serviceImpl.StreamingCall).Build();
}
}
public static partial class WorkerService
{
static readonly string __ServiceName = "grpc.testing.WorkerService";
static readonly grpc::Marshaller<global::Grpc.Testing.ServerArgs> __Marshaller_ServerArgs = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerArgs.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.ServerStatus> __Marshaller_ServerStatus = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerStatus.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.ClientArgs> __Marshaller_ClientArgs = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientArgs.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.ClientStatus> __Marshaller_ClientStatus = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientStatus.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.CoreRequest> __Marshaller_CoreRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.CoreResponse> __Marshaller_CoreResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.Void> __Marshaller_Void = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Void.Parser.ParseFrom);
static readonly grpc::Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> __Method_RunServer = new grpc::Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"RunServer",
__Marshaller_ServerArgs,
__Marshaller_ServerStatus);
static readonly grpc::Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> __Method_RunClient = new grpc::Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"RunClient",
__Marshaller_ClientArgs,
__Marshaller_ClientStatus);
static readonly grpc::Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse> __Method_CoreCount = new grpc::Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse>(
grpc::MethodType.Unary,
__ServiceName,
"CoreCount",
__Marshaller_CoreRequest,
__Marshaller_CoreResponse);
static readonly grpc::Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void> __Method_QuitWorker = new grpc::Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void>(
grpc::MethodType.Unary,
__ServiceName,
"QuitWorker",
__Marshaller_Void,
__Marshaller_Void);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[1]; }
}
/// <summary>Base class for server-side implementations of WorkerService</summary>
public abstract partial class WorkerServiceBase
{
/// <summary>
/// Start server with specified workload.
/// First request sent specifies the ServerConfig followed by ServerStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test server
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task RunServer(grpc::IAsyncStreamReader<global::Grpc.Testing.ServerArgs> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.ServerStatus> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Start client with specified workload.
/// First request sent specifies the ClientConfig followed by ClientStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test client
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task RunClient(grpc::IAsyncStreamReader<global::Grpc.Testing.ClientArgs> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.ClientStatus> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.CoreResponse> CoreCount(global::Grpc.Testing.CoreRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Void> QuitWorker(global::Grpc.Testing.Void request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for WorkerService</summary>
public partial class WorkerServiceClient : grpc::ClientBase<WorkerServiceClient>
{
/// <summary>Creates a new client for WorkerService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public WorkerServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for WorkerService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public WorkerServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected WorkerServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected WorkerServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Start server with specified workload.
/// First request sent specifies the ServerConfig followed by ServerStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test server
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RunServer(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Start server with specified workload.
/// First request sent specifies the ServerConfig followed by ServerStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test server
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_RunServer, null, options);
}
/// <summary>
/// Start client with specified workload.
/// First request sent specifies the ClientConfig followed by ClientStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test client
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RunClient(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Start client with specified workload.
/// First request sent specifies the ClientConfig followed by ClientStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test client
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_RunClient, null, options);
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CoreCount(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CoreCount, null, options, request);
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CoreCountAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CoreCount, null, options, request);
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return QuitWorker(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_QuitWorker, null, options, request);
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return QuitWorkerAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_QuitWorker, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override WorkerServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new WorkerServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(WorkerServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_RunServer, serviceImpl.RunServer)
.AddMethod(__Method_RunClient, serviceImpl.RunClient)
.AddMethod(__Method_CoreCount, serviceImpl.CoreCount)
.AddMethod(__Method_QuitWorker, serviceImpl.QuitWorker).Build();
}
}
}
#endregion
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
public static class PathTests
{
[Theory]
[InlineData(null, null, null)]
[InlineData(null, null, "exe")]
[InlineData("", "", "")]
[InlineData("file", "file.exe", null)]
[InlineData("file.", "file.exe", "")]
[InlineData("file.exe", "file", "exe")]
[InlineData("file.exe", "file", ".exe")]
[InlineData("file.exe", "file.txt", "exe")]
[InlineData("file.exe", "file.txt", ".exe")]
[InlineData("file.txt.exe", "file.txt.bin", "exe")]
[InlineData("dir/file.exe", "dir/file.t", "exe")]
[InlineData("dir/file.t", "dir/file.exe", "t")]
[InlineData("dir/file.exe", "dir/file", "exe")]
public static void ChangeExtension(string expected, string path, string newExtension)
{
if (expected != null)
expected = expected.Replace('/', Path.DirectorySeparatorChar);
if (path != null)
path = path.Replace('/', Path.DirectorySeparatorChar);
Assert.Equal(expected, Path.ChangeExtension(path, newExtension));
}
[Theory,
InlineData(null, null),
InlineData(@"", null),
InlineData(@".", @""),
InlineData(@"..", @""),
InlineData(@"baz", @"")
]
public static void GetDirectoryName(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory,
InlineData(@"dir/baz", @"dir"),
InlineData(@"dir\baz", @"dir"),
InlineData(@"dir\baz\bar", @"dir\baz"),
InlineData(@"dir\\baz", @"dir"),
InlineData(@" dir\baz", @" dir"),
InlineData(@" C:\dir\baz", @"C:\dir"),
InlineData(@"..\..\files.txt", @"..\.."),
InlineData(@"C:\", null),
InlineData(@"C:", null)
]
[PlatformSpecific(PlatformID.Windows)]
public static void GetDirectoryName_Windows(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Theory,
InlineData(@"dir/baz", @"dir"),
InlineData(@"dir//baz", @"dir"),
InlineData(@"dir\baz", @""),
InlineData(@"dir/baz/bar", @"dir/baz"),
InlineData(@"../../files.txt", @"../.."),
InlineData(@"/", null)
]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void GetDirectoryName_Unix(string path, string expected)
{
Assert.Equal(expected, Path.GetDirectoryName(path));
}
[Fact]
public static void GetDirectoryName_CurrentDirectory()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz")));
Assert.Equal(null, Path.GetDirectoryName(Path.GetPathRoot(curDir)));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetDirectoryName_ControlCharacters_Unix()
{
Assert.Equal(new string('\t', 1), Path.GetDirectoryName(Path.Combine(new string('\t', 1), "file")));
Assert.Equal(new string('\b', 2), Path.GetDirectoryName(Path.Combine(new string('\b', 2), "fi le")));
Assert.Equal(new string('\v', 3), Path.GetDirectoryName(Path.Combine(new string('\v', 3), "fi\nle")));
Assert.Equal(new string('\n', 4), Path.GetDirectoryName(Path.Combine(new string('\n', 4), "fi\rle")));
}
[Theory]
[InlineData(".exe", "file.exe")]
[InlineData("", "file")]
[InlineData(null, null)]
[InlineData("", "file.")]
[InlineData(".s", "file.s")]
[InlineData("", "test/file")]
[InlineData(".extension", "test/file.extension")]
public static void GetExtension(string expected, string path)
{
if (path != null)
{
path = path.Replace('/', Path.DirectorySeparatorChar);
}
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData(".e xe", "file.e xe")]
[InlineData(". ", "file. ")]
[InlineData(". ", " file. ")]
[InlineData(".extension", " file.extension")]
[InlineData(".exten\tsion", "file.exten\tsion")]
public static void GetExtension_Unix(string expected, string path)
{
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[Fact]
public static void GetFileName()
{
Assert.Equal(null, Path.GetFileName(null));
Assert.Equal(string.Empty, Path.GetFileName(string.Empty));
Assert.Equal(".", Path.GetFileName("."));
Assert.Equal("..", Path.GetFileName(".."));
Assert.Equal("file", Path.GetFileName("file"));
Assert.Equal("file.", Path.GetFileName("file."));
Assert.Equal("file.exe", Path.GetFileName("file.exe"));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("baz", "file.exe")));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileName(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFileName_Unix()
{
Assert.Equal(" . ", Path.GetFileName(" . "));
Assert.Equal(" .. ", Path.GetFileName(" .. "));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName(Path.Combine("b \r\n ar", "fi le")));
}
[Fact]
public static void GetFileNameWithoutExtension()
{
Assert.Equal(null, Path.GetFileNameWithoutExtension(null));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(string.Empty));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file"));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file.exe"));
Assert.Equal("file", Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[Fact]
public static void GetPathRoot()
{
Assert.Null(Path.GetPathRoot(null));
Assert.Equal(string.Empty, Path.GetPathRoot(string.Empty));
string cwd = Directory.GetCurrentDirectory();
Assert.Equal(cwd.Substring(0, cwd.IndexOf(Path.DirectorySeparatorChar) + 1), Path.GetPathRoot(cwd));
Assert.True(Path.IsPathRooted(cwd));
Assert.Equal(string.Empty, Path.GetPathRoot(@"file.exe"));
Assert.False(Path.IsPathRooted("file.exe"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\test\unc\path\to\something", @"\\test\unc")]
[InlineData(@"\\a\b\c\d\e", @"\\a\b")]
[InlineData(@"\\a\b\", @"\\a\b")]
[InlineData(@"\\a\b", @"\\a\b")]
[InlineData(@"\\test\unc", @"\\test\unc")]
[InlineData(@"\\?\UNC\test\unc\path\to\something", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\a\b", @"\\?\UNC\a\b")]
[InlineData(@"\\?\UNC\a\b\", @"\\?\UNC\a\b")]
[InlineData(@"\\?\C:\foo\bar.txt", @"\\?\C:\")]
public static void GetPathRoot_Windows_UncAndExtended(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:", @"C:")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\\", @"C:\")]
[InlineData(@"C://", @"C:\")]
[InlineData(@"C:\foo", @"C:\")]
[InlineData(@"C:\\foo", @"C:\")]
[InlineData(@"C://foo", @"C:\")]
public static void GetPathRoot_Windows(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetPathRoot_Unix()
{
// slashes are normal filename characters
string uncPath = @"\\test\unc\path\to\something";
Assert.False(Path.IsPathRooted(uncPath));
Assert.Equal(string.Empty, Path.GetPathRoot(uncPath));
}
[Fact]
public static void GetRandomFileName()
{
char[] invalidChars = Path.GetInvalidFileNameChars();
var fileNames = new HashSet<string>();
for (int i = 0; i < 100; i++)
{
string s = Path.GetRandomFileName();
Assert.Equal(s.Length, 8 + 1 + 3);
Assert.Equal(s[8], '.');
Assert.Equal(-1, s.IndexOfAny(invalidChars));
Assert.True(fileNames.Add(s));
}
}
[Fact]
public static void GetInvalidPathChars()
{
Assert.NotNull(Path.GetInvalidPathChars());
Assert.NotSame(Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidPathChars(), (IEnumerable<char>)Path.GetInvalidPathChars());
Assert.True(Path.GetInvalidPathChars().Length > 0);
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
Assert.Throws<ArgumentException>(() => Path.ChangeExtension(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, bad, bad, bad, bad));
Assert.Throws<ArgumentException>(() => Path.GetDirectoryName(bad));
Assert.Throws<ArgumentException>(() => Path.GetExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileName(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileNameWithoutExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(bad));
Assert.Throws<ArgumentException>(() => Path.GetPathRoot(bad));
Assert.Throws<ArgumentException>(() => Path.IsPathRooted(bad));
});
}
[Fact]
public static void GetInvalidFileNameChars()
{
Assert.NotNull(Path.GetInvalidFileNameChars());
Assert.NotSame(Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.True(Path.GetInvalidFileNameChars().Length > 0);
}
[Fact]
[OuterLoop]
public static void GetInvalidFileNameChars_OtherCharsValid()
{
string curDir = Directory.GetCurrentDirectory();
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
for (int i = 0; i < char.MaxValue; i++)
{
char c = (char)i;
if (!invalidChars.Contains(c))
{
string name = "file" + c + ".txt";
Assert.Equal(Path.Combine(curDir, name), Path.GetFullPath(name));
}
}
}
[Fact]
public static void GetTempPath_Default()
{
string tmpPath = Path.GetTempPath();
Assert.False(string.IsNullOrEmpty(tmpPath));
Assert.Equal(tmpPath, Path.GetTempPath());
Assert.Equal(Path.DirectorySeparatorChar, tmpPath[tmpPath.Length - 1]);
Assert.True(Directory.Exists(tmpPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp")]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\tmp\", @"C:\tmp")]
[InlineData(@"C:\tmp\", @"C:\tmp\")]
public static void GetTempPath_SetEnvVar_Windows(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMP", expected, newTempPath);
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("/tmp/", "/tmp")]
[InlineData("/tmp/", "/tmp/")]
[InlineData("/", "/")]
[InlineData("/var/tmp/", "/var/tmp")]
[InlineData("/var/tmp/", "/var/tmp/")]
[InlineData("~/", "~")]
[InlineData("~/", "~/")]
[InlineData(".tmp/", ".tmp")]
[InlineData("./tmp/", "./tmp")]
[InlineData("/home/someuser/sometempdir/", "/home/someuser/sometempdir/")]
[InlineData("/home/someuser/some tempdir/", "/home/someuser/some tempdir/")]
[InlineData("/tmp/", null)]
public static void GetTempPath_SetEnvVar_Unix(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMPDIR", expected, newTempPath);
}
private static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, original);
Assert.Equal(original, Path.GetTempPath());
}
}
[Fact]
public static void GetTempFileName()
{
string tmpFile = Path.GetTempFileName();
try
{
Assert.True(File.Exists(tmpFile));
Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false);
Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars()));
using (FileStream fs = File.OpenRead(tmpFile))
{
Assert.Equal(0, fs.Length);
}
Assert.Equal(Path.Combine(Path.GetTempPath(), Path.GetFileName(tmpFile)), tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[Fact]
public static void GetFullPath_InvalidArgs()
{
Assert.Throws<ArgumentNullException>(() => Path.GetFullPath(null));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(string.Empty));
}
[Fact]
public static void GetFullPath_BasicExpansions()
{
string curDir = Directory.GetCurrentDirectory();
// Current directory => current directory
Assert.Equal(curDir, Path.GetFullPath(curDir));
// "." => current directory
Assert.Equal(curDir, Path.GetFullPath("."));
// ".." => up a directory
Assert.Equal(Path.GetDirectoryName(curDir), Path.GetFullPath(".."));
// "dir/./././." => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, ".", ".", ".", ".", ".")));
// "dir///." => "dir"
Assert.Equal(curDir, Path.GetFullPath(curDir + new string(Path.DirectorySeparatorChar, 3) + "."));
// "dir/../dir/./../dir" => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, "..", Path.GetFileName(curDir), ".", "..", Path.GetFileName(curDir))));
// "C:\somedir\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "somedir", "..")));
// "C:\." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), ".")));
// "C:\..\..\..\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "..", "..", "..", "..")));
// "C:\\\" => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.GetPathRoot(curDir) + new string(Path.DirectorySeparatorChar, 3)));
// Path longer than MaxPath that normalizes down to less than MaxPath
const int Iters = 10000;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 2));
for (int i = 0; i < 10000; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(curDir, Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFullPath_Unix_Whitespace()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal("/ / ", Path.GetFullPath("/ // "));
Assert.Equal(Path.Combine(curDir, " "), Path.GetFullPath(" "));
Assert.Equal(Path.Combine(curDir, "\r\n"), Path.GetFullPath("\r\n"));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://somefile")]
public static void GetFullPath_Unix_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", "/")),
Path.GetFullPath(uriAsFileName));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_NormalizedLongPathTooLong()
{
// Try out a long path that normalizes down to more than MaxPath
string curDir = Directory.GetCurrentDirectory();
const int Iters = 260;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4));
for (int i = 0; i < Iters; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.');
}
// Now no longer throws unless over ~32K
Assert.NotNull(Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_AlternateDataStreamsNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"bad:path"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"C:\some\bad:path"));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_URIFormatNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("http://www.microsoft.com"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("file://www.microsoft.com"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\GLOBALROOT\")]
[InlineData(@"\\?\")]
[InlineData(@"\\?\.")]
[InlineData(@"\\?\..")]
[InlineData(@"\\?\\")]
[InlineData(@"\\?\C:\\")]
[InlineData(@"\\?\C:\|")]
[InlineData(@"\\?\C:\.")]
[InlineData(@"\\?\C:\..")]
[InlineData(@"\\?\C:\Foo\.")]
[InlineData(@"\\?\C:\Foo\..")]
public static void GetFullPath_Windows_ArgumentExceptionPaths(string path)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"bad::$DATA")]
[InlineData(@"C :")]
[InlineData(@"C :\somedir")]
public static void GetFullPath_Windows_NotSupportedExceptionPaths(string path)
{
// Many of these used to throw ArgumentException despite being documented as NotSupportedException
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:...")]
[InlineData(@"C:...\somedir")]
[InlineData(@"\.. .\")]
[InlineData(@"\. .\")]
[InlineData(@"\ .\")]
public static void GetFullPath_Windows_LegacyArgumentExceptionPaths(string path)
{
// These paths are legitimate Windows paths that can be created without extended syntax.
// We now allow them through.
Path.GetFullPath(path);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_MaxPathNotTooLong()
{
// Shouldn't throw anymore
Path.GetFullPath(@"C:\" + new string('a', 255) + @"\");
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_PathTooLong()
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\.", @"C:\")]
[InlineData(@"C:\..", @"C:\")]
[InlineData(@"C:\..\..", @"C:\")]
[InlineData(@"C:\A\..", @"C:\")]
[InlineData(@"C:\..\..\A\..", @"C:\")]
public static void GetFullPath_Windows_RelativeRoot(string path, string expected)
{
Assert.Equal(Path.GetFullPath(path), expected);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_StrangeButLegalPaths()
{
// These are legal and creatable without using extended syntax if you use a trailing slash
// (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from
// being blocked when they hit these paths.
string curDir = Directory.GetCurrentDirectory();
Assert.NotEqual(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\C:\ ")]
[InlineData(@"\\?\C:\ \ ")]
[InlineData(@"\\?\C:\ .")]
[InlineData(@"\\?\C:\ ..")]
[InlineData(@"\\?\C:\...")]
public static void GetFullPath_Windows_ValidExtendedPaths(string path)
{
Assert.Equal(path, Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\server\share", @"\\server\share")]
[InlineData(@"\\server\share", @" \\server\share")]
[InlineData(@"\\server\share\dir", @"\\server\share\dir")]
[InlineData(@"\\server\share", @"\\server\share\.")]
[InlineData(@"\\server\share", @"\\server\share\..")]
[InlineData(@"\\server\share\", @"\\server\share\ ")]
[InlineData(@"\\server\ share\", @"\\server\ share\")]
[InlineData(@"\\?\UNC\server\share", @"\\?\UNC\server\share")]
[InlineData(@"\\?\UNC\server\share\dir", @"\\?\UNC\server\share\dir")]
[InlineData(@"\\?\UNC\server\share\. ", @"\\?\UNC\server\share\. ")]
[InlineData(@"\\?\UNC\server\share\.. ", @"\\?\UNC\server\share\.. ")]
[InlineData(@"\\?\UNC\server\share\ ", @"\\?\UNC\server\share\ ")]
[InlineData(@"\\?\UNC\server\ share\", @"\\?\UNC\server\ share\")]
public static void GetFullPath_Windows_UNC_Valid(string expected, string input)
{
Assert.Equal(expected, Path.GetFullPath(input));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\server")]
[InlineData(@"\\server\")]
[InlineData(@"\\server\\")]
[InlineData(@"\\server\..")]
[InlineData(@"\\?\UNC\")]
[InlineData(@"\\?\UNC\server")]
[InlineData(@"\\?\UNC\server\")]
[InlineData(@"\\?\UNC\server\\")]
[InlineData(@"\\?\UNC\server\..")]
[InlineData(@"\\?\UNC\server\share\.")]
[InlineData(@"\\?\UNC\server\share\..")]
[InlineData(@"\\?\UNC\a\b\\")]
public static void GetFullPath_Windows_UNC_Invalid(string invalidPath)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(invalidPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_83Paths()
{
// Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened.
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt");
File.Create(tempFilePath).Dispose();
try
{
// Get its short name
var sb = new StringBuilder(260);
if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name
{
// Make sure the shortened name expands back to the original one
Assert.Equal(tempFilePath, Path.GetFullPath(sb.ToString()));
// Validate case where short name doesn't expand to a real file
string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp";
Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName));
// Same thing, but with a long path that normalizes down to a short enough one
const int Iters = 1000;
var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2));
for (int i = 0; i < Iters; i++)
{
shortLongName.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString()));
}
}
finally
{
File.Delete(tempFilePath);
}
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData('*')]
[InlineData('?')]
public static void GetFullPath_Windows_Wildcards(char wildcard)
{
Assert.Throws<ArgumentException>("path", () => Path.GetFullPath("test" + wildcard + "ing"));
}
// Windows-only P/Invoke to create 8.3 short names from long names
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
}
| |
// 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.Globalization;
using System.Runtime.Tests.Common;
using Xunit;
public static class SByteTests
{
[Fact]
public static void TestCtorEmpty()
{
sbyte i = new sbyte();
Assert.Equal(0, i);
}
[Fact]
public static void TestCtorValue()
{
sbyte i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void TestMaxValue()
{
Assert.Equal(0x7F, sbyte.MaxValue);
}
[Fact]
public static void TestMinValue()
{
Assert.Equal(-0x80, sbyte.MinValue);
}
[Theory]
[InlineData((sbyte)114, 0)]
[InlineData(sbyte.MinValue, 1)]
[InlineData((sbyte)0, 1)]
[InlineData((sbyte)45, 1)]
[InlineData((sbyte)123, -1)]
[InlineData(sbyte.MaxValue, -1)]
public static void TestCompareTo(sbyte value, int expected)
{
sbyte i = 114;
int result = CompareHelper.NormalizeCompare(i.CompareTo(value));
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null, 1)]
[InlineData((sbyte)114, 0)]
[InlineData(sbyte.MinValue, 1)]
[InlineData((sbyte)(-23), 1)]
[InlineData((sbyte)0, 1)]
[InlineData((sbyte)45, 1)]
[InlineData((sbyte)123, -1)]
[InlineData(sbyte.MaxValue, -1)]
public static void TestCompareToObject(object obj, int expected)
{
IComparable comparable = (sbyte)114;
int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj));
Assert.Equal(expected, i);
}
[Fact]
public static void TestCompareToObjectInvalid()
{
IComparable comparable = (sbyte)114;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a sbyte
}
[Theory]
[InlineData((sbyte)78, true)]
[InlineData((sbyte)(-78), false)]
[InlineData((sbyte)0, false)]
public static void TestEqualsObject(object obj, bool expected)
{
sbyte i = 78;
Assert.Equal(expected, i.Equals(obj));
}
[Theory]
[InlineData((sbyte)78, true)]
[InlineData((sbyte)(-78), false)]
[InlineData((sbyte)0, false)]
public static void TestEqualsObject(sbyte i2, bool expected)
{
sbyte i = 78;
Assert.Equal(expected, i.Equals(i2));
}
[Fact]
public static void TestGetHashCode()
{
sbyte i1 = 123;
sbyte i2 = 65;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
sbyte i1 = 63;
Assert.Equal("63", i1.ToString());
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new NumberFormatInfo();
sbyte i1 = 63;
Assert.Equal("63", i1.ToString(numberFormat));
}
[Fact]
public static void TestToStringFormat()
{
sbyte i1 = 63;
Assert.Equal("63", i1.ToString("G"));
sbyte i2 = 82;
Assert.Equal("82", i2.ToString("g"));
sbyte i3 = 46;
Assert.Equal(string.Format("{0:N}", 46.00), i3.ToString("N"));
sbyte i4 = 0x24;
Assert.Equal("24", i4.ToString("x"));
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new NumberFormatInfo();
sbyte i1 = 63;
Assert.Equal("63", i1.ToString("G", numberFormat));
sbyte i2 = 82;
Assert.Equal("82", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
numberFormat.NumberDecimalSeparator = ".";
sbyte i3 = 24;
Assert.Equal("24.00", i3.ToString("N", numberFormat));
}
public static IEnumerable<object[]> ParseValidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
yield return new object[] { "-123", defaultStyle, defaultFormat, (sbyte)-123 };
yield return new object[] { "0", defaultStyle, defaultFormat, (sbyte)0 };
yield return new object[] { "123", defaultStyle, defaultFormat, (sbyte)123 };
yield return new object[] { " 123 ", defaultStyle, defaultFormat, (sbyte)123 };
yield return new object[] { "127", defaultStyle, defaultFormat, (sbyte)127 };
yield return new object[] { "12", NumberStyles.HexNumber, defaultFormat, (sbyte)0x12 };
yield return new object[] { "10", NumberStyles.AllowThousands, defaultFormat, (sbyte)10 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, (sbyte)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyNfi, (sbyte)123 };
yield return new object[] { "123", NumberStyles.Any, emptyNfi, (sbyte)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, (sbyte)0x12 };
yield return new object[] { "$100", NumberStyles.Currency, testNfi, (sbyte)100 };
}
public static IEnumerable<object[]> ParseInvalidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
testNfi.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, defaultFormat, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { " ", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "ab", defaultStyle, defaultFormat, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, defaultFormat, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, defaultFormat, typeof(FormatException) }; // Parentheses
yield return new object[] { 100.ToString("C0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Thousands
yield return new object[] { 67.90.ToString("F2"), defaultStyle, defaultFormat, typeof(FormatException) }; //Decimal
yield return new object[] { "ab", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, testNfi, typeof(FormatException) }; // Decimal
yield return new object[] { "-129", defaultStyle, defaultFormat, typeof(OverflowException) }; // < min value
yield return new object[] { "128", defaultStyle, defaultFormat, typeof(OverflowException) }; // > max value
}
[Theory, MemberData("ParseValidData")]
public static void TestParse(string value, NumberStyles style, NumberFormatInfo nfi, sbyte expected)
{
sbyte i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(true, sbyte.TryParse(value, out i));
Assert.Equal(expected, i);
Assert.Equal(expected, sbyte.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Equal(expected, sbyte.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(true, sbyte.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(expected, i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Equal(expected, sbyte.Parse(value, style));
}
Assert.Equal(expected, sbyte.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
[Theory, MemberData("ParseInvalidData")]
public static void TestParseInvalid(string value, NumberStyles style, NumberFormatInfo nfi, Type exceptionType)
{
sbyte i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(false, sbyte.TryParse(value, out i));
Assert.Equal(default(sbyte), i);
Assert.Throws(exceptionType, () => sbyte.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Throws(exceptionType, () => sbyte.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(false, sbyte.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(default(sbyte), i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Throws(exceptionType, () => sbyte.Parse(value, style));
}
Assert.Throws(exceptionType, () => sbyte.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
}
| |
/*
* Copyright (c) 2015 Andrew Johnson
*
* 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.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace CommonImageModel
{
/// <summary>
/// An Image object that allows you to read from it form multiple threads
/// </summary>
public sealed class WritableLockBitImage : IDisposable, IImageFrame
{
private bool _disposed;
private bool _locked;
private readonly Bitmap _bitmap;
private readonly BitmapData _bitmapData;
private readonly byte[] _buffer;
private readonly int _bitDepth;
private readonly int _width;
private readonly int _height;
/// <summary>
/// Creates a new writable lockbit image
/// </summary>
/// <remarks>
/// This will not hold on to the original reference of the passed in image,
/// so it's safe to dispose of any references passed to this object
/// </remarks>
public WritableLockBitImage(Image image)
{
_disposed = _locked = false;
_bitmap = new Bitmap(image.Clone() as Image);
_bitmapData = _bitmap.LockBits(
new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadWrite,
image.PixelFormat
);
_bitDepth = Image.GetPixelFormatSize(image.PixelFormat);
if (_bitDepth != 8 && _bitDepth != 24 && _bitDepth != 32)
{
throw new ArgumentException("Only 8, 24, and 32 bit pixels are supported.");
}
_buffer = new byte[_bitmapData.Width * _bitmapData.Height * (_bitDepth / 8)];
_width = image.Width;
_height = image.Height;
Marshal.Copy(_bitmapData.Scan0, _buffer, 0, _buffer.Length);
}
/// <summary>
/// Creates an empty writable lockbit image
/// </summary>
public WritableLockBitImage(int width, int height)
{
_disposed = _locked = false;
_bitmap = new Bitmap(width, height);
_bitmapData = _bitmap.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite,
_bitmap.PixelFormat
);
_bitDepth = Image.GetPixelFormatSize(_bitmap.PixelFormat);
if (_bitDepth != 8 && _bitDepth != 24 && _bitDepth != 32)
{
throw new ArgumentException("Only 8, 24, and 32 bit pixels are supported.");
}
_buffer = new byte[_bitmapData.Width * _bitmapData.Height * (_bitDepth / 8)];
_width = width;
_height = height;
Marshal.Copy(_bitmapData.Scan0, _buffer, 0, _buffer.Length);
}
/// <summary>
/// Get the pixel at a specific point in this image
/// </summary>
/// <param name="x">The X coordinate</param>
/// <param name="y">The Y coordinate</param>
/// <returns>A color representing this pixel</returns>
public Color GetPixel(int x, int y)
{
if (_disposed)
{
throw new ObjectDisposedException("Object already disposed");
}
Color clr = Color.Empty;
// Get color components count
int cCount = _bitDepth / 8;
// Get start index of the specified pixel
int offset = ((y * Width) + x) * cCount;
if (offset > _buffer.Length - cCount)
{
throw new IndexOutOfRangeException();
}
if (_bitDepth == 32) // For 32 bpp get Red, Green, Blue and Alpha
{
byte b = _buffer[offset];
byte g = _buffer[offset + 1];
byte r = _buffer[offset + 2];
byte a = _buffer[offset + 3]; // a
clr = Color.FromArgb(a, r, g, b);
}
if (_bitDepth == 24) // For 24 bpp get Red, Green and Blue
{
byte b = _buffer[offset];
byte g = _buffer[offset + 1];
byte r = _buffer[offset + 2];
clr = Color.FromArgb(r, g, b);
}
if (_bitDepth == 8) // For 8 bpp get color value (Red, Green and Blue values are the same)
{
byte c = _buffer[offset];
clr = Color.FromArgb(c, c, c);
}
return clr;
}
public void SetPixel(int x, int y, Color color)
{
if (_locked)
{
throw new InvalidOperationException("Cannot modify a locked image");
}
if (_disposed)
{
throw new ObjectDisposedException("Object already disposed");
}
// Get color components count
int cCount = _bitDepth / 8;
// Get start index of the specified pixel
int offset = ((y * Width) + x) * cCount;
if (offset > _buffer.Length - cCount)
{
throw new IndexOutOfRangeException();
}
if (_bitDepth == 32) // For 32 bpp get Red, Green, Blue and Alpha
{
_buffer[offset] = color.B;
_buffer[offset + 1] = color.G;
_buffer[offset + 2] = color.R;
_buffer[offset + 3] = color.A; // a
}
if (_bitDepth == 24) // For 24 bpp get Red, Green and Blue
{
_buffer[offset] = color.B;
_buffer[offset + 1] = color.G;
_buffer[offset + 2] = color.R;
}
if (_bitDepth == 8) // For 8 bpp get color value (Red, Green and Blue values are the same)
{
_buffer[offset] = color.B;
}
}
/// <summary>
/// The width of the image
/// </summary>
public int Width
{
get
{
if (_disposed)
{
throw new ObjectDisposedException("Object already disposed");
}
return _width;
}
}
/// <summary>
/// The height of the image
/// </summary>
public int Height
{
get
{
if (_disposed)
{
throw new ObjectDisposedException("Object already disposed");
}
return _height;
}
}
public void Lock()
{
if (_locked)
{
return;
}
_locked = true;
//Marshal.Copy(_buffer, 0, _bitmapData.Scan0, _buffer.Length);
WriteBufferDirectlyToMemory();
_bitmap.UnlockBits(_bitmapData);
}
public Image GetImage()
{
if (_locked == false)
{
throw new InvalidOperationException("Cannot retrieve unlocked object");
}
return _bitmap.Clone() as Image;
}
public void Dispose()
{
if (_disposed)
{
return;
}
if (_locked == false)
{
Lock();
}
_locked = true;
_disposed = true;
_bitmap.Dispose();
}
private void WriteBufferDirectlyToMemory()
{
unsafe
{
int bytesPerPixel = _bitDepth / 8;
int widthInBytes = _bitmapData.Width * bytesPerPixel;
byte* ptrFirstPixel = (byte*)_bitmapData.Scan0;
Parallel.For(0, Height, y =>
{
byte* currentLine = ptrFirstPixel + (y * _bitmapData.Stride);
for (int x = 0; x < widthInBytes; x = x + bytesPerPixel)
{
Color bufferColor = GetPixel(x / bytesPerPixel, y);
if (_bitDepth == 32) // For 32 bpp get Red, Green, Blue and Alpha
{
currentLine[x] = bufferColor.B;
currentLine[x + 1] = bufferColor.G;
currentLine[x + 2] = bufferColor.R;
currentLine[x + 3] = bufferColor.A;
}
if (_bitDepth == 24) // For 24 bpp get Red, Green and Blue
{
currentLine[x] = bufferColor.B;
currentLine[x + 1] = bufferColor.G;
currentLine[x + 2] = bufferColor.R;
}
if (_bitDepth == 8) // For 8 bpp get color value (Red, Green and Blue values are the same)
{
currentLine[x] = bufferColor.B;
}
}
});
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Versions;
namespace Orleans.Runtime.Placement
{
/// <summary>
/// Central point for placement decisions.
/// </summary>
internal class PlacementService : IPlacementContext
{
private const int PlacementWorkerCount = 16;
private readonly PlacementStrategyResolver _strategyResolver;
private readonly PlacementDirectorResolver _directorResolver;
private readonly ILogger<PlacementService> _logger;
private readonly GrainLocator _grainLocator;
private readonly GrainVersionManifest _grainInterfaceVersions;
private readonly CachedVersionSelectorManager _versionSelectorManager;
private readonly ISiloStatusOracle _siloStatusOracle;
private readonly bool _assumeHomogeneousSilosForTesting;
private readonly PlacementWorker[] _workers;
/// <summary>
/// Create a <see cref="PlacementService"/> instance.
/// </summary>
public PlacementService(
IOptionsMonitor<SiloMessagingOptions> siloMessagingOptions,
ILocalSiloDetails localSiloDetails,
ISiloStatusOracle siloStatusOracle,
ILogger<PlacementService> logger,
GrainLocator grainLocator,
GrainVersionManifest grainInterfaceVersions,
CachedVersionSelectorManager versionSelectorManager,
PlacementDirectorResolver directorResolver,
PlacementStrategyResolver strategyResolver)
{
LocalSilo = localSiloDetails.SiloAddress;
_strategyResolver = strategyResolver;
_directorResolver = directorResolver;
_logger = logger;
_grainLocator = grainLocator;
_grainInterfaceVersions = grainInterfaceVersions;
_versionSelectorManager = versionSelectorManager;
_siloStatusOracle = siloStatusOracle;
_assumeHomogeneousSilosForTesting = siloMessagingOptions.CurrentValue.AssumeHomogenousSilosForTesting;
_workers = new PlacementWorker[PlacementWorkerCount];
for (var i = 0; i < PlacementWorkerCount; i++)
{
_workers[i] = new(this);
}
}
public SiloAddress LocalSilo { get; }
public SiloStatus LocalSiloStatus => _siloStatusOracle.CurrentStatus;
/// <summary>
/// Gets or places an activation.
/// </summary>
public Task AddressMessage(Message message)
{
if (message.IsFullyAddressed) return Task.CompletedTask;
if (message.TargetGrain.IsDefault) ThrowMissingAddress();
var grainId = message.TargetGrain;
if (_grainLocator.TryLookupInCache(grainId, out var result))
{
SetMessageTargetPlacement(message, result.ActivationId, result.SiloAddress);
return Task.CompletedTask;
}
var worker = _workers[grainId.GetUniformHashCode() % PlacementWorkerCount];
return worker.AddressMessage(message);
[MethodImpl(MethodImplOptions.NoInlining)]
static void ThrowMissingAddress() => throw new InvalidOperationException("Cannot address a message without a target");
}
private void SetMessageTargetPlacement(Message message, ActivationId activationId, SiloAddress targetSilo)
{
message.TargetActivation = activationId;
message.TargetSilo = targetSilo;
#if DEBUG
if (_logger.IsEnabled(LogLevel.Trace)) _logger.Trace(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message);
#endif
}
public SiloAddress[] GetCompatibleSilos(PlacementTarget target)
{
// For test only: if we have silos that are not yet in the Cluster TypeMap, we assume that they are compatible
// with the current silo
if (_assumeHomogeneousSilosForTesting)
{
return AllActiveSilos;
}
var grainType = target.GrainIdentity.Type;
var silos = target.InterfaceVersion > 0
? _versionSelectorManager.GetSuitableSilos(grainType, target.InterfaceType, target.InterfaceVersion).SuitableSilos
: _grainInterfaceVersions.GetSupportedSilos(grainType).Result;
var compatibleSilos = silos.Intersect(AllActiveSilos).ToArray();
if (compatibleSilos.Length == 0)
{
var allWithType = _grainInterfaceVersions.GetSupportedSilos(grainType).Result;
var versions = _grainInterfaceVersions.GetSupportedSilos(target.InterfaceType, target.InterfaceVersion).Result;
var allWithTypeString = string.Join(", ", allWithType.Select(s => s.ToString())) is string withGrain && !string.IsNullOrWhiteSpace(withGrain) ? withGrain : "none";
var allWithInterfaceString = string.Join(", ", versions.Select(s => s.ToString())) is string withIface && !string.IsNullOrWhiteSpace(withIface) ? withIface : "none";
throw new OrleansException(
$"No active nodes are compatible with grain {grainType} and interface {target.InterfaceType} version {target.InterfaceVersion}. "
+ $"Known nodes with grain type: {allWithTypeString}. "
+ $"All known nodes compatible with interface version: {allWithTypeString}");
}
return compatibleSilos;
}
public SiloAddress[] AllActiveSilos
{
get
{
var result = _siloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToArray();
if (result.Length > 0) return result;
_logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new SiloAddress[] { LocalSilo };
}
}
public IReadOnlyDictionary<ushort, SiloAddress[]> GetCompatibleSilosWithVersions(PlacementTarget target)
{
if (target.InterfaceVersion == 0)
{
throw new ArgumentException("Interface version not provided", nameof(target));
}
var grainType = target.GrainIdentity.Type;
var silos = _versionSelectorManager
.GetSuitableSilos(grainType, target.InterfaceType, target.InterfaceVersion)
.SuitableSilosByVersion;
return silos;
}
private class PlacementWorker
{
private readonly Dictionary<GrainId, GrainPlacementWorkItem> _inProgress = new();
private readonly SingleWaiterAutoResetEvent _workSignal = new();
private readonly ILogger _logger;
private readonly Task _processLoopTask;
private readonly object _lockObj = new();
private readonly PlacementService _placementService;
private List<(Message Message, TaskCompletionSource<bool> Completion)> _messages = new();
public PlacementWorker(PlacementService placementService)
{
_logger = placementService._logger;
_placementService = placementService;
_processLoopTask = Task.Run(ProcessLoop);
}
public Task AddressMessage(Message message)
{
var completion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (_lockObj)
{
_messages ??= new();
_messages.Add((message, completion));
}
_workSignal.Signal();
return completion.Task;
}
private List<(Message Message, TaskCompletionSource<bool> Completion)> GetMessages()
{
lock (_lockObj)
{
if (_messages is { Count: > 0 } result)
{
_messages = null;
return result;
}
return null;
}
}
private async Task ProcessLoop()
{
var toRemove = new List<GrainId>();
while (true)
{
try
{
// Start processing new requests
var messages = GetMessages();
if (messages is not null)
{
foreach (var message in messages)
{
var target = message.Message.TargetGrain;
if (!_inProgress.TryGetValue(target, out var workItem))
{
_inProgress[target] = workItem = new();
}
workItem.Messages.Add(message);
if (workItem.Result is null)
{
// Note that the first message is used as the target to place the message,
// so if subsequent messsages do not agree with the first message's interface
// type or version, then they may be sent to an incompatible silo, which is
// fine since the remote silo will handle that incompatibility.
workItem.Result = GetOrPlaceActivationAsync(message.Message);
// Wake up this processing loop when the task completes
workItem.Result.SignalOnCompleted(_workSignal);
}
}
}
// Complete processing any completed request
foreach (var pair in _inProgress)
{
var workItem = pair.Value;
if (workItem.Result.IsCompleted)
{
AddressWaitingMessages(workItem);
toRemove.Add(pair.Key);
}
}
// Clean up after completed requests
if (toRemove.Count > 0)
{
foreach (var grainId in toRemove)
{
_inProgress.Remove(grainId);
}
toRemove.Clear();
}
}
catch (Exception exception)
{
_logger.LogWarning(exception, "Exception in placement worker");
}
await _workSignal.WaitAsync();
}
}
private void AddressWaitingMessages(GrainPlacementWorkItem completedWorkItem)
{
var resultTask = completedWorkItem.Result;
var messages = completedWorkItem.Messages;
if (resultTask.IsCompletedSuccessfully)
{
foreach (var message in messages)
{
var result = resultTask.Result;
_placementService.SetMessageTargetPlacement(message.Message, result.ActivationId, result.SiloAddress);
message.Completion.TrySetResult(true);
}
messages.Clear();
}
else
{
foreach (var message in messages)
{
message.Completion.TrySetException(OriginalException(resultTask.Exception));
}
messages.Clear();
}
static Exception OriginalException(AggregateException exception)
{
if (exception.InnerExceptions.Count == 1)
{
return exception.InnerException;
}
return exception;
}
}
private async Task<GrainAddress> GetOrPlaceActivationAsync(Message firstMessage)
{
await Task.Yield();
var target = new PlacementTarget(
firstMessage.TargetGrain,
firstMessage.RequestContextData,
firstMessage.InterfaceType,
firstMessage.InterfaceVersion);
var targetGrain = target.GrainIdentity;
var result = await _placementService._grainLocator.Lookup(targetGrain);
if (result is not null)
{
return result;
}
var strategy = _placementService._strategyResolver.GetPlacementStrategy(target.GrainIdentity.Type);
var director = _placementService._directorResolver.GetPlacementDirector(strategy);
var siloAddress = await director.OnAddActivation(strategy, target, _placementService);
// Give the grain locator one last chance to tell us that the grain has already been placed
if (_placementService._grainLocator.TryLookupInCache(targetGrain, out result))
{
return result;
}
ActivationId activationId;
if (strategy.IsDeterministicActivationId)
{
// Use the grain id as the activation id.
activationId = ActivationId.GetDeterministic(target.GrainIdentity);
}
else
{
activationId = ActivationId.NewId();
}
result = GrainAddress.GetAddress(siloAddress, targetGrain, activationId);
_placementService._grainLocator.InvalidateCache(targetGrain);
_placementService._grainLocator.CachePlacementDecision(result);
return result;
}
private class GrainPlacementWorkItem
{
public List<(Message Message, TaskCompletionSource<bool> Completion)> Messages { get; } = new();
public Task<GrainAddress> Result { get; set; }
}
}
}
}
| |
using System;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0})")]
public virtual jQuery FocusOut(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0})")]
public virtual jQuery FocusOut(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0},{1})")]
public virtual jQuery FocusOut(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "focusout" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("focusout({0},{1})")]
public virtual jQuery FocusOut(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "keydown" JavaScript event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
[Template("keydown()")]
public virtual jQuery KeyDown()
{
return null;
}
/// <summary>
/// Bind an event handler to the "keydown" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keydown({0})")]
public virtual jQuery KeyDown(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keydown" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keydown({0})")]
public virtual jQuery KeyDown(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keydown" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keydown({0},{1})")]
public virtual jQuery KeyDown(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keydown" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keydown({0},{1})")]
public virtual jQuery KeyDown(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "keypress" JavaScript event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
[Template("keypress()")]
public virtual jQuery KeyPress()
{
return null;
}
/// <summary>
/// Bind an event handler to the "keypress" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keypress({0})")]
public virtual jQuery KeyPress(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keypress" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keypress({0})")]
public virtual jQuery KeyPress(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keypress" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keypress({0},{1})")]
public virtual jQuery KeyPress(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keypress" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keypress({0},{1})")]
public virtual jQuery KeyPress(object eventData, Action handler)
{
return null;
}
/// <summary>
/// Trigger the "keyup" JavaScript event on an element.
/// </summary>
/// <returns>The jQuery instance</returns>
[Template("keyup()")]
public virtual jQuery KeyUp()
{
return null;
}
/// <summary>
/// Bind an event handler to the "keyup" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keyup({0})")]
public virtual jQuery KeyUp(Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keyup" JavaScript event.
/// </summary>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keyup({0})")]
public virtual jQuery KeyUp(Action handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keyup" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keyup({0},{1})")]
public virtual jQuery KeyUp(object eventData, Delegate handler)
{
return null;
}
/// <summary>
/// Bind an event handler to the "keyup" JavaScript event.
/// </summary>
/// <param name="eventData">An object containing data that will be passed to the event handler.</param>
/// <param name="handler">A function to execute each time the event is triggered.</param>
/// <returns>The jQuery instance</returns>
[Template("keyup({0},{1})")]
public virtual jQuery KeyUp(object eventData, Action handler)
{
return null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite.Replay
{
[TestClass]
public class Replay : SMB2TestBase
{
#region Variables
private Smb2FunctionalClient mainChannelClient;
private Smb2FunctionalClient alternativeChannelClient;
private string sharePath;
private string fileName;
private ushort channelSequence;
#endregion
#region Test Initialize and Cleanup
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Case Initialize and Clean up
protected override void TestInitialize()
{
base.TestInitialize();
sharePath = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare);
fileName = Path.Combine(CreateTestDirectory(sharePath), "Replay_" + Guid.NewGuid() + ".txt");
mainChannelClient = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
alternativeChannelClient = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
}
protected override void TestCleanup()
{
if (mainChannelClient != null)
{
mainChannelClient.Disconnect();
}
if (alternativeChannelClient != null)
{
alternativeChannelClient.Disconnect();
}
base.TestCleanup();
}
#endregion
/// <summary>
/// Delegate to check negotiate response header and payload in this class.
/// </summary>
/// <param name="responseHeader">Response header to be checked</param>
/// <param name="response">Negotiate response payload to be checked</param>
public void ReplayNegotiateResponseChecker(Packet_Header responseHeader, NEGOTIATE_Response response)
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
responseHeader.Status,
"Negotiation should succeed, actually server returns {0}.", Smb2Status.GetStatusCode(responseHeader.Status));
TestConfig.CheckNegotiateCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL, response);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Replay)]
[Description("This test case is designed to test whether server can handle the Replay request with invalid channel sequence correctly.")]
public void BVT_Replay_WriteWithInvalidChannelSequence()
{
///1. mainChannelClient opens a file and write to it.
///2. mainChannelClient loses connection.
///3. ChannelSequence is set to 0x8000 which exceeds the max value.
///4. alternativeChannelClient opens the same file and try to write to it.
///5. Server should fail the write request with STATUS_FILE_NOT_AVAILABLE.
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb30);
TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL);
TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2);
// According to TD, server must support signing when it supports multichannel.
// 3.3.5.5 Receiving an SMB2 SESSION_SETUP Request
// 4. If Connection.Dialect belongs to the SMB 3.x dialect family, IsMultiChannelCapable is TRUE, and the SMB2_SESSION_FLAG_BINDING bit is
// set in the Flags field of the request, the server MUST perform the following:
// If the SMB2_FLAGS_SIGNED bit is not set in the Flags field in the header, the server MUST fail the request with error STATUS_INVALID_PARAMETER.
TestConfig.CheckSigning();
#endregion
Guid clientGuid = Guid.NewGuid();
Capabilities_Values capabilityValue = Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL;
channelSequence = 0;
#region MainChannelClient Create a File
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Start a client from main channel by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT; CREATE.");
mainChannelClient.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
mainChannelClient.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
capabilityValue: capabilityValue,
clientGuid: clientGuid,
checker: ReplayNegotiateResponseChecker);
mainChannelClient.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, false);
mainChannelClient.SessionChannelSequence = channelSequence;
uint treeId;
mainChannelClient.TreeConnect(sharePath, out treeId);
FILEID fileId;
Smb2CreateContextResponse[] createContextResponse;
mainChannelClient.Create(treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out createContextResponse,
RequestedOplockLevel_Values.OPLOCK_LEVEL_BATCH,
new Smb2CreateContextRequest[]
{
new Smb2CreateDurableHandleRequestV2
{
CreateGuid = Guid.NewGuid()
}
});
CheckCreateContextResponses(createContextResponse, new DefaultDurableHandleV2ResponseChecker(BaseTestSite, 0, uint.MaxValue));
#endregion
#region alternativeChannelClient Opens the Previously Created File
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start a client from alternative channel by sending NEGOTIATE request.");
alternativeChannelClient.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutAlternativeIPAddress);
alternativeChannelClient.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
capabilityValue: capabilityValue,
clientGuid: clientGuid,
checker: ReplayNegotiateResponseChecker);
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"The alternative client sends SESSION_SETUP request binding the previous session created by the main channel client.");
alternativeChannelClient.AlternativeChannelSessionSetup(mainChannelClient, TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, false);
alternativeChannelClient.SessionChannelSequence = channelSequence;
#endregion
BaseTestSite.Log.Add(LogEntryKind.TestStep, "The main channel client sends WRITE request to write content to file.");
mainChannelClient.Write(treeId, fileId, " ");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the main channel client by sending DISCONNECT request.");
mainChannelClient.Disconnect();
//Network Disconnection Increase the Channel Sequence
//Server MUST fail SMB2 WRITE, SET_INFO, and IOCTL requests with STATUS_FILE_NOT_AVAILABLE
//if the difference between the ChannelSequence in the header and Open.ChannelSequence is greater than 0x7FFF
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Set the channel sequence of the alternative channel client to an invalid value.");
alternativeChannelClient.SessionChannelSequence = 0x8000;
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"The alternative client sends WRITE request to write content to the file created by the main channel client.");
alternativeChannelClient.Write(treeId,
fileId,
" ",
checker: (header, response) =>
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_FILE_NOT_AVAILABLE,
header.Status,
"Server MUST fail the {0} request with STATUS_FILE_NOT_AVAILABLE if the difference between the ChannelSequence in the header and Open.ChannelSequence is greater than 0x7FFF. " +
"Actually server returns {1}.",
header.Command,
Smb2Status.GetStatusCode(header.Status));
},
isReplay: true);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the alternative channel client by sending TREE_DISCONNECT and LOG_OFF requests.");
alternativeChannelClient.TreeDisconnect(treeId);
alternativeChannelClient.LogOff();
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Replay)]
[Description("This test case is designed to test whether server can handle Replay operation correctly.")]
public void BVT_Replay_ReplayCreate()
{
///1. mainChannelClient opens a file
///2. mainChannelClient loses connection.
///3. ChannelSequence is increased by 1.
///4. alternativeChannelClient opens the same file with replay flag set.
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb30);
TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL);
TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2);
// According to TD, server must support signing when it supports multichannel.
// 3.3.5.5 Receiving an SMB2 SESSION_SETUP Request
// 4. If Connection.Dialect belongs to the SMB 3.x dialect family, IsMultiChannelCapable is TRUE, and the SMB2_SESSION_FLAG_BINDING bit is
// set in the Flags field of the request, the server MUST perform the following:
// If the SMB2_FLAGS_SIGNED bit is not set in the Flags field in the header, the server MUST fail the request with error STATUS_INVALID_PARAMETER.
TestConfig.CheckSigning();
#endregion
Guid durableHandleGuid = Guid.NewGuid();
Guid clientGuid = Guid.NewGuid();
Capabilities_Values capabilityValue = Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL;
#region MainChannelClient Finish Session Setup and AlternativeChannelClient Establish Another Channel
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Start a client from main channel by sending the following requests: NEGOTIATE; SESSION_SETUP");
mainChannelClient.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
mainChannelClient.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
capabilityValue: capabilityValue,
clientGuid: clientGuid,
checker: ReplayNegotiateResponseChecker);
mainChannelClient.SessionSetup(TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, false);
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Start another client from alternative channel by sending the following requests: NEGOTIATE SESSION_SETUP");
alternativeChannelClient.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutAlternativeIPAddress);
alternativeChannelClient.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
capabilityValue: capabilityValue,
clientGuid: clientGuid,
checker: ReplayNegotiateResponseChecker);
alternativeChannelClient.AlternativeChannelSessionSetup(mainChannelClient, TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, false);
#endregion
#region MainChannelClient Create a File with DurableHandleV1 and BatchOpLock
uint treeId;
BaseTestSite.Log.Add(LogEntryKind.TestStep, "The main channel client sends TREE_CONNECT request.");
mainChannelClient.TreeConnect(sharePath, out treeId);
FILEID fileId;
Smb2CreateContextResponse[] createContextResponse;
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"The main channel client sends CREATE request with SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 create context.");
mainChannelClient.Create(treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out createContextResponse,
RequestedOplockLevel_Values.OPLOCK_LEVEL_BATCH,
new Smb2CreateContextRequest[]
{
new Smb2CreateDurableHandleRequestV2
{
CreateGuid = durableHandleGuid
}
});
CheckCreateContextResponses(createContextResponse, new DefaultDurableHandleV2ResponseChecker(BaseTestSite, 0, uint.MaxValue));
#endregion
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the main channel client by sending DISCONNECT request.");
mainChannelClient.Disconnect();
alternativeChannelClient.SessionChannelSequence++;
#region AlternativeChannelClient Opens the Previously Created File with Replay Flag Set
FILEID alternativeFileId;
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"The alternative client sends CREATE request with replay flag set and SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 to open the same file with the main channel client.");
alternativeChannelClient.Create(treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
Packet_Header_Flags_Values.FLAGS_REPLAY_OPERATION | (testConfig.SendSignedRequest ? Packet_Header_Flags_Values.FLAGS_SIGNED : Packet_Header_Flags_Values.NONE),
out alternativeFileId,
out createContextResponse,
RequestedOplockLevel_Values.OPLOCK_LEVEL_BATCH,
new Smb2CreateContextRequest[]
{
new Smb2CreateDurableHandleRequestV2
{
CreateGuid = durableHandleGuid
}
});
CheckCreateContextResponses(createContextResponse, new DefaultDurableHandleV2ResponseChecker(BaseTestSite, 0, uint.MaxValue));
#endregion
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the alternative channel client by sending the following requests: TREE_DISCONNECT; LOG_OFF");
alternativeChannelClient.TreeDisconnect(treeId);
alternativeChannelClient.LogOff();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NSpec;
using NSpec.Domain;
using NUnit.Framework;
using describe_OtherNameSpace;
using describe_SomeNameSpace;
using Moq;
namespace NSpecSpecs
{
public class SpecClass : nspec
{
public void public_method() { }
private void private_method() { }
}
public class AnotherSpecClass : nspec
{
void public_method() { }
}
public class NonSpecClass { }
public class SpecClassWithNoVoidMethods : nspec
{
string parameter_less_method() { return ""; }
}
public class SpecClassWithNoParameterLessMethods : nspec
{
void private_method(string parameter) { }
public void public_method(string parameter) { }
}
[TestFixture]
[Category("SpecFinder")]
public class without_filtering : when_finding_specs
{
[SetUp]
public void setup()
{
GivenDllContains();
}
[Test]
public void it_should_get_types_from_reflection()
{
reflector.Verify(r => r.GetTypesFrom());
}
[Test]
public void it_should_include_classes_that_implement_nspec_and_have_paramterless_void_methods()
{
GivenDllContains(typeof(SpecClass));
finder.SpecClasses().should_contain(typeof(SpecClass));
}
[Test]
public void it_should_exclude_classes_that_inherit_from_nspec_but_have_no_parameterless_methods()
{
GivenDllContains(typeof(SpecClassWithNoParameterLessMethods));
finder.SpecClasses().should_be_empty();
}
[Test]
public void it_should_exclude_classes_that_do_not_inherit_from_nspec()
{
GivenDllContains(typeof(NonSpecClass));
finder.SpecClasses().should_be_empty();
}
[Test]
public void it_should_exclude_classes_that_have_no_void_methods()
{
GivenDllContains(typeof(SpecClassWithNoVoidMethods));
finder.SpecClasses().should_be_empty();
}
}
[TestFixture]
[Category("SpecFinder")]
public class when_filtering_specs : when_finding_specs
{
[Test]
public void it_should_filter_in()
{
GivenDllContains(typeof(AnotherSpecClass));
GivenFilter(typeof(AnotherSpecClass).Name);
finder.SpecClasses().should_contain(typeof(AnotherSpecClass));
}
[Test]
public void it_should_filter_out()
{
GivenDllContains(typeof(SpecClass));
GivenFilter(typeof(AnotherSpecClass).Name);
finder.SpecClasses().should_be_empty();
}
}
[TestFixture]
[Category("SpecFinder")]
public class when_finding_specs_based_on_regex : when_finding_specs
{
[SetUp]
public void Setup()
{
GivenDllContains(typeof(SomeClass),
typeof(SomeDerivedClass),
typeof(SomeClassInOtherNameSpace),
typeof(SomeDerivedDerivedClass));
}
[Test]
public void it_should_find_all_specs_if_regex_is_not_specified()
{
GivenFilter("");
TheSpecClasses()
.should_contain(typeof(SomeClass))
.should_contain(typeof(SomeDerivedClass))
.should_contain(typeof(SomeClassInOtherNameSpace));
}
[Test]
public void it_should_find_specs_for_derived_class_and_include_base_class()
{
GivenFilter("DerivedClass$");
TheSpecClasses()
.should_contain(typeof(SomeClass))
.should_contain(typeof(SomeDerivedClass))
.should_contain(typeof(SomeDerivedDerivedClass))
.should_not_contain(typeof(SomeClassInOtherNameSpace));
TheSpecClasses().Count().should_be(3);
}
[Test]
public void it_should_find_specs_that_contain_namespace()
{
GivenFilter("describe_SomeNameSpace");
TheSpecClasses()
.should_contain(typeof(SomeClass))
.should_contain(typeof(SomeDerivedClass))
.should_not_contain(typeof(SomeClassInOtherNameSpace));
}
[Test]
public void it_should_find_distinct_specs()
{
GivenFilter("Derived");
TheSpecClasses()
.should_contain(typeof(SomeClass))
.should_contain(typeof(SomeDerivedClass))
.should_contain(typeof(SomeDerivedDerivedClass));
TheSpecClasses().Count().should_be(3);
}
}
public class when_finding_specs
{
protected void GivenDllContains(params Type[] types)
{
reflector = new Mock<IReflector>();
reflector.Setup(r => r.GetTypesFrom()).Returns(types);
someDLL = "an nspec project dll";
finder = new SpecFinder(reflector.Object);
}
protected void GivenFilter(string filter)
{
finder = new SpecFinder(reflector.Object, filter);
}
protected IEnumerable<Type> TheSpecClasses()
{
return finder.SpecClasses();
}
protected ISpecFinder finder;
protected Mock<IReflector> reflector;
protected string someDLL;
}
}
namespace describe_SomeNameSpace
{
class SomeClass : nspec
{
void context_method()
{
}
}
class SomeDerivedClass : SomeClass
{
void context_method()
{
}
}
class SomeDerivedDerivedClass : SomeClass
{
void context_method()
{
}
}
}
namespace describe_OtherNameSpace
{
class SomeClassInOtherNameSpace : nspec
{
void context_method()
{
}
}
}
| |
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\GameLogic
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:39
#region Using directives
using DungeonQuest.Game;
using DungeonQuest.Graphics;
using DungeonQuest.Helpers;
using DungeonQuest.Sounds;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;
using Texture = DungeonQuest.Graphics.Texture;
using DungeonQuest.Shaders;
#endregion
namespace DungeonQuest.GameLogic
{
/// <summary>
/// Game manager
/// </summary>
public class GameManager
{
#region Types enum
/// <summary>
/// Animated types
/// </summary>
public enum AnimatedTypes
{
// Player
Hero,
// Monsters
Goblin,
GoblinMaster,
GoblinWizard,
Ogre,
BigOgre,
} // enum AnimatedTypes
/// <summary>
/// Static Types
/// </summary>
public enum StaticTypes
{
// Static geometry
Flare,
DoorWall,
Door,
Treasure,
// Note: We can collect the key, club, sword and big sword!
Key,
// Weapons
Club,
Sword,
BigSword,
} // enum StaticTypes
#endregion
#region Health, Damage, etc. settings
/// <summary>
/// Monster hitpoints
/// </summary>
public static readonly float[] MonsterHitpoints = new float[]
{
100, // Hero (unused, just to match enum)
10,//10, // Goblin
15,//15, // GoblinMaster
8,//5, // GoblinWizard,
32,//30, // Ogre
60,//50, // BigOgre
};
/// <summary>
/// Monster damages
/// </summary>
public static readonly float[] MonsterDamages = new float[]
{
10, // Hero (unused, just to match enum)
5,//6,//4, // Goblin
7,//8,//6, // GoblinMaster
0,//not used here: 10, // GoblinWizard,
9,//10,//8, // Ogre
15,//16,//14, // BigOgre
};
/// <summary>
/// Monster weapon drop percentages
/// </summary>
public static readonly float[,] MonsterWeaponDropPercentages = new float[,]
{
{0, 0, 0}, // Hero (unused, just to match enum)
{0.14f, 0.02f, 0.001f}, // Goblin
{0.05f, 0.5f, 0.006f}, // GoblinMaster
{0.085f, 0.25f, 0.05f}, // GoblinWizard,
{0.02f, 0.15f, 0.35f}, // Ogre
{0.01f, 0.125f, 0.625f}, // BigOgre
};
/// <summary>
/// Get drop percentages
/// </summary>
/// <param name="type">Type</param>
/// <returns>Drop object</returns>
public static AnimatedGameObject.DropObject GetDropPercentages(
AnimatedTypes type)
{
for (int i = 0; i < 3; i++)
if (RandomHelper.GetRandomFloat(0, 1) <
MonsterWeaponDropPercentages[(int)type, i])
return (AnimatedGameObject.DropObject)
((int)AnimatedGameObject.DropObject.Club + i);
return AnimatedGameObject.DropObject.None;
} // GetDropPercentages(type)
#endregion
#region Variables
/// <summary>
/// Cave model
/// </summary>
ColladaModel caveModel = null;
/// <summary>
/// Static models
/// </summary>
public List<ColladaModel> staticModels =
new List<ColladaModel>();
/// <summary>
/// Animated models
/// </summary>
public List<AnimatedColladaModel> animatedModels =
new List<AnimatedColladaModel>();
/// <summary>
/// Static objects
/// </summary>
public static List<StaticGameObject> staticObjects =
new List<StaticGameObject>();
/// <summary>
/// Animated objects
/// </summary>
public static List<AnimatedGameObject> animatedObjects =
new List<AnimatedGameObject>();
/// <summary>
/// Helper texture for the Gears of War blood effect :D
/// </summary>
public static Texture screenBorder = null;
/// <summary>
/// Blood border effect, just set it to 1 and it will be bloody ^^
/// </summary>
public static float bloodBorderEffect = 0;
/// <summary>
/// Blood border color, can be replaced by other effects (like new level).
/// </summary>
public static Color bloodBorderColor = Color.Red;
#endregion
#region Reset
/// <summary>
/// Reset
/// </summary>
public static void Reset()
{
foreach (AnimatedGameObject obj in animatedObjects)
obj.Reset();
bloodBorderEffect = 0;
bloodBorderColor = Color.Red;
} // Reset()
#endregion
#region Weapon projectiles
/// <summary>
/// Current weapon projectiles.
/// </summary>
static List<Projectile> weaponProjectiles = new List<Projectile>();
/// <summary>
/// Add weapon projectile
/// </summary>
/// <param name="weaponType">Weapon</param>
/// <param name="position">Pos</param>
/// <param name="ownProjectile">True for player, false for enemy</param>
public static void AddWeaponProjectile(
//Projectile.WeaponTypes weaponType,
Vector3 position)
//bool ownProjectile)
{
weaponProjectiles.Add(
new Projectile(//weaponType,
position));//, ownProjectile));
} // AddWeaponProjectile(weaponType, position, direction)
/// <summary>
/// Render weapon projectiles
/// </summary>
private void RenderWeaponProjectiles()
{
for (int num = 0; num < weaponProjectiles.Count; num++)
{
// Remove weapon projectile if we are done
if (weaponProjectiles[num].Render())
{
weaponProjectiles.RemoveAt(num);
num--;
} // if
} // for
} // RenderWeaponProjectiles()
#endregion
#region Constructor
/// <summary>
/// Create game manager
/// </summary>
public GameManager()
{
// Load the cave and fill in all static game items (will be done
// there in the loading process).
caveModel = new ColladaModel("Cave");
caveModel.material.ambientColor = Material.DefaultAmbientColor;
// Load all animated models (player and monsters)
for (int i = 0; i <= (int)AnimatedTypes.BigOgre; i++)
animatedModels.Add(new AnimatedColladaModel(
//tst: "GoblinWizard"));
((AnimatedTypes)i).ToString()));
// Also load all static models
for (int i = 0; i <= (int)StaticTypes.BigSword; i++)
staticModels.Add(new ColladaModel(
((StaticTypes)i).ToString()));
screenBorder = new Texture("ScreenBorder");
} // GameManager()
#endregion
#region Add text message
/// <summary>
/// Text types
/// </summary>
public enum TextTypes
{
Normal,
LevelUp,
GotWeapon,
GotKey,
Damage,
Died,
} // enum TextTypes
/// <summary>
/// Colors for each text type
/// </summary>
static readonly Color[] TextTypeColors = new Color[]
{
new Color(200, 200, 200),//Color.White,
Color.Yellow,
Color.Orange,
Color.LightBlue,
Color.Red,
Color.Red,
};
class FadeupText
{
public string text;
public Color color;
public float showTimeMs;
public const float MaxShowTimeMs = 3750;//3000;
public FadeupText(string setText, Color setColor)
{
text = setText;
color = setColor;
showTimeMs = MaxShowTimeMs;
} // TimeFadeupText(setText, setShowTimeMs)
} // TimeFadeupText
static List<FadeupText> fadeupTexts = new List<FadeupText>();
/// <summary>
/// Add text message
/// </summary>
/// <param name="message">Message</param>
/// <param name="type">Type</param>
public static void AddTextMessage(string message, TextTypes type)
{
// Check number of texts that were added in the last 400 ms!
int numOfRecentTexts = 0;
for (int num = 0; num < fadeupTexts.Count; num++)
{
FadeupText fadeupText = fadeupTexts[num];
if (fadeupText.showTimeMs > FadeupText.MaxShowTimeMs - 400)
numOfRecentTexts++;
} // for (num)
fadeupTexts.Add(new FadeupText(message, TextTypeColors[(int)type]));
// Add offset to this text to be displayed below the already existing
// texts! This fixes the overlapping texts!
fadeupTexts[fadeupTexts.Count - 1].showTimeMs += numOfRecentTexts * 400;
} // AddTextMessage(message, type)
/// <summary>
/// Render all time fadeup effects, move them up and fade them out.
/// </summary>
public void RenderTimeFadeupEffects()
{
for (int num = 0; num < fadeupTexts.Count; num++)
{
FadeupText fadeupText = fadeupTexts[num];
fadeupText.showTimeMs -= BaseGame.ElapsedTimeThisFrameInMs;
if (fadeupText.showTimeMs < 0)
{
fadeupTexts.Remove(fadeupText);
num--;
} // if
else
{
// Fade out
float alpha = 1.0f;
if (fadeupText.showTimeMs < 1500)
alpha = fadeupText.showTimeMs / 1500.0f;
// Move up
float moveUpAmount =
(FadeupText.MaxShowTimeMs - fadeupText.showTimeMs) /
FadeupText.MaxShowTimeMs;
// Calculate screen position
TextureFont.WriteTextCentered(BaseGame.Width / 2,
BaseGame.Height / 3 - (int)(moveUpAmount * BaseGame.Height / 3),
fadeupText.text,
//ColorHelper.ApplyAlphaToColor(fadeupText.color, alpha),
//2.25f);
fadeupText.color, alpha);
} // else
} // for
} // RenderTimeFadeupEffects()
#endregion
#region Run
//obs: bool firstTimeWeaponHelp = false;
public static Vector3 doorPosition = Vector3.Zero;
public static Vector3 treasurePosition = Vector3.Zero;
/// <summary>
/// Run
/// </summary>
public void Run(bool showUI)
{
#region Init glow
//if (Input.Keyboard.IsKeyDown(Keys.LeftAlt) == false)
{
// Start glow shader
BaseGame.GlowShader.Start();
// Clear background with white color, looks much cooler for the
// post screen glow effect.
//BaseGame.Device.Clear(Color.Black);
PostScreenGlow.sceneMapTexture.Clear(Color.Black);
} // if (Input.Keyboard.IsKeyDown)
#endregion
#region Init variables
// Restart with start or space
if (Input.GamePad.Buttons.Start == ButtonState.Pressed ||
Input.KeyboardEnterJustPressed)
{
// Reset everything
Player.Reset();
BaseGame.camera.Reset();
GameManager.Reset();
} // if
// Render goblin always in center, but he is really big, bring him
// down to a more normal size that fits better in our test scene.
Matrix renderMatrix = Matrix.Identity;// Matrix.CreateScale(0.1f);
// Restore z buffer state
BaseGame.Device.RenderState.DepthBufferEnable = true;
BaseGame.Device.RenderState.DepthBufferWriteEnable = true;
// Make sure we got the closest 6 lights, only has to be checked
// once per frame.
Vector3 camPos = BaseGame.CameraPos;
LightManager.FindClosestLights(camPos);
// Render the player first
AnimatedColladaModel playerModel =
animatedModels[(int)AnimatedTypes.Hero];
Matrix playerMatrix =
Matrix.CreateRotationZ(BaseGame.camera.PlayerRotation) *
Matrix.CreateTranslation(BaseGame.camera.PlayerPos);
AnimatedColladaModel.currentAnimatedObject = BaseGame.camera.playerObject;
Vector3 playerPos = BaseGame.camera.PlayerPos + new Vector3(0, 0, 0.75f);
// Is player close to the door and he got the key?
if (Vector3.Distance(playerPos, doorPosition) < 4.5f &&
Player.gotKey)
{
// Then remove door, allow walking through!
foreach (StaticGameObject model in staticObjects)
if (model.type == StaticTypes.Door)
{
staticObjects.Remove(model);
Sound.Play(Sound.Sounds.HitClub);
Sound.Play(Sound.Sounds.Click);
GameManager.AddTextMessage("Entering Level 2 ..",
GameManager.TextTypes.LevelUp);
GameManager.AddTextMessage("Find the Treasure!",
GameManager.TextTypes.LevelUp);
break;
} // foreach if (model.type)
} // if (Vector3.Distance)
int weaponModelNum = Player.currentWeapon == Player.WeaponTypes.Club ?
(int)StaticTypes.Club :
Player.currentWeapon == Player.WeaponTypes.Sword ?
(int)StaticTypes.Sword : (int)StaticTypes.BigSword;
Matrix weaponMatrix =
playerModel.HandlePlayerFlareAndWeapon() *
playerMatrix;
#endregion
#region Generate and render shadows
// Generate shadows
ShaderEffect.shadowMapping.GenerateShadows(
delegate
{
// First render all animated models
playerModel.GenerateShadow(playerMatrix,
BaseGame.camera.PlayerBlendStates);
foreach (AnimatedGameObject model in animatedObjects)
if ((camPos - model.positionMatrix.Translation).LengthSquared() <
15 * 15)//60 * 60)
{
AnimatedColladaModel.currentAnimatedObject = model;
if ((int)model.type < animatedModels.Count)
animatedModels[(int)model.type].GenerateShadow(
model.positionMatrix,
model.blendedStates);
} // foreach if (camPos)
// And then all static models!
staticModels[weaponModelNum].GenerateShadow(weaponMatrix);
foreach (StaticGameObject model in staticObjects)
if ((camPos - model.positionMatrix.Translation).LengthSquared() <
15 * 15)//60 * 60)
{
Matrix objectMatrix = model.positionMatrix;
// For collectable items replace matrix, rotate around
if (model.IsCollectable)
objectMatrix =
Matrix.CreateScale(1.5f) *
Matrix.CreateRotationZ(Player.GameTime / 0.556f) *
Matrix.CreateTranslation(objectMatrix.Translation +
new Vector3(0, 0,
(float)Math.Sin(Player.GameTime / 0.856f) * 0.15f));
staticModels[(int)model.type].GenerateShadow(objectMatrix);
} // foreach if (camPos)
});
// Render shadows
ShaderEffect.shadowMapping.RenderShadows(
delegate
{
// Throw shadows on the cave
caveModel.UseShadow(
// Note: We have to rescale ourselfs, we use the world matrix here!
// Below it does not matter for Render because the shader handles
// everything. Also move up a little to fix ground error.
Matrix.CreateScale(100)*
Matrix.CreateTranslation(new Vector3(0, 0, 0.05f)));
// And all animated and static models
playerModel.UseShadow(playerMatrix,
BaseGame.camera.PlayerBlendStates);
foreach (AnimatedGameObject model in animatedObjects)
if ((camPos - model.positionMatrix.Translation).LengthSquared() <
15 * 15)//20 * 20)
{
AnimatedColladaModel.currentAnimatedObject = model;
if ((int)model.type < animatedModels.Count)
animatedModels[(int)model.type].UseShadow(
model.positionMatrix,
model.blendedStates);
} // foreach if (camPos)
// And finally all static models!
staticModels[weaponModelNum].UseShadow(weaponMatrix);
foreach (StaticGameObject model in staticObjects)
if ((camPos - model.positionMatrix.Translation).LengthSquared() <
15 * 15)//20 * 20)
{
Matrix objectMatrix = model.positionMatrix;
// For collectable items replace matrix, rotate around
if (model.IsCollectable)
objectMatrix =
Matrix.CreateScale(1.5f) *
Matrix.CreateRotationZ(Player.GameTime / 0.556f) *
Matrix.CreateTranslation(objectMatrix.Translation +
new Vector3(0, 0,
(float)Math.Sin(Player.GameTime / 0.856f) * 0.15f));
staticModels[(int)model.type].UseShadow(objectMatrix);
} // foreach if (camPos)
});
#endregion
#region Render cave
// Enable culling for the cave (faster rendering!)
BaseGame.Device.RenderState.CullMode = CullMode.CullCounterClockwiseFace;
//*tst
caveModel.Render(Matrix.Identity);//Matrix.CreateTranslation(0, 0, +1));
//*/
// Disable culling, some models use backsides (for swords, etc.)
// This should be fixed on the model level and not here, but there is no
// time.
BaseGame.Device.RenderState.CullMode = CullMode.None;
#endregion
#region Render player and his weapon
// Render player
playerModel.Render(playerMatrix, BaseGame.camera.PlayerBlendStates);
// Handle player flare and weapon, which have to be updated with
// the bones.
staticModels[weaponModelNum].Render(weaponMatrix);
// Set our flare light as shadow mapping light position.
// This is very important for our shadow mapping.
ShaderEffect.shadowMapping.SetVirtualLightPos(
AnimatedColladaModel.finalPlayerFlarePos);
#endregion
#region Render static models
// Render all static and animated models and update the closest lights
// for each of them. Note: We only have to render the visible stuff,
// which is basically everything in a 60m radius.
foreach (StaticGameObject model in staticObjects)
if ((camPos - model.positionMatrix.Translation).LengthSquared() <
50 * 50)//60 * 60)
{
LightManager.FindClosestLights(model.positionMatrix.Translation);
Matrix objectMatrix = model.positionMatrix;
// For collectable items replace matrix, rotate around
if (model.IsCollectable)
objectMatrix =
Matrix.CreateScale(1.5f) *
Matrix.CreateRotationZ(Player.GameTime/0.556f) *
Matrix.CreateTranslation(objectMatrix.Translation+
new Vector3(0, 0,
(float)Math.Sin(Player.GameTime/0.856f)*0.15f));
staticModels[(int)model.type].Render(objectMatrix);
// If player is close enough, collect this item (if it is a key,
// club, sword or big sword).
if (model.IsCollectable && Vector3.Distance(
playerPos, model.positionMatrix.Translation) < 1.0f)//1.25f)
{
if (model.type == StaticTypes.Key)
{
Player.gotKey = true;
// Show text message
GameManager.AddTextMessage("You got the key, find "+
"the door to the second level!", TextTypes.GotKey);
// Play level up sound effect for got key
Sound.Play(Sound.Sounds.LevelUp);
} // if (model.type)
else
{
if (model.type == StaticTypes.Club)
Player.gotWeapons[0] = true;
else if (model.type == StaticTypes.Sword &&
Player.gotWeapons[1] == false)
{
Player.gotWeapons[1] = true;
Player.currentWeapon = Player.WeaponTypes.Sword;
} // else if
else if (model.type == StaticTypes.BigSword &&
Player.gotWeapons[2] == false)
{
Player.gotWeapons[2] = true;
Player.currentWeapon = Player.WeaponTypes.BigSword;
} // else if
// Show text message
GameManager.AddTextMessage("You collected a "+
StringHelper.SplitFunctionNameToWordString(
model.type.ToString()) + ".", TextTypes.GotWeapon);
//Too annoying every time!
/*ignore, we autochange weapon now!
if (firstTimeWeaponHelp == false)
{
firstTimeWeaponHelp = true;
GameManager.AddTextMessage("Change weapon with " +
"Q/E/MouseWheel or shoulder buttons", TextTypes.Normal);
} // if (firstTimeWeaponHelp)
*/
// Play one of the whosh sounds for the new weapon
Sound.Play(Sound.Sounds.Whosh);
// And add a click effect to make it sound a little different!
Sound.Play(Sound.Sounds.Click);
} // else
// Remove this object
staticObjects.Remove(model);
// Get outta here, we modified the collection
break;
} // if (Vector3.Distance)
} // foreach if (camPos)
#endregion
#region Render animated models
//int goblinNum = 0;
foreach (AnimatedGameObject model in animatedObjects)
if ((camPos - model.positionMatrix.Translation).LengthSquared() <
50 * 50)//60 * 60)
{
//goblinNum++;
//TextureFont.WriteText(100, 100+goblinNum*25,
// "state=" + animatedObjects[goblinNum].state);
LightManager.FindClosestLights(model.positionMatrix.Translation);
if (Player.GameOver == false &&
Player.GameTime >= 0)
{
model.UpdateMonsterAI();
model.UpdateState();
} // if (Player.GameOver)
//TextureFont.WriteText(300, 100 + goblinNum * 25,
// "state=" + animatedObjects[goblinNum].state);
AnimatedColladaModel.currentAnimatedObject = model;
if ((int)model.type < animatedModels.Count)
animatedModels[(int)model.type].Render(model.positionMatrix,
model.blendedStates);
// Update weapon pos (important for the wizard)
model.weaponPos =
animatedModels[(int)model.type].GetWeaponPos(model.positionMatrix);
} // foreach if (camPos)
if (bloodBorderEffect > 0)
{
// Show also on border
GameManager.screenBorder.RenderOnScreen(
BaseGame.ResolutionRect,
GameManager.screenBorder.GfxRectangle,
ColorHelper.ApplyAlphaToColor(bloodBorderColor, bloodBorderEffect));
if (bloodBorderColor == Color.Green)
{
// Formular: (1/speed)*1000*15 ms
float speed = 10;
int msToCheck = (int)(speed > 0 ?
(1 / speed) * 1000 * 15 : 1000.0f);
// Don't go above 500, looks bad
if (msToCheck > 500)
msToCheck = 500;
//*tst disabling
if (BaseGame.EveryMs(msToCheck))//75))
{
EffectManager.AddEffect(
BaseGame.camera.PlayerPos + new Vector3(0, 0, 1.5f) +
RandomHelper.GetRandomVector3(-0.275f, 0.275f),
EffectManager.EffectType.Smoke, 1.5f,
RandomHelper.GetRandomFloat(0, (float)Math.PI * 2.0f));
} // if (BaseGame.EveryMs)
} // if (bloodBorderColor)
bloodBorderEffect -= BaseGame.MoveFactorPerSecond;// *2.5f;
} // if (bloodBorderEffect)
#endregion
#region Render shadow map
ShaderEffect.shadowMapping.ShowShadows();
#endregion
#region Render lights and effects
LightManager.RenderAllCloseLightEffects();
RenderWeaponProjectiles();
// We have to render the effects ourselfs because
// it is usually done in DungeonQuestGame!
// Finally render all effects (before applying post screen effects)
BaseGame.effectManager.HandleAllEffects();
#endregion
#region Handle UI and rest of game logic
if (showUI)
{
// Show UI
UIManager.DrawUI();
// Show extra text messages in the center
RenderTimeFadeupEffects();
// Handle the game logic and show the victory/defeat screen.
Player.HandleGameLogic();
} // if (showUI)
else
{
// Stop everything
Player.StopTime();
} // else
/*tst
if (Input.Keyboard.IsKeyDown(Keys.LeftShift) ||
Input.GamePadAPressed)
{
ShaderEffect.shadowMapping.shadowMapTexture.RenderOnScreen(
new Rectangle(10, 10, 256, 256));
ShaderEffect.shadowMapping.shadowMapBlur.SceneMapTexture.
RenderOnScreen(
new Rectangle(10 + 256 + 10, 10, 256, 256));
} // if (Input.Keyboard.IsKeyDown)
*/
#endregion
#region Finish with glow
//if (Input.Keyboard.IsKeyDown(Keys.LeftAlt) == false)
{
// And finally show glow shader on top of everything
BaseGame.GlowShader.Show();
} // if (Input.Keyboard.IsKeyDown)
#endregion
} // Run()
#endregion
#region Add
/// <summary>
/// Add
/// </summary>
/// <param name="type">Type</param>
/// <param name="positionMatrix">Position matrix</param>
public static void Add(StaticTypes type, Matrix positionMatrix)
{
staticObjects.Add(new StaticGameObject(type, positionMatrix));
} // Add(type, positionMatrix)
/// <summary>
/// Add
/// </summary>
/// <param name="type">Type</param>
/// <param name="positionMatrix">Position matrix</param>
public static void Add(AnimatedTypes type, Matrix positionMatrix)
{
animatedObjects.Add(new AnimatedGameObject(type, positionMatrix));
} // Add(type, positionMatrix)
/// <summary>
/// Add
/// </summary>
/// <param name="type">Type</param>
/// <param name="positionMatrix">Position matrix</param>
public static void Add(AnimatedTypes type, Matrix positionMatrix,
AnimatedGameObject.DropObject dropObject)
{
animatedObjects.Add(new AnimatedGameObject(type, positionMatrix,
dropObject));
} // Add(type, positionMatrix)
#endregion
} // class GameManager
} // namespace DungeonQuest.GameLogic
| |
// 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.Data.SqlTypes;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System.Data.SqlClient
{
internal sealed class SqlBuffer
{
internal enum StorageType
{
Empty = 0,
Boolean,
Byte,
DateTime,
Decimal,
Double,
Int16,
Int32,
Int64,
Money,
Single,
String,
SqlBinary,
SqlCachedBuffer,
SqlGuid,
SqlXml,
Date,
DateTime2,
DateTimeOffset,
Time,
}
internal struct DateTimeInfo
{
// This is used to store DateTime
internal int daypart;
internal int timepart;
}
internal struct NumericInfo
{
// This is used to store Decimal data
internal int data1;
internal int data2;
internal int data3;
internal int data4;
internal byte precision;
internal byte scale;
internal bool positive;
}
internal struct TimeInfo
{
internal long ticks;
internal byte scale;
}
internal struct DateTime2Info
{
internal int date;
internal TimeInfo timeInfo;
}
internal struct DateTimeOffsetInfo
{
internal DateTime2Info dateTime2Info;
internal short offset;
}
[StructLayout(LayoutKind.Explicit)]
internal struct Storage
{
[FieldOffset(0)]
internal bool _boolean;
[FieldOffset(0)]
internal byte _byte;
[FieldOffset(0)]
internal DateTimeInfo _dateTimeInfo;
[FieldOffset(0)]
internal double _double;
[FieldOffset(0)]
internal NumericInfo _numericInfo;
[FieldOffset(0)]
internal short _int16;
[FieldOffset(0)]
internal int _int32;
[FieldOffset(0)]
internal long _int64; // also used to store Money, UtcDateTime, Date , and Time
[FieldOffset(0)]
internal float _single;
[FieldOffset(0)]
internal TimeInfo _timeInfo;
[FieldOffset(0)]
internal DateTime2Info _dateTime2Info;
[FieldOffset(0)]
internal DateTimeOffsetInfo _dateTimeOffsetInfo;
}
private bool _isNull;
private StorageType _type;
private Storage _value;
private object _object; // String, SqlBinary, SqlCachedBuffer, SqlGuid, SqlString, SqlXml
internal SqlBuffer()
{
}
private SqlBuffer(SqlBuffer value)
{ // Clone
// value types
_isNull = value._isNull;
_type = value._type;
// ref types - should also be read only unless at some point we allow this data
// to be mutable, then we will need to copy
_value = value._value;
_object = value._object;
}
internal bool IsEmpty
{
get
{
return (StorageType.Empty == _type);
}
}
internal bool IsNull
{
get
{
return _isNull;
}
}
internal StorageType VariantInternalStorageType
{
get { return _type; }
}
internal bool Boolean
{
get
{
ThrowIfNull();
if (StorageType.Boolean == _type)
{
return _value._boolean;
}
return (bool)this.Value; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._boolean = value;
_type = StorageType.Boolean;
_isNull = false;
}
}
internal byte Byte
{
get
{
ThrowIfNull();
if (StorageType.Byte == _type)
{
return _value._byte;
}
return (byte)this.Value; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._byte = value;
_type = StorageType.Byte;
_isNull = false;
}
}
internal byte[] ByteArray
{
get
{
ThrowIfNull();
return this.SqlBinary.Value;
}
}
internal DateTime DateTime
{
get
{
ThrowIfNull();
if (StorageType.Date == _type)
{
return DateTime.MinValue.AddDays(_value._int32);
}
if (StorageType.DateTime2 == _type)
{
return new DateTime(GetTicksFromDateTime2Info(_value._dateTime2Info));
}
if (StorageType.DateTime == _type)
{
return SqlTypeWorkarounds.SqlDateTimeToDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart);
}
return (DateTime)this.Value; // anything else we haven't thought of goes through boxing.
}
}
internal decimal Decimal
{
get
{
ThrowIfNull();
if (StorageType.Decimal == _type)
{
if (_value._numericInfo.data4 != 0 || _value._numericInfo.scale > 28)
{
throw new OverflowException(SQLResource.ConversionOverflowMessage);
}
return new decimal(_value._numericInfo.data1, _value._numericInfo.data2, _value._numericInfo.data3, !_value._numericInfo.positive, _value._numericInfo.scale);
}
if (StorageType.Money == _type)
{
long l = _value._int64;
bool isNegative = false;
if (l < 0)
{
isNegative = true;
l = -l;
}
return new decimal((int)(l & 0xffffffff), (int)(l >> 32), 0, isNegative, 4);
}
return (decimal)this.Value; // anything else we haven't thought of goes through boxing.
}
}
internal double Double
{
get
{
ThrowIfNull();
if (StorageType.Double == _type)
{
return _value._double;
}
return (double)this.Value; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._double = value;
_type = StorageType.Double;
_isNull = false;
}
}
internal Guid Guid
{
get
{
ThrowIfNull();
return this.SqlGuid.Value;
}
}
internal short Int16
{
get
{
ThrowIfNull();
if (StorageType.Int16 == _type)
{
return _value._int16;
}
return (short)this.Value; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._int16 = value;
_type = StorageType.Int16;
_isNull = false;
}
}
internal int Int32
{
get
{
ThrowIfNull();
if (StorageType.Int32 == _type)
{
return _value._int32;
}
return (int)this.Value; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._int32 = value;
_type = StorageType.Int32;
_isNull = false;
}
}
internal long Int64
{
get
{
ThrowIfNull();
if (StorageType.Int64 == _type)
{
return _value._int64;
}
return (long)this.Value; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._int64 = value;
_type = StorageType.Int64;
_isNull = false;
}
}
internal float Single
{
get
{
ThrowIfNull();
if (StorageType.Single == _type)
{
return _value._single;
}
return (float)this.Value; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._single = value;
_type = StorageType.Single;
_isNull = false;
}
}
internal string String
{
get
{
ThrowIfNull();
if (StorageType.String == _type)
{
return (string)_object;
}
else if (StorageType.SqlCachedBuffer == _type)
{
return ((SqlCachedBuffer)(_object)).ToString();
}
return (string)this.Value; // anything else we haven't thought of goes through boxing.
}
}
// use static list of format strings indexed by scale for perf
private static string[] s_katmaiDateTimeOffsetFormatByScale = new string[] {
"yyyy-MM-dd HH:mm:ss zzz",
"yyyy-MM-dd HH:mm:ss.f zzz",
"yyyy-MM-dd HH:mm:ss.ff zzz",
"yyyy-MM-dd HH:mm:ss.fff zzz",
"yyyy-MM-dd HH:mm:ss.ffff zzz",
"yyyy-MM-dd HH:mm:ss.fffff zzz",
"yyyy-MM-dd HH:mm:ss.ffffff zzz",
"yyyy-MM-dd HH:mm:ss.fffffff zzz",
};
private static string[] s_katmaiDateTime2FormatByScale = new string[] {
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.f",
"yyyy-MM-dd HH:mm:ss.ff",
"yyyy-MM-dd HH:mm:ss.fff",
"yyyy-MM-dd HH:mm:ss.ffff",
"yyyy-MM-dd HH:mm:ss.fffff",
"yyyy-MM-dd HH:mm:ss.ffffff",
"yyyy-MM-dd HH:mm:ss.fffffff",
};
private static string[] s_katmaiTimeFormatByScale = new string[] {
"HH:mm:ss",
"HH:mm:ss.f",
"HH:mm:ss.ff",
"HH:mm:ss.fff",
"HH:mm:ss.ffff",
"HH:mm:ss.fffff",
"HH:mm:ss.ffffff",
"HH:mm:ss.fffffff",
};
internal string KatmaiDateTimeString
{
get
{
ThrowIfNull();
if (StorageType.Date == _type)
{
return this.DateTime.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
}
if (StorageType.Time == _type)
{
byte scale = _value._timeInfo.scale;
return new DateTime(_value._timeInfo.ticks).ToString(s_katmaiTimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
if (StorageType.DateTime2 == _type)
{
byte scale = _value._dateTime2Info.timeInfo.scale;
return this.DateTime.ToString(s_katmaiDateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
if (StorageType.DateTimeOffset == _type)
{
DateTimeOffset dto = this.DateTimeOffset;
byte scale = _value._dateTimeOffsetInfo.dateTime2Info.timeInfo.scale;
return dto.ToString(s_katmaiDateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo);
}
return (string)this.Value; // anything else we haven't thought of goes through boxing.
}
}
internal SqlString KatmaiDateTimeSqlString
{
get
{
if (StorageType.Date == _type ||
StorageType.Time == _type ||
StorageType.DateTime2 == _type ||
StorageType.DateTimeOffset == _type)
{
if (IsNull)
{
return SqlString.Null;
}
return new SqlString(KatmaiDateTimeString);
}
return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal TimeSpan Time
{
get
{
ThrowIfNull();
if (StorageType.Time == _type)
{
return new TimeSpan(_value._timeInfo.ticks);
}
return (TimeSpan)this.Value; // anything else we haven't thought of goes through boxing.
}
}
internal DateTimeOffset DateTimeOffset
{
get
{
ThrowIfNull();
if (StorageType.DateTimeOffset == _type)
{
TimeSpan offset = new TimeSpan(0, _value._dateTimeOffsetInfo.offset, 0);
// datetime part presents time in UTC
return new DateTimeOffset(GetTicksFromDateTime2Info(_value._dateTimeOffsetInfo.dateTime2Info) + offset.Ticks, offset);
}
return (DateTimeOffset)this.Value; // anything else we haven't thought of goes through boxing.
}
}
private static long GetTicksFromDateTime2Info(DateTime2Info dateTime2Info)
{
return (dateTime2Info.date * TimeSpan.TicksPerDay + dateTime2Info.timeInfo.ticks);
}
internal SqlBinary SqlBinary
{
get
{
if (StorageType.SqlBinary == _type)
{
return (SqlBinary)_object;
}
return (SqlBinary)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_object = value;
_type = StorageType.SqlBinary;
_isNull = value.IsNull;
}
}
internal SqlBoolean SqlBoolean
{
get
{
if (StorageType.Boolean == _type)
{
if (IsNull)
{
return SqlBoolean.Null;
}
return new SqlBoolean(_value._boolean);
}
return (SqlBoolean)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlByte SqlByte
{
get
{
if (StorageType.Byte == _type)
{
if (IsNull)
{
return SqlByte.Null;
}
return new SqlByte(_value._byte);
}
return (SqlByte)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlCachedBuffer SqlCachedBuffer
{
get
{
if (StorageType.SqlCachedBuffer == _type)
{
if (IsNull)
{
return SqlCachedBuffer.Null;
}
return (SqlCachedBuffer)_object;
}
return (SqlCachedBuffer)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_object = value;
_type = StorageType.SqlCachedBuffer;
_isNull = value.IsNull;
}
}
internal SqlXml SqlXml
{
get
{
if (StorageType.SqlXml == _type)
{
if (IsNull)
{
return SqlXml.Null;
}
return (SqlXml)_object;
}
return (SqlXml)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_object = value;
_type = StorageType.SqlXml;
_isNull = value.IsNull;
}
}
internal SqlDateTime SqlDateTime
{
get
{
if (StorageType.DateTime == _type)
{
if (IsNull)
{
return SqlDateTime.Null;
}
return new SqlDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart);
}
return (SqlDateTime)SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlDecimal SqlDecimal
{
get
{
if (StorageType.Decimal == _type)
{
if (IsNull)
{
return SqlDecimal.Null;
}
return new SqlDecimal(_value._numericInfo.precision,
_value._numericInfo.scale,
_value._numericInfo.positive,
_value._numericInfo.data1,
_value._numericInfo.data2,
_value._numericInfo.data3,
_value._numericInfo.data4
);
}
return (SqlDecimal)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlDouble SqlDouble
{
get
{
if (StorageType.Double == _type)
{
if (IsNull)
{
return SqlDouble.Null;
}
return new SqlDouble(_value._double);
}
return (SqlDouble)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlGuid SqlGuid
{
get
{
if (StorageType.SqlGuid == _type)
{
return (SqlGuid)_object;
}
return (SqlGuid)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
set
{
Debug.Assert(IsEmpty, "setting value a second time?");
_object = value;
_type = StorageType.SqlGuid;
_isNull = value.IsNull;
}
}
internal SqlInt16 SqlInt16
{
get
{
if (StorageType.Int16 == _type)
{
if (IsNull)
{
return SqlInt16.Null;
}
return new SqlInt16(_value._int16);
}
return (SqlInt16)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlInt32 SqlInt32
{
get
{
if (StorageType.Int32 == _type)
{
if (IsNull)
{
return SqlInt32.Null;
}
return new SqlInt32(_value._int32);
}
return (SqlInt32)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlInt64 SqlInt64
{
get
{
if (StorageType.Int64 == _type)
{
if (IsNull)
{
return SqlInt64.Null;
}
return new SqlInt64(_value._int64);
}
return (SqlInt64)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlMoney SqlMoney
{
get
{
if (StorageType.Money == _type)
{
if (IsNull)
{
return SqlMoney.Null;
}
return SqlTypeWorkarounds.SqlMoneyCtor(_value._int64, 1/*ignored*/);
}
return (SqlMoney)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlSingle SqlSingle
{
get
{
if (StorageType.Single == _type)
{
if (IsNull)
{
return SqlSingle.Null;
}
return new SqlSingle(_value._single);
}
return (SqlSingle)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal SqlString SqlString
{
get
{
if (StorageType.String == _type)
{
if (IsNull)
{
return SqlString.Null;
}
return new SqlString((string)_object);
}
else if (StorageType.SqlCachedBuffer == _type)
{
SqlCachedBuffer data = (SqlCachedBuffer)(_object);
if (data.IsNull)
{
return SqlString.Null;
}
return data.ToSqlString();
}
return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing.
}
}
internal object SqlValue
{
get
{
switch (_type)
{
case StorageType.Empty: return DBNull.Value;
case StorageType.Boolean: return SqlBoolean;
case StorageType.Byte: return SqlByte;
case StorageType.DateTime: return SqlDateTime;
case StorageType.Decimal: return SqlDecimal;
case StorageType.Double: return SqlDouble;
case StorageType.Int16: return SqlInt16;
case StorageType.Int32: return SqlInt32;
case StorageType.Int64: return SqlInt64;
case StorageType.Money: return SqlMoney;
case StorageType.Single: return SqlSingle;
case StorageType.String: return SqlString;
case StorageType.SqlCachedBuffer:
{
SqlCachedBuffer data = (SqlCachedBuffer)(_object);
if (data.IsNull)
{
return SqlXml.Null;
}
return data.ToSqlXml();
}
case StorageType.SqlBinary:
case StorageType.SqlGuid:
return _object;
case StorageType.SqlXml:
{
if (_isNull)
{
return SqlXml.Null;
}
Debug.Assert(null != _object);
return (SqlXml)_object;
}
case StorageType.Date:
case StorageType.DateTime2:
if (_isNull)
{
return DBNull.Value;
}
return DateTime;
case StorageType.DateTimeOffset:
if (_isNull)
{
return DBNull.Value;
}
return DateTimeOffset;
case StorageType.Time:
if (_isNull)
{
return DBNull.Value;
}
return Time;
}
return null; // need to return the value as an object of some SQL type
}
}
private static readonly object s_cachedTrueObject = true;
private static readonly object s_cachedFalseObject = false;
internal object Value
{
get
{
if (IsNull)
{
return DBNull.Value;
}
switch (_type)
{
case StorageType.Empty: return DBNull.Value;
case StorageType.Boolean: return Boolean ? s_cachedTrueObject : s_cachedFalseObject;
case StorageType.Byte: return Byte;
case StorageType.DateTime: return DateTime;
case StorageType.Decimal: return Decimal;
case StorageType.Double: return Double;
case StorageType.Int16: return Int16;
case StorageType.Int32: return Int32;
case StorageType.Int64: return Int64;
case StorageType.Money: return Decimal;
case StorageType.Single: return Single;
case StorageType.String: return String;
case StorageType.SqlBinary: return ByteArray;
case StorageType.SqlCachedBuffer:
{
// If we have a CachedBuffer, it's because it's an XMLTYPE column
// and we have to return a string when they're asking for the CLS
// value of the column.
return ((SqlCachedBuffer)(_object)).ToString();
}
case StorageType.SqlGuid: return Guid;
case StorageType.SqlXml:
{
// XMLTYPE columns must be returned as string when asking for the CLS value
SqlXml data = (SqlXml)_object;
string s = data.Value;
return s;
}
case StorageType.Date: return DateTime;
case StorageType.DateTime2: return DateTime;
case StorageType.DateTimeOffset: return DateTimeOffset;
case StorageType.Time: return Time;
}
return null; // need to return the value as an object of some CLS type
}
}
internal Type GetTypeFromStorageType(bool isSqlType)
{
if (isSqlType)
{
switch (_type)
{
case SqlBuffer.StorageType.Empty: return null;
case SqlBuffer.StorageType.Boolean: return typeof(SqlBoolean);
case SqlBuffer.StorageType.Byte: return typeof(SqlByte);
case SqlBuffer.StorageType.DateTime: return typeof(SqlDateTime);
case SqlBuffer.StorageType.Decimal: return typeof(SqlDecimal);
case SqlBuffer.StorageType.Double: return typeof(SqlDouble);
case SqlBuffer.StorageType.Int16: return typeof(SqlInt16);
case SqlBuffer.StorageType.Int32: return typeof(SqlInt32);
case SqlBuffer.StorageType.Int64: return typeof(SqlInt64);
case SqlBuffer.StorageType.Money: return typeof(SqlMoney);
case SqlBuffer.StorageType.Single: return typeof(SqlSingle);
case SqlBuffer.StorageType.String: return typeof(SqlString);
case SqlBuffer.StorageType.SqlCachedBuffer: return typeof(SqlString);
case SqlBuffer.StorageType.SqlBinary: return typeof(object);
case SqlBuffer.StorageType.SqlGuid: return typeof(object);
case SqlBuffer.StorageType.SqlXml: return typeof(SqlXml);
}
}
else
{ //Is CLR Type
switch (_type)
{
case SqlBuffer.StorageType.Empty: return null;
case SqlBuffer.StorageType.Boolean: return typeof(bool);
case SqlBuffer.StorageType.Byte: return typeof(byte);
case SqlBuffer.StorageType.DateTime: return typeof(DateTime);
case SqlBuffer.StorageType.Decimal: return typeof(decimal);
case SqlBuffer.StorageType.Double: return typeof(double);
case SqlBuffer.StorageType.Int16: return typeof(short);
case SqlBuffer.StorageType.Int32: return typeof(int);
case SqlBuffer.StorageType.Int64: return typeof(long);
case SqlBuffer.StorageType.Money: return typeof(decimal);
case SqlBuffer.StorageType.Single: return typeof(float);
case SqlBuffer.StorageType.String: return typeof(string);
case SqlBuffer.StorageType.SqlBinary: return typeof(byte[]);
case SqlBuffer.StorageType.SqlCachedBuffer: return typeof(string);
case SqlBuffer.StorageType.SqlGuid: return typeof(Guid);
case SqlBuffer.StorageType.SqlXml: return typeof(string);
}
}
return null; // need to return the value as an object of some CLS type
}
internal static SqlBuffer[] CreateBufferArray(int length)
{
SqlBuffer[] buffers = new SqlBuffer[length];
for (int i = 0; i < buffers.Length; ++i)
{
buffers[i] = new SqlBuffer();
}
return buffers;
}
internal static SqlBuffer[] CloneBufferArray(SqlBuffer[] values)
{
SqlBuffer[] copy = new SqlBuffer[values.Length];
for (int i = 0; i < values.Length; i++)
{
copy[i] = new SqlBuffer(values[i]);
}
return copy;
}
internal static void Clear(SqlBuffer[] values)
{
if (null != values)
{
for (int i = 0; i < values.Length; ++i)
{
values[i].Clear();
}
}
}
internal void Clear()
{
_isNull = false;
_type = StorageType.Empty;
_object = null;
}
internal void SetToDateTime(int daypart, int timepart)
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._dateTimeInfo.daypart = daypart;
_value._dateTimeInfo.timepart = timepart;
_type = StorageType.DateTime;
_isNull = false;
}
internal void SetToDecimal(byte precision, byte scale, bool positive, int[] bits)
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._numericInfo.precision = precision;
_value._numericInfo.scale = scale;
_value._numericInfo.positive = positive;
_value._numericInfo.data1 = bits[0];
_value._numericInfo.data2 = bits[1];
_value._numericInfo.data3 = bits[2];
_value._numericInfo.data4 = bits[3];
_type = StorageType.Decimal;
_isNull = false;
}
internal void SetToMoney(long value)
{
Debug.Assert(IsEmpty, "setting value a second time?");
_value._int64 = value;
_type = StorageType.Money;
_isNull = false;
}
internal void SetToNullOfType(StorageType storageType)
{
Debug.Assert(IsEmpty, "setting value a second time?");
_type = storageType;
_isNull = true;
_object = null;
}
internal void SetToString(string value)
{
Debug.Assert(IsEmpty, "setting value a second time?");
_object = value;
_type = StorageType.String;
_isNull = false;
}
internal void SetToDate(ReadOnlySpan<byte> bytes)
{
Debug.Assert(IsEmpty, "setting value a second time?");
_type = StorageType.Date;
_value._int32 = GetDateFromByteArray(bytes);
_isNull = false;
}
internal void SetToTime(ReadOnlySpan<byte> bytes, byte scale)
{
Debug.Assert(IsEmpty, "setting value a second time?");
_type = StorageType.Time;
FillInTimeInfo(ref _value._timeInfo, bytes, scale);
_isNull = false;
}
internal void SetToDateTime2(ReadOnlySpan<byte> bytes, byte scale)
{
Debug.Assert(IsEmpty, "setting value a second time?");
int length = bytes.Length;
_type = StorageType.DateTime2;
FillInTimeInfo(ref _value._dateTime2Info.timeInfo, bytes.Slice(0, length - 3), scale); // remaining 3 bytes is for date
_value._dateTime2Info.date = GetDateFromByteArray(bytes.Slice(length - 3)); // 3 bytes for date
_isNull = false;
}
internal void SetToDateTimeOffset(ReadOnlySpan<byte> bytes, byte scale)
{
Debug.Assert(IsEmpty, "setting value a second time?");
int length = bytes.Length;
_type = StorageType.DateTimeOffset;
FillInTimeInfo(ref _value._dateTimeOffsetInfo.dateTime2Info.timeInfo, bytes.Slice(0, length - 5), scale); // remaining 5 bytes are for date and offset
_value._dateTimeOffsetInfo.dateTime2Info.date = GetDateFromByteArray(bytes.Slice(length - 5)); // 3 bytes for date
_value._dateTimeOffsetInfo.offset = (short)(bytes[length - 2] + (bytes[length - 1] << 8)); // 2 bytes for offset (Int16)
_isNull = false;
}
private static void FillInTimeInfo(ref TimeInfo timeInfo, ReadOnlySpan<byte> timeBytes, byte scale)
{
int length = timeBytes.Length;
Debug.Assert(3 <= length && length <= 5, "invalid data length for timeInfo: " + length);
Debug.Assert(0 <= scale && scale <= 7, "invalid scale: " + scale);
long tickUnits = (long)timeBytes[0] + ((long)timeBytes[1] << 8) + ((long)timeBytes[2] << 16);
if (length > 3)
{
tickUnits += ((long)timeBytes[3] << 24);
}
if (length > 4)
{
tickUnits += ((long)timeBytes[4] << 32);
}
timeInfo.ticks = tickUnits * TdsEnums.TICKS_FROM_SCALE[scale];
timeInfo.scale = scale;
}
private static int GetDateFromByteArray(ReadOnlySpan<byte> buf)
{
byte thirdByte = buf[2]; // reordered to optimize JIT generated bounds checks to a single instance, review generated asm before changing
return buf[0] + (buf[1] << 8) + (thirdByte << 16);
}
private void ThrowIfNull()
{
if (IsNull)
{
throw new SqlNullValueException();
}
}
}
}// namespace
| |
#region File Description
//-----------------------------------------------------------------------------
// ScreenManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO;
using System.IO.IsolatedStorage;
#endregion
namespace GameStateManagement
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
public class ScreenManager : DrawableGameComponent
{
#region Fields
List<GameScreen> screens = new List<GameScreen>();
List<GameScreen> screensToUpdate = new List<GameScreen>();
InputState input = new InputState();
SpriteBatch spriteBatch;
SpriteFont font;
Texture2D blankTexture;
bool isInitialized;
bool traceEnabled;
#endregion
#region Properties
/// <summary>
/// A default SpriteBatch shared by all the screens. This saves
/// each screen having to bother creating their own local instance.
/// </summary>
public SpriteBatch SpriteBatch
{
get { return spriteBatch; }
}
/// <summary>
/// A default font shared by all the screens. This saves
/// each screen having to bother loading their own local copy.
/// </summary>
public SpriteFont Font
{
get { return font; }
}
/// <summary>
/// If true, the manager prints out a list of all the screens
/// each time it is updated. This can be useful for making sure
/// everything is being added and removed at the right times.
/// </summary>
public bool TraceEnabled
{
get { return traceEnabled; }
set { traceEnabled = value; }
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ScreenManager(Game game)
: base(game)
{
// we must set EnabledGestures before we can query for them, but
// we don't assume the game wants to read them.
TouchPanel.EnabledGestures = GestureType.None;
}
/// <summary>
/// Initializes the screen manager component.
/// </summary>
public override void Initialize()
{
base.Initialize();
isInitialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load content belonging to the screen manager.
ContentManager content = Game.Content;
spriteBatch = new SpriteBatch(GraphicsDevice);
font = content.Load<SpriteFont>("Fonts/MenuFont");
blankTexture = content.Load<Texture2D>("Textures/Backgrounds/blank");
// Tell each of the screens to load their content.
foreach (GameScreen screen in screens)
{
screen.LoadContent();
}
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
// Tell each of the screens to unload their content.
foreach (GameScreen screen in screens)
{
screen.UnloadContent();
}
}
#endregion
#region Update and Draw
/// <summary>
/// Allows each screen to run logic.
/// </summary>
public override void Update(GameTime gameTime)
{
// Read the keyboard and gamepad.
input.Update();
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
screensToUpdate.Clear();
foreach (GameScreen screen in screens)
screensToUpdate.Add(screen);
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = screensToUpdate[screensToUpdate.Count - 1];
screensToUpdate.RemoveAt(screensToUpdate.Count - 1);
// Update the screen.
screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.ScreenState == ScreenState.TransitionOn ||
screen.ScreenState == ScreenState.Active)
{
// If this is the first active screen we came across,
// give it a chance to handle input.
if (!otherScreenHasFocus)
{
screen.HandleInput(input);
otherScreenHasFocus = true;
}
// If this is an active non-popup, inform any subsequent
// screens that they are covered by it.
if (!screen.IsPopup)
coveredByOtherScreen = true;
}
}
// Print debug trace?
if (traceEnabled)
TraceScreens();
}
/// <summary>
/// Prints a list of all the screens, for debugging.
/// </summary>
void TraceScreens()
{
List<string> screenNames = new List<string>();
foreach (GameScreen screen in screens)
screenNames.Add(screen.GetType().Name);
Debug.WriteLine(string.Join(", ", screenNames.ToArray()));
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
foreach (GameScreen screen in screens)
{
if (screen.ScreenState == ScreenState.Hidden)
continue;
screen.Draw(gameTime);
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
{
screen.ControllingPlayer = controllingPlayer;
screen.ScreenManager = this;
screen.IsExiting = false;
// If we have a graphics device, tell the screen to load content.
if (isInitialized)
{
screen.LoadContent();
}
screens.Add(screen);
// update the TouchPanel to respond to gestures this screen is interested in
TouchPanel.EnabledGestures = screen.EnabledGestures;
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public void RemoveScreen(GameScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (isInitialized)
{
screen.UnloadContent();
}
screens.Remove(screen);
screensToUpdate.Remove(screen);
// if there is a screen still in the manager, update TouchPanel
// to respond to gestures that screen is interested in.
if (screens.Count > 0)
{
TouchPanel.EnabledGestures = screens[screens.Count - 1].EnabledGestures;
}
}
/// <summary>
/// Expose an array holding all the screens. We return a copy rather
/// than the real master list, because screens should only ever be added
/// or removed using the AddScreen and RemoveScreen methods.
/// </summary>
public GameScreen[] GetScreens()
{
return screens.ToArray();
}
/// <summary>
/// Helper draws a translucent black fullscreen sprite, used for fading
/// screens in and out, and for darkening the background behind popups.
/// </summary>
public void FadeBackBufferToBlack(float alpha)
{
Viewport viewport = GraphicsDevice.Viewport;
spriteBatch.Begin();
spriteBatch.Draw(blankTexture,
new Rectangle(0, 0, viewport.Width, viewport.Height),
Color.Black * alpha);
spriteBatch.End();
}
/// <summary>
/// Informs the screen manager to serialize its state to disk.
/// </summary>
public void SerializeState()
{
// open up isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
// if our screen manager directory already exists, delete the contents
if (storage.DirectoryExists("ScreenManager"))
{
DeleteState(storage);
}
// otherwise just create the directory
else
{
storage.CreateDirectory("ScreenManager");
}
// create a file we'll use to store the list of screens in the stack
using (IsolatedStorageFileStream stream = storage.CreateFile("ScreenManager\\ScreenList.dat"))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
// write out the full name of all the types in our stack so we can
// recreate them if needed.
foreach (GameScreen screen in screens)
{
if (screen.IsSerializable)
{
writer.Write(screen.GetType().AssemblyQualifiedName);
}
}
}
}
// now we create a new file stream for each screen so it can save its state
// if it needs to. we name each file "ScreenX.dat" where X is the index of
// the screen in the stack, to ensure the files are uniquely named
int screenIndex = 0;
foreach (GameScreen screen in screens)
{
if (screen.IsSerializable)
{
string fileName = string.Format("ScreenManager\\Screen{0}.dat", screenIndex);
// open up the stream and let the screen serialize whatever state it wants
using (IsolatedStorageFileStream stream = storage.CreateFile(fileName))
{
screen.Serialize(stream);
}
screenIndex++;
}
}
}
}
public bool DeserializeState()
{
// open up isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
// see if our saved state directory exists
if (storage.DirectoryExists("ScreenManager"))
{
try
{
// see if we have a screen list
if (storage.FileExists("ScreenManager\\ScreenList.dat"))
{
// load the list of screen types
using (IsolatedStorageFileStream stream =
storage.OpenFile("ScreenManager\\ScreenList.dat",
FileMode.Open, FileAccess.Read))
{
using (BinaryReader reader = new BinaryReader(stream))
{
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
// read a line from our file
string line = reader.ReadString();
// if it isn't blank, we can create a screen from it
if (!string.IsNullOrEmpty(line))
{
Type screenType = Type.GetType(line);
GameScreen screen = Activator.CreateInstance(screenType) as GameScreen;
AddScreen(screen, PlayerIndex.One);
}
}
}
}
}
// next we give each screen a chance to deserialize from the disk
for (int i = 0; i < screens.Count; i++)
{
string filename = string.Format("ScreenManager\\Screen{0}.dat", i);
using (IsolatedStorageFileStream stream = storage.OpenFile(filename,
FileMode.Open, FileAccess.Read))
{
screens[i].Deserialize(stream);
}
}
return true;
}
catch (Exception)
{
// if an exception was thrown while reading, odds are we cannot recover
// from the saved state, so we will delete it so the game can correctly
// launch.
DeleteState(storage);
}
}
}
return false;
}
/// <summary>
/// Deletes the saved state files from isolated storage.
/// </summary>
private void DeleteState(IsolatedStorageFile storage)
{
// get all of the files in the directory and delete them
string[] files = storage.GetFileNames("ScreenManager\\*");
foreach (string file in files)
{
storage.DeleteFile(Path.Combine("ScreenManager", file));
}
}
#endregion
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using MyWebPlayground.Models;
namespace MyWebPlayground.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20160323113305_first")]
partial class first
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("MyWebPlayground.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("MyWebPlayground.Models.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Author")
.IsRequired();
b.Property<string>("Css")
.IsRequired();
b.Property<string>("CssMode")
.IsRequired();
b.Property<string>("Description")
.IsRequired();
b.Property<string>("Html")
.IsRequired();
b.Property<string>("HtmlMode")
.IsRequired();
b.Property<string>("Javascript")
.IsRequired();
b.Property<string>("JavascriptMode")
.IsRequired();
b.Property<string>("MarkupChoice")
.IsRequired();
b.Property<string>("ScriptChoice")
.IsRequired();
b.Property<string>("StyleChoice")
.IsRequired();
b.Property<string>("Title")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("MyWebPlayground.Models.DocumentCssLibrary", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CssLibrary")
.IsRequired();
b.Property<int?>("DocumentId");
b.HasKey("Id");
});
modelBuilder.Entity("MyWebPlayground.Models.DocumentJavascriptLibrary", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("DocumentId");
b.Property<string>("JavascriptLibrary")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("MyWebPlayground.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("MyWebPlayground.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("MyWebPlayground.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("MyWebPlayground.Models.DocumentCssLibrary", b =>
{
b.HasOne("MyWebPlayground.Models.Document")
.WithMany()
.HasForeignKey("DocumentId");
});
modelBuilder.Entity("MyWebPlayground.Models.DocumentJavascriptLibrary", b =>
{
b.HasOne("MyWebPlayground.Models.Document")
.WithMany()
.HasForeignKey("DocumentId");
});
}
}
}
| |
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using UnityEngine.LowLevel;
using UnityEngine.PlayerLoop;
namespace MLAPI.RuntimeTests
{
public class NetworkUpdateLoopTests
{
[Test]
public void RegisterCustomLoopInTheMiddle()
{
// caching the current PlayerLoop (to prevent side-effects on other tests)
var cachedPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
{
// since current PlayerLoop already took NetworkUpdateLoop systems inside,
// we are going to swap it with the default PlayerLoop temporarily for testing
PlayerLoop.SetPlayerLoop(PlayerLoop.GetDefaultPlayerLoop());
NetworkUpdateLoop.RegisterLoopSystems();
var curPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
int initSubsystemCount = curPlayerLoop.subSystemList[0].subSystemList.Length;
var newInitSubsystems = new PlayerLoopSystem[initSubsystemCount + 1];
Array.Copy(curPlayerLoop.subSystemList[0].subSystemList, newInitSubsystems, initSubsystemCount);
newInitSubsystems[initSubsystemCount] = new PlayerLoopSystem { type = typeof(NetworkUpdateLoopTests) };
curPlayerLoop.subSystemList[0].subSystemList = newInitSubsystems;
PlayerLoop.SetPlayerLoop(curPlayerLoop);
NetworkUpdateLoop.UnregisterLoopSystems();
// our custom `PlayerLoopSystem` with the type of `NetworkUpdateLoopTests` should still exist
Assert.AreEqual(typeof(NetworkUpdateLoopTests), PlayerLoop.GetCurrentPlayerLoop().subSystemList[0].subSystemList.Last().type);
}
// replace the current PlayerLoop with the cached PlayerLoop after the test
PlayerLoop.SetPlayerLoop(cachedPlayerLoop);
}
[UnityTest]
public IEnumerator RegisterAndUnregisterSystems()
{
// caching the current PlayerLoop (it will have NetworkUpdateLoop systems registered)
var cachedPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
{
// since current PlayerLoop already took NetworkUpdateLoop systems inside,
// we are going to swap it with the default PlayerLoop temporarily for testing
PlayerLoop.SetPlayerLoop(PlayerLoop.GetDefaultPlayerLoop());
var oldPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
NetworkUpdateLoop.RegisterLoopSystems();
int nextFrameNumber = Time.frameCount + 1;
yield return new WaitUntil(() => Time.frameCount >= nextFrameNumber);
NetworkUpdateLoop.UnregisterLoopSystems();
var newPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
// recursively compare old and new PlayerLoop systems and their subsystems
AssertAreEqualPlayerLoopSystems(newPlayerLoop, oldPlayerLoop);
}
// replace the current PlayerLoop with the cached PlayerLoop after the test
PlayerLoop.SetPlayerLoop(cachedPlayerLoop);
}
private void AssertAreEqualPlayerLoopSystems(PlayerLoopSystem leftPlayerLoop, PlayerLoopSystem rightPlayerLoop)
{
Assert.AreEqual(leftPlayerLoop.type, rightPlayerLoop.type);
Assert.AreEqual(leftPlayerLoop.subSystemList?.Length ?? 0, rightPlayerLoop.subSystemList?.Length ?? 0);
for (int i = 0; i < (leftPlayerLoop.subSystemList?.Length ?? 0); i++)
{
AssertAreEqualPlayerLoopSystems(leftPlayerLoop.subSystemList[i], rightPlayerLoop.subSystemList[i]);
}
}
[Test]
public void UpdateStageSystems()
{
var currentPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
for (int i = 0; i < currentPlayerLoop.subSystemList.Length; i++)
{
var playerLoopSystem = currentPlayerLoop.subSystemList[i];
var subsystems = playerLoopSystem.subSystemList.ToList();
if (playerLoopSystem.type == typeof(Initialization))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkInitialization)),
nameof(NetworkUpdateLoop.NetworkInitialization));
}
else if (playerLoopSystem.type == typeof(EarlyUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkEarlyUpdate)),
nameof(NetworkUpdateLoop.NetworkEarlyUpdate));
}
else if (playerLoopSystem.type == typeof(FixedUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkFixedUpdate)),
nameof(NetworkUpdateLoop.NetworkFixedUpdate));
}
else if (playerLoopSystem.type == typeof(PreUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkPreUpdate)),
nameof(NetworkUpdateLoop.NetworkPreUpdate));
}
else if (playerLoopSystem.type == typeof(Update))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkUpdate)),
nameof(NetworkUpdateLoop.NetworkUpdate));
}
else if (playerLoopSystem.type == typeof(PreLateUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkPreLateUpdate)),
nameof(NetworkUpdateLoop.NetworkPreLateUpdate));
}
else if (playerLoopSystem.type == typeof(PostLateUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkPostLateUpdate)),
nameof(NetworkUpdateLoop.NetworkPostLateUpdate));
}
}
}
private struct NetworkUpdateCallbacks
{
public Action OnInitialization;
public Action OnEarlyUpdate;
public Action OnFixedUpdate;
public Action OnPreUpdate;
public Action OnUpdate;
public Action OnPreLateUpdate;
public Action OnPostLateUpdate;
}
private class MyPlainScript : IDisposable, INetworkUpdateSystem
{
public NetworkUpdateCallbacks UpdateCallbacks;
public void Initialize()
{
this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
}
public void NetworkUpdate(NetworkUpdateStage updateStage)
{
switch (updateStage)
{
case NetworkUpdateStage.Initialization:
UpdateCallbacks.OnInitialization();
break;
case NetworkUpdateStage.EarlyUpdate:
UpdateCallbacks.OnEarlyUpdate();
break;
case NetworkUpdateStage.FixedUpdate:
UpdateCallbacks.OnFixedUpdate();
break;
case NetworkUpdateStage.PreUpdate:
UpdateCallbacks.OnPreUpdate();
break;
case NetworkUpdateStage.Update:
UpdateCallbacks.OnUpdate();
break;
case NetworkUpdateStage.PreLateUpdate:
UpdateCallbacks.OnPreLateUpdate();
break;
case NetworkUpdateStage.PostLateUpdate:
UpdateCallbacks.OnPostLateUpdate();
break;
}
}
public void Dispose()
{
this.UnregisterAllNetworkUpdates();
}
}
[UnityTest]
public IEnumerator UpdateStagesPlain()
{
const int kNetInitializationIndex = 0;
const int kNetEarlyUpdateIndex = 1;
const int kNetFixedUpdateIndex = 2;
const int kNetPreUpdateIndex = 3;
const int kNetUpdateIndex = 4;
const int kNetPreLateUpdateIndex = 5;
const int kNetPostLateUpdateIndex = 6;
int[] netUpdates = new int[7];
bool isTesting = false;
using (var plainScript = new MyPlainScript())
{
plainScript.UpdateCallbacks = new NetworkUpdateCallbacks
{
OnInitialization = () =>
{
if (isTesting)
{
netUpdates[kNetInitializationIndex]++;
}
},
OnEarlyUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetEarlyUpdateIndex]++;
}
},
OnFixedUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetFixedUpdateIndex]++;
}
},
OnPreUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreUpdateIndex]++;
}
},
OnUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetUpdateIndex]++;
}
},
OnPreLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreLateUpdateIndex]++;
}
},
OnPostLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPostLateUpdateIndex]++;
}
}
};
plainScript.Initialize();
int nextFrameNumber = Time.frameCount + 1;
yield return new WaitUntil(() => Time.frameCount >= nextFrameNumber);
isTesting = true;
const int kRunTotalFrames = 16;
int waitFrameNumber = Time.frameCount + kRunTotalFrames;
yield return new WaitUntil(() => Time.frameCount >= waitFrameNumber);
Assert.AreEqual(0, netUpdates[kNetInitializationIndex]);
Assert.AreEqual(kRunTotalFrames, netUpdates[kNetEarlyUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetFixedUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetPreUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetUpdateIndex]);
Assert.AreEqual(kRunTotalFrames, netUpdates[kNetPreLateUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetPostLateUpdateIndex]);
}
}
private struct MonoBehaviourCallbacks
{
public Action OnFixedUpdate;
public Action OnUpdate;
public Action OnLateUpdate;
}
private class MyGameScript : MonoBehaviour, INetworkUpdateSystem
{
public NetworkUpdateCallbacks UpdateCallbacks;
public MonoBehaviourCallbacks BehaviourCallbacks;
private void Awake()
{
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
// intentionally try to register for 'PreUpdate' stage twice
// it should be ignored and the instance should not be registered twice
// otherwise test would fail because it would call 'OnPreUpdate()' twice
// which would ultimately increment 'netUpdates[idx]' integer twice
// and cause 'Assert.AreEqual()' to fail the test
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
}
public void NetworkUpdate(NetworkUpdateStage updateStage)
{
switch (updateStage)
{
case NetworkUpdateStage.FixedUpdate:
UpdateCallbacks.OnFixedUpdate();
break;
case NetworkUpdateStage.PreUpdate:
UpdateCallbacks.OnPreUpdate();
break;
case NetworkUpdateStage.PreLateUpdate:
UpdateCallbacks.OnPreLateUpdate();
break;
case NetworkUpdateStage.PostLateUpdate:
UpdateCallbacks.OnPostLateUpdate();
break;
}
}
private void FixedUpdate()
{
BehaviourCallbacks.OnFixedUpdate();
}
private void Update()
{
BehaviourCallbacks.OnUpdate();
}
private void LateUpdate()
{
BehaviourCallbacks.OnLateUpdate();
}
private void OnDestroy()
{
this.UnregisterAllNetworkUpdates();
}
}
[UnityTest]
public IEnumerator UpdateStagesMixed()
{
const int kNetFixedUpdateIndex = 0;
const int kNetPreUpdateIndex = 1;
const int kNetPreLateUpdateIndex = 2;
const int kNetPostLateUpdateIndex = 3;
int[] netUpdates = new int[4];
const int kMonoFixedUpdateIndex = 0;
const int kMonoUpdateIndex = 1;
const int kMonoLateUpdateIndex = 2;
int[] monoUpdates = new int[3];
bool isTesting = false;
{
var gameObject = new GameObject($"{nameof(NetworkUpdateLoopTests)}.{nameof(UpdateStagesMixed)} (Dummy)");
var gameScript = gameObject.AddComponent<MyGameScript>();
gameScript.UpdateCallbacks = new NetworkUpdateCallbacks
{
OnFixedUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetFixedUpdateIndex]++;
Assert.AreEqual(monoUpdates[kMonoFixedUpdateIndex] + 1, netUpdates[kNetFixedUpdateIndex]);
}
},
OnPreUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreUpdateIndex]++;
Assert.AreEqual(monoUpdates[kMonoUpdateIndex] + 1, netUpdates[kNetPreUpdateIndex]);
}
},
OnPreLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreLateUpdateIndex]++;
Assert.AreEqual(monoUpdates[kMonoLateUpdateIndex] + 1, netUpdates[kNetPreLateUpdateIndex]);
}
},
OnPostLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPostLateUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetPostLateUpdateIndex], netUpdates[kNetPreLateUpdateIndex]);
}
}
};
gameScript.BehaviourCallbacks = new MonoBehaviourCallbacks
{
OnFixedUpdate = () =>
{
if (isTesting)
{
monoUpdates[kMonoFixedUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetFixedUpdateIndex], monoUpdates[kMonoFixedUpdateIndex]);
}
},
OnUpdate = () =>
{
if (isTesting)
{
monoUpdates[kMonoUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetPreUpdateIndex], monoUpdates[kMonoUpdateIndex]);
}
},
OnLateUpdate = () =>
{
if (isTesting)
{
monoUpdates[kMonoLateUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetPreLateUpdateIndex], monoUpdates[kMonoLateUpdateIndex]);
}
}
};
int nextFrameNumber = Time.frameCount + 1;
yield return new WaitUntil(() => Time.frameCount >= nextFrameNumber);
isTesting = true;
const int kRunTotalFrames = 16;
int waitFrameNumber = Time.frameCount + kRunTotalFrames;
yield return new WaitUntil(() => Time.frameCount >= waitFrameNumber);
Assert.AreEqual(kRunTotalFrames, netUpdates[kNetPreUpdateIndex]);
Assert.AreEqual(netUpdates[kNetPreUpdateIndex], monoUpdates[kMonoUpdateIndex]);
GameObject.DestroyImmediate(gameObject);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Data.MultiBinding.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Data
{
public partial class MultiBinding : BindingBase, System.Windows.Markup.IAddChild
{
#region Methods and constructors
public MultiBinding()
{
}
public bool ShouldSerializeBindings()
{
return default(bool);
}
public bool ShouldSerializeValidationRules()
{
return default(bool);
}
void System.Windows.Markup.IAddChild.AddChild(Object value)
{
}
void System.Windows.Markup.IAddChild.AddText(string text)
{
}
#endregion
#region Properties and indexers
public System.Collections.ObjectModel.Collection<BindingBase> Bindings
{
get
{
return default(System.Collections.ObjectModel.Collection<BindingBase>);
}
}
public IMultiValueConverter Converter
{
get
{
return default(IMultiValueConverter);
}
set
{
}
}
public System.Globalization.CultureInfo ConverterCulture
{
get
{
return default(System.Globalization.CultureInfo);
}
set
{
}
}
public Object ConverterParameter
{
get
{
return default(Object);
}
set
{
}
}
public BindingMode Mode
{
get
{
Contract.Ensures(((System.Windows.Data.BindingMode)(0)) <= Contract.Result<System.Windows.Data.BindingMode>());
Contract.Ensures(Contract.Result<System.Windows.Data.BindingMode>() <= ((System.Windows.Data.BindingMode)(4)));
return default(BindingMode);
}
set
{
}
}
public bool NotifyOnSourceUpdated
{
get
{
return default(bool);
}
set
{
}
}
public bool NotifyOnTargetUpdated
{
get
{
return default(bool);
}
set
{
}
}
public bool NotifyOnValidationError
{
get
{
return default(bool);
}
set
{
}
}
public UpdateSourceExceptionFilterCallback UpdateSourceExceptionFilter
{
get
{
return default(UpdateSourceExceptionFilterCallback);
}
set
{
}
}
public UpdateSourceTrigger UpdateSourceTrigger
{
get
{
Contract.Ensures(((System.Windows.Data.UpdateSourceTrigger)(0)) <= Contract.Result<System.Windows.Data.UpdateSourceTrigger>());
Contract.Ensures(Contract.Result<System.Windows.Data.UpdateSourceTrigger>() <= ((System.Windows.Data.UpdateSourceTrigger)(3)));
return default(UpdateSourceTrigger);
}
set
{
}
}
public bool ValidatesOnDataErrors
{
get
{
return default(bool);
}
set
{
}
}
public bool ValidatesOnExceptions
{
get
{
return default(bool);
}
set
{
}
}
public System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule> ValidationRules
{
get
{
Contract.Ensures(Contract.Result<System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule>>() != null);
return default(System.Collections.ObjectModel.Collection<System.Windows.Controls.ValidationRule>);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Xml;
namespace System.ServiceModel.Syndication
{
public delegate bool TryParseDateTimeCallback(XmlDateTimeData data, out DateTimeOffset dateTimeOffset);
public delegate bool TryParseUriCallback(XmlUriData data, out Uri uri);
[DataContract]
public abstract class SyndicationFeedFormatter
{
private SyndicationFeed _feed;
protected SyndicationFeedFormatter()
{
_feed = null;
DateTimeParser = GetDefaultDateTimeParser();
}
protected SyndicationFeedFormatter(SyndicationFeed feedToWrite)
{
_feed = feedToWrite ?? throw new ArgumentNullException(nameof(feedToWrite));
DateTimeParser = GetDefaultDateTimeParser();
}
public SyndicationFeed Feed => _feed;
public TryParseUriCallback UriParser { get; set; } = DefaultUriParser;
// Different DateTimeParsers are needed for Atom and Rss so can't set inline
public TryParseDateTimeCallback DateTimeParser { get; set; }
internal virtual TryParseDateTimeCallback GetDefaultDateTimeParser() => NotImplementedDateTimeParser;
private bool NotImplementedDateTimeParser(XmlDateTimeData XmlDateTimeData, out DateTimeOffset dateTimeOffset)
{
dateTimeOffset = default;
return false;
}
public abstract string Version { get; }
public abstract bool CanRead(XmlReader reader);
public abstract void ReadFrom(XmlReader reader);
public override string ToString() => $"{GetType()}, SyndicationVersion={Version}";
public abstract void WriteTo(XmlWriter writer);
protected internal static SyndicationCategory CreateCategory(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreateCategory(), SR.FeedCreatedNullCategory);
}
protected internal static SyndicationCategory CreateCategory(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return GetNonNullValue(item.CreateCategory(), SR.ItemCreatedNullCategory);
}
protected internal static SyndicationItem CreateItem(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreateItem(), SR.FeedCreatedNullItem);
}
protected internal static SyndicationLink CreateLink(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreateLink(), SR.FeedCreatedNullPerson);
}
protected internal static SyndicationLink CreateLink(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return GetNonNullValue(item.CreateLink(), SR.ItemCreatedNullPerson);
}
protected internal static SyndicationPerson CreatePerson(SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return GetNonNullValue(feed.CreatePerson(), SR.FeedCreatedNullPerson);
}
protected internal static SyndicationPerson CreatePerson(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return GetNonNullValue(item.CreatePerson(), SR.ItemCreatedNullPerson);
}
protected internal static void LoadElementExtensions(XmlReader reader, SyndicationFeed feed, int maxExtensionSize)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
feed.LoadElementExtensions(reader, maxExtensionSize);
}
protected internal static void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.LoadElementExtensions(reader, maxExtensionSize);
}
protected internal static void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
category.LoadElementExtensions(reader, maxExtensionSize);
}
protected internal static void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
link.LoadElementExtensions(reader, maxExtensionSize);
}
protected internal static void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.LoadElementExtensions(reader, maxExtensionSize);
}
protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return feed.TryParseAttribute(name, ns, value, version);
}
protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return item.TryParseAttribute(name, ns, value, version);
}
protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return category.TryParseAttribute(name, ns, value, version);
}
protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return link.TryParseAttribute(name, ns, value, version);
}
protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
if (FeedUtils.IsXmlns(name, ns))
{
return true;
}
return person.TryParseAttribute(name, ns, value, version);
}
protected internal static bool TryParseContent(XmlReader reader, SyndicationItem item, string contentType, string version, out SyndicationContent content)
{
return item.TryParseContent(reader, contentType, version, out content);
}
protected internal static bool TryParseElement(XmlReader reader, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
return feed.TryParseElement(reader, version);
}
protected internal static bool TryParseElement(XmlReader reader, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return item.TryParseElement(reader, version);
}
protected internal static bool TryParseElement(XmlReader reader, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
return category.TryParseElement(reader, version);
}
protected internal static bool TryParseElement(XmlReader reader, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
return link.TryParseElement(reader, version);
}
protected internal static bool TryParseElement(XmlReader reader, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
return person.TryParseElement(reader, version);
}
protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
feed.WriteAttributeExtensions(writer, version);
}
protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.WriteAttributeExtensions(writer, version);
}
protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
category.WriteAttributeExtensions(writer, version);
}
protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
link.WriteAttributeExtensions(writer, version);
}
protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.WriteAttributeExtensions(writer, version);
}
protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationFeed feed, string version)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
feed.WriteElementExtensions(writer, version);
}
protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationItem item, string version)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
item.WriteElementExtensions(writer, version);
}
protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationCategory category, string version)
{
if (category == null)
{
throw new ArgumentNullException(nameof(category));
}
category.WriteElementExtensions(writer, version);
}
protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationLink link, string version)
{
if (link == null)
{
throw new ArgumentNullException(nameof(link));
}
link.WriteElementExtensions(writer, version);
}
protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationPerson person, string version)
{
if (person == null)
{
throw new ArgumentNullException(nameof(person));
}
person.WriteElementExtensions(writer, version);
}
protected internal virtual void SetFeed(SyndicationFeed feed)
{
_feed = feed ?? throw new ArgumentNullException(nameof(feed));
}
internal Uri UriFromString(string uriString, UriKind uriKind, string localName, string namespaceURI, XmlReader reader)
{
return UriFromString(UriParser, uriString, uriKind, localName, namespaceURI, reader);
}
internal static Uri UriFromString(TryParseUriCallback uriParser, string uriString, UriKind uriKind, string localName, string namespaceURI, XmlReader reader)
{
Uri uri = null;
var elementQualifiedName = new XmlQualifiedName(localName, namespaceURI);
var xmlUriData = new XmlUriData(uriString, uriKind, elementQualifiedName);
object[] args = new object[] { xmlUriData, uri };
try
{
foreach (Delegate parser in uriParser.GetInvocationList())
{
if ((bool)parser.Method.Invoke(parser.Target, args))
{
uri = (Uri)args[args.Length - 1];
return uri;
}
}
}
catch (Exception e)
{
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingUri), e);
}
DefaultUriParser(xmlUriData, out uri);
return uri;
}
internal DateTimeOffset DateFromString(string dateTimeString, XmlReader reader)
{
try
{
DateTimeOffset dateTimeOffset = default;
var elementQualifiedName = new XmlQualifiedName(reader.LocalName, reader.NamespaceURI);
var xmlDateTimeData = new XmlDateTimeData(dateTimeString, elementQualifiedName);
object[] args = new object[] { xmlDateTimeData, dateTimeOffset };
foreach (Delegate dateTimeParser in DateTimeParser.GetInvocationList())
{
if ((bool)dateTimeParser.Method.Invoke(dateTimeParser.Target, args))
{
dateTimeOffset = (DateTimeOffset)args[args.Length - 1];
return dateTimeOffset;
}
}
}
catch (Exception e)
{
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDateTime), e);
}
throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDateTime));
}
internal static bool DefaultUriParser(XmlUriData XmlUriData, out Uri uri)
{
uri = new Uri(XmlUriData.UriString, XmlUriData.UriKind);
return true;
}
internal static void CloseBuffer(XmlBuffer buffer, XmlDictionaryWriter extWriter)
{
if (buffer == null)
{
return;
}
extWriter.WriteEndElement();
buffer.CloseSection();
buffer.Close();
}
internal static void CreateBufferIfRequiredAndWriteNode(ref XmlBuffer buffer, ref XmlDictionaryWriter extWriter, XmlReader reader, int maxExtensionSize)
{
if (buffer == null)
{
buffer = new XmlBuffer(maxExtensionSize);
extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
}
extWriter.WriteNode(reader, false);
}
internal static SyndicationFeed CreateFeedInstance(Type feedType)
{
if (feedType.Equals(typeof(SyndicationFeed)))
{
return new SyndicationFeed();
}
else
{
return (SyndicationFeed)Activator.CreateInstance(feedType);
}
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed)
{
if (feed == null)
{
throw new ArgumentNullException(nameof(feed));
}
CloseBuffer(buffer, writer);
feed.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationItem item)
{
Debug.Assert(item != null);
CloseBuffer(buffer, writer);
item.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationCategory category)
{
Debug.Assert(category != null);
CloseBuffer(buffer, writer);
category.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationLink link)
{
Debug.Assert(link != null);
CloseBuffer(buffer, writer);
link.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationPerson person)
{
Debug.Assert(person != null);
CloseBuffer(buffer, writer);
person.LoadElementExtensions(buffer);
}
internal static void MoveToStartElement(XmlReader reader)
{
Debug.Assert(reader != null, "reader != null");
if (!reader.IsStartElement())
{
XmlExceptionHelper.ThrowStartElementExpected(XmlDictionaryReader.CreateDictionaryReader(reader));
}
}
protected abstract SyndicationFeed CreateFeedInstance();
private static T GetNonNullValue<T>(T value, string errorMsg)
{
if (value == null)
{
throw new InvalidOperationException(errorMsg);
}
return value;
}
private static class XmlExceptionHelper
{
private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1)
{
string s = SR.Format(res, arg1);
if (reader is IXmlLineInfo lineInfo && lineInfo.HasLineInfo())
{
s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
}
throw new XmlException(s);
}
private static string GetName(string prefix, string localName)
{
if (prefix.Length == 0)
return localName;
else
return string.Concat(prefix, ":", localName);
}
private static string GetWhatWasFound(XmlDictionaryReader reader)
{
if (reader.EOF)
return SR.XmlFoundEndOfFile;
switch (reader.NodeType)
{
case XmlNodeType.Element:
return SR.Format(SR.XmlFoundElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
case XmlNodeType.EndElement:
return SR.Format(SR.XmlFoundEndElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return SR.Format(SR.XmlFoundText, reader.Value);
case XmlNodeType.Comment:
return SR.Format(SR.XmlFoundComment, reader.Value);
case XmlNodeType.CDATA:
return SR.Format(SR.XmlFoundCData, reader.Value);
}
return SR.Format(SR.XmlFoundNodeType, reader.NodeType);
}
public static void ThrowStartElementExpected(XmlDictionaryReader reader)
{
ThrowXmlException(reader, SR.XmlStartElementExpected, GetWhatWasFound(reader));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Dapper;
using Hangfire.Console;
using Hangfire.Server;
using Relisten.Api.Models;
using Relisten.Controllers;
namespace Relisten.Import
{
[Flags]
public enum ImportableData
{
Nothing = 0,
Eras = 1 << 0,
Tours = 1 << 1,
Venues = 1 << 2,
SetlistShowsAndSongs = 1 << 3,
SourceReviews = 1 << 4,
SourceRatings = 1 << 5,
Sources = 1 << 6
}
public class ImportStats
{
public static readonly ImportStats None = new();
public int Updated { get; set; }
public int Created { get; set; }
public int Removed { get; set; }
public static ImportStats operator +(ImportStats c1, ImportStats c2)
{
return new ImportStats
{
Updated = c1.Updated + c2.Updated,
Removed = c1.Removed + c2.Removed,
Created = c1.Created + c2.Created
};
}
public override string ToString()
{
return $"Created: {Created}; Updated: {Updated}; Removed: {Removed}";
}
}
public class ImporterService
{
public ImporterService(
ArchiveOrgImporter _archiveOrg,
SetlistFmImporter _setlistFm,
PhishinImporter _phishin,
PhishNetImporter _phishnet,
JerryGarciaComImporter _jerry,
PanicStreamComImporter _panic,
PhantasyTourImporter _phantasy
)
{
var imps = new ImporterBase[] {_setlistFm, _archiveOrg, _panic, _jerry, _phishin, _phishnet, _phantasy};
importers = new Dictionary<string, ImporterBase>();
foreach (var i in imps)
{
importers[i.ImporterName] = i;
}
}
private IDictionary<string, ImporterBase> importers { get; }
public IEnumerable<ImporterBase> ImportersForArtist(Artist art)
{
return art.upstream_sources.Select(s => importers[s.upstream_source.name]);
}
public ImporterBase ImporterForUpstreamSource(UpstreamSource source)
{
return importers[source.name];
}
public Task<ImportStats> Import(Artist artist, Func<ArtistUpstreamSource, bool> filterUpstreamSources,
PerformContext ctx)
{
return Import(artist, filterUpstreamSources, null, ctx);
}
public async Task<ImportStats> Rebuild(Artist artist, PerformContext ctx)
{
var importer = artist.upstream_sources.First().upstream_source.importer;
ctx?.WriteLine("Rebuilding Shows");
var stats = await importer.RebuildShows(artist);
ctx?.WriteLine("Rebuilding Years");
stats += await importer.RebuildYears(artist);
ctx?.WriteLine("Done!");
return stats;
}
public async Task<ImportStats> Import(Artist artist, Func<ArtistUpstreamSource, bool> filterUpstreamSources,
string showIdentifier, PerformContext ctx)
{
var stats = new ImportStats();
var srcs = artist.upstream_sources.ToList();
ctx?.WriteLine($"Found {srcs.Count} valid importers.");
var prog = ctx?.WriteProgressBar();
await srcs.AsyncForEachWithProgress(prog, async item =>
{
if (filterUpstreamSources != null && !filterUpstreamSources(item))
{
ctx?.WriteLine(
$"Skipping (rejected by filter): {item.upstream_source_id}, {item.upstream_identifier}");
return;
}
ctx?.WriteLine($"Importing with {item.upstream_source_id}, {item.upstream_identifier}");
if (showIdentifier != null)
{
stats += await item.upstream_source.importer.ImportSpecificShowDataForArtist(artist, item,
showIdentifier, ctx);
}
else
{
stats += await item.upstream_source.importer.ImportDataForArtist(artist, item, ctx);
}
});
return stats;
}
}
public abstract class ImporterBase : IDisposable
{
protected readonly RedisService redisService;
public ImporterBase(DbService db, RedisService redisService)
{
this.redisService = redisService;
this.db = db;
http = new HttpClient();
// iPhone on iOS 11.4
http.DefaultRequestHeaders.Add("User-Agent",
"Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1");
http.DefaultRequestHeaders.Add("Accept", "*/*");
}
protected DbService db { get; set; }
protected HttpClient http { get; set; }
public abstract string ImporterName { get; }
private IDictionary<string, int> trackSlugCounts { get; } = new Dictionary<string, int>();
public void Dispose()
{
http.Dispose();
}
public abstract ImportableData ImportableDataForArtist(Artist artist);
public abstract Task<ImportStats> ImportDataForArtist(Artist artist, ArtistUpstreamSource src,
PerformContext ctx);
public abstract Task<ImportStats> ImportSpecificShowDataForArtist(Artist artist, ArtistUpstreamSource src,
string showIdentifier, PerformContext ctx);
/// <summary>
/// Resets the slug counts. This needs to be called after each source is imported otherwise you'll get thing like
/// you-enjoy-myself-624
/// </summary>
public void ResetTrackSlugCounts()
{
trackSlugCounts.Clear();
}
public string Slugify(string full)
{
var slug = Regex.Replace(full.ToLower().Normalize(), @"['.]", "");
slug = Regex.Replace(slug, @"[^a-z0-9\s-]", " ");
return Regex.Replace(slug, @"\s+", " ").Trim().Replace(" ", "-").Trim('-');
}
public string SlugifyTrack(string full)
{
var slug = Slugify(full);
if (trackSlugCounts.ContainsKey(slug))
{
var count = 0;
do
{
count = trackSlugCounts[slug];
count++;
trackSlugCounts[slug] = count;
// keep incrementing until we find a slug that isn't taken
} while (trackSlugCounts.ContainsKey(slug + $"-{count}"));
slug += $"-{count}";
trackSlugCounts[slug] = 1;
}
else
{
trackSlugCounts[slug] = 1;
}
return slug;
}
public async Task<ImportStats> RebuildYears(Artist artist)
{
await db.WithConnection(con => con.ExecuteAsync(@"
BEGIN TRANSACTION;
-- Build Years
WITH year_sources AS (
SELECT
to_char(sh.date, 'YYYY') as year,
COUNT(*) as source_count
FROM
shows sh
JOIN sources s ON sh.id = s.show_id
WHERE
sh.artist_id = @id
GROUP BY
to_char(sh.date, 'YYYY')
)
INSERT INTO
years
(year, show_count, source_count, duration, avg_duration, avg_rating, artist_id, updated_at, uuid)
SELECT
to_char(s.date, 'YYYY') as year,
COUNT(DISTINCT s.id) as show_count,
COUNT(DISTINCT so.id) as source_count,
SUM(so.duration) as duration,
AVG(s.avg_duration) as avg_duration,
AVG(s.avg_rating) as avg_rating,
s.artist_id as artist_id,
MAX(so.updated_at) as updated_at,
md5(s.artist_id || '::year::' || to_char(s.date, 'YYYY'))::uuid as uuid
FROM
shows s
JOIN sources so ON so.show_id = s.id
WHERE
s.artist_id = @id
GROUP BY
s.artist_id, to_char(s.date, 'YYYY')
ON CONFLICT ON CONSTRAINT years_uuid_key
DO
UPDATE SET -- don't update artist_id or year since uuid is based on that
show_count = EXCLUDED.show_count,
source_count = EXCLUDED.source_count,
duration = EXCLUDED.duration,
avg_duration = EXCLUDED.avg_duration,
avg_rating = EXCLUDED.avg_rating,
updated_at = EXCLUDED.updated_at
;
COMMIT;
-- Associate shows with years
UPDATE
shows s
SET
year_id = y.id
FROM
years y
WHERE
y.year = to_char(s.date, 'YYYY')
AND s.artist_id = @id
AND y.artist_id = @id
;
REFRESH MATERIALIZED VIEW show_source_information;
REFRESH MATERIALIZED VIEW venue_show_counts;
", new {artist.id}));
await redisService.db.KeyDeleteAsync(ArtistsController.FullArtistCacheKey(artist));
return ImportStats.None;
}
public async Task<ImportStats> RebuildShows(Artist artist)
{
var sql = @"
-- Update durations
WITH durs AS (
SELECT
t.source_id,
SUM(t.duration) as duration
FROM
source_tracks t
JOIN sources s ON t.source_id = s.id
WHERE
s.artist_id = @id
GROUP BY
t.source_id
)
UPDATE
sources s
SET
duration = d.duration
FROM
durs d
WHERE
s.id = d.source_id
AND s.artist_id = @id
;
BEGIN TRANSACTION;
-- Generate shows table without years or rating information
INSERT INTO
shows
(artist_id, date, display_date, updated_at, tour_id, era_id, venue_id, avg_duration, uuid)
SELECT
--array_agg(source.id) as srcs,
--array_agg(setlist_show.id) as setls,
--array_agg(source.display_date),
--array_agg(setlist_show.date),
source.artist_id,
COALESCE(setlist_show.date, CASE
WHEN MIN(source.display_date) LIKE '%X%' THEN to_date(LEFT(MIN(source.display_date), 10), 'YYYY')
ELSE to_date(LEFT(MIN(source.display_date), 10), 'YYYY-MM-DD')
END) as date,
MIN(source.display_date) as display_date,
MAX(source.updated_at) as updated_at,
MAX(setlist_show.tour_id) as tour_id,
MAX(setlist_show.era_id) as era_id,
COALESCE(MAX(setlist_show.venue_id), MAX(source.venue_id)) as venue_id,
MAX(source.duration) as avg_duration,
md5(source.artist_id || '::show::' || source.display_date)::uuid
FROM
sources source
LEFT JOIN setlist_shows setlist_show ON to_char(setlist_show.date, 'YYYY-MM-DD') = source.display_date AND setlist_show.artist_id = @id
WHERE
(setlist_show.artist_id = @id OR setlist_show.artist_id IS NULL)
AND source.artist_id = @id
GROUP BY
date, source.display_date, source.artist_id
ORDER BY
setlist_show.date
ON CONFLICT ON CONSTRAINT shows_uuid_key
DO
UPDATE SET -- don't update artist_id or display_date since uuid is based on those
date = EXCLUDED.date,
updated_at = EXCLUDED.updated_at,
tour_id = EXCLUDED.tour_id,
era_id = EXCLUDED.era_id,
venue_id = EXCLUDED.venue_id,
avg_duration = EXCLUDED.avg_duration
;
COMMIT;
BEGIN;
-- Associate sources with show
WITH show_assoc AS (
SELECT
src.id as source_id,
sh.id as show_id
FROM
sources src
JOIN shows sh ON src.display_date = sh.display_date AND sh.artist_id = @id
WHERE
src.artist_id = @id
)
UPDATE
sources s
SET
show_id = a.show_id
FROM
show_assoc a
WHERE
a.source_id = s.id
AND s.artist_id = @id
;
COMMIT;
";
if (artist.features.reviews_have_ratings)
{
sql += @"
BEGIN;
-- Update sources with calculated rating/review information
WITH review_info AS (
SELECT
s.id as id,
COALESCE(AVG(rating), 0) as avg,
COUNT(r.rating) as num_reviews
FROM
sources s
LEFT JOIN source_reviews r ON r.source_id = s.id
WHERE
s.artist_id = @id
GROUP BY
s.id
ORDER BY
s.id
)
UPDATE
sources s
SET
avg_rating = i.avg,
num_reviews = i.num_reviews
FROM
review_info i
WHERE
s.id = i.id
AND s.artist_id = @id
;
-- Calculate weighted averages for sources once we have average data and update sources
WITH review_info AS (
SELECT
s.id as id,
COALESCE(AVG(r.rating), 0) as avg,
COUNT(r.rating) as num_reviews
FROM
sources s
LEFT JOIN source_reviews r ON r.source_id = s.id
WHERE
s.artist_id = @id
GROUP BY
s.id
ORDER BY
s.id
), show_info AS (
SELECT
s.show_id,
SUM(s.num_reviews) as num_reviews,
AVG(s.avg_rating) as avg
FROM
sources s
WHERE
s.artist_id = @id
GROUP BY
s.show_id
), weighted_info AS (
SELECT
s.id as id,
i_show.show_id,
i.num_reviews,
i.avg,
i_show.num_reviews,
i_show.avg,
(i_show.num_reviews * i_show.avg) + (i.num_reviews * i.avg) / (i_show.num_reviews + i.num_reviews + 1) as avg_rating_weighted
FROM
sources s
LEFT JOIN review_info i ON i.id = s.id
LEFT JOIN show_info i_show ON i_show.show_id = s.show_id
WHERE
s.artist_id = @id
GROUP BY
s.id, i_show.show_id, i.num_reviews, i.avg, i_show.num_reviews, i_show.avg
ORDER BY
s.id
)
UPDATE
sources s
SET
avg_rating_weighted = i.avg_rating_weighted
FROM
weighted_info i
WHERE
i.id = s.id
AND s.artist_id = @id
;
COMMIT;
";
}
else
{
sql += @"
BEGIN;
-- used for things like Phish where ratings aren't attached to textual reviews
-- Calculate weighted averages for sources once we have average data and update sources
WITH show_info AS (
SELECT
s.show_id,
SUM(s.num_ratings) as num_reviews,
AVG(s.avg_rating) as avg
FROM
sources s
WHERE
s.artist_id = @id
GROUP BY
s.show_id
), weighted_info AS (
SELECT
s.id as id,
i_show.show_id,
s.num_ratings,
s.avg_rating,
i_show.num_reviews,
i_show.avg,
(i_show.num_reviews * i_show.avg) + (s.num_ratings * s.avg_rating) / (i_show.num_reviews + s.num_ratings + 1) as avg_rating_weighted
FROM
sources s
LEFT JOIN show_info i_show ON i_show.show_id = s.show_id
WHERE
s.artist_id = @id
GROUP BY
s.id, i_show.show_id, s.num_ratings, s.avg_rating, i_show.num_reviews, i_show.avg
ORDER BY
s.id
)
UPDATE
sources s
SET
avg_rating_weighted = i.avg_rating_weighted
FROM
weighted_info i
WHERE
i.id = s.id
AND s.artist_id = @id
;
COMMIT;
";
}
sql += @"
BEGIN;
-- Update shows with rating based on weighted averages
WITH rating_ranks AS (
SELECT
sh.id as show_id,
s.avg_rating,
s.updated_at as updated_at,
s.num_reviews,
s.avg_rating_weighted,
RANK() OVER (PARTITION BY sh.id ORDER BY s.avg_rating_weighted DESC) as rank
FROM
sources s
JOIN shows sh ON s.show_id = sh.id
WHERE
s.artist_id = @id
), max_rating AS (
SELECT
show_id,
AVG(avg_rating) as avg_rating,
MAX(updated_at) as updated_at
FROM
rating_ranks
WHERE
rank = 1
GROUP BY
show_id
)
UPDATE
shows s
SET
avg_rating = r.avg_rating,
updated_at = r.updated_at
FROM max_rating r
WHERE
r.show_id = s.id
AND s.artist_id = @id
;
COMMIT;
REFRESH MATERIALIZED VIEW show_source_information;
REFRESH MATERIALIZED VIEW venue_show_counts;
REFRESH MATERIALIZED VIEW source_review_counts;
";
await db.WithConnection(con => con.ExecuteAsync(sql, new {artist.id}));
return ImportStats.None;
}
}
}
| |
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Default
{
public class DefaultSpinnerDisc : CompositeDrawable
{
private DrawableSpinner drawableSpinner;
private const float initial_scale = 1.3f;
private const float idle_alpha = 0.2f;
private const float tracking_alpha = 0.4f;
private Color4 normalColour;
private Color4 completeColour;
private SpinnerTicks ticks;
private int wholeRotationCount;
private readonly BindableBool complete = new BindableBool();
private SpinnerFill fill;
private Container mainContainer;
private SpinnerCentreLayer centre;
private SpinnerBackgroundLayer background;
public DefaultSpinnerDisc()
{
// we are slightly bigger than our parent, to clip the top and bottom of the circle
// this should probably be revisited when scaled spinners are a thing.
Scale = new Vector2(initial_scale);
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, DrawableHitObject drawableHitObject)
{
drawableSpinner = (DrawableSpinner)drawableHitObject;
normalColour = colours.BlueDark;
completeColour = colours.YellowLight;
InternalChildren = new Drawable[]
{
mainContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
background = new SpinnerBackgroundLayer(),
fill = new SpinnerFill
{
Alpha = idle_alpha,
AccentColour = normalColour
},
ticks = new SpinnerTicks
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AccentColour = normalColour
},
}
},
centre = new SpinnerCentreLayer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
};
}
protected override void LoadComplete()
{
base.LoadComplete();
complete.BindValueChanged(complete => updateComplete(complete.NewValue, 200));
drawableSpinner.ApplyCustomUpdateState += updateStateTransforms;
updateStateTransforms(drawableSpinner, drawableSpinner.State.Value);
}
protected override void Update()
{
base.Update();
complete.Value = Time.Current >= drawableSpinner.Result.TimeCompleted;
if (complete.Value)
{
if (checkNewRotationCount)
{
fill.FinishTransforms(false, nameof(Alpha));
fill
.FadeTo(tracking_alpha + 0.2f, 60, Easing.OutExpo)
.Then()
.FadeTo(tracking_alpha, 250, Easing.OutQuint);
}
}
else
{
fill.Alpha = (float)Interpolation.Damp(fill.Alpha, drawableSpinner.RotationTracker.Tracking ? tracking_alpha : idle_alpha, 0.98f, (float)Math.Abs(Clock.ElapsedFrameTime));
}
const float initial_fill_scale = 0.2f;
float targetScale = initial_fill_scale + (1 - initial_fill_scale) * drawableSpinner.Progress;
fill.Scale = new Vector2((float)Interpolation.Lerp(fill.Scale.X, targetScale, Math.Clamp(Math.Abs(Time.Elapsed) / 100, 0, 1)));
mainContainer.Rotation = drawableSpinner.RotationTracker.Rotation;
}
private void updateStateTransforms(DrawableHitObject drawableHitObject, ArmedState state)
{
if (!(drawableHitObject is DrawableSpinner))
return;
Spinner spinner = drawableSpinner.HitObject;
using (BeginAbsoluteSequence(spinner.StartTime - spinner.TimePreempt, true))
{
this.ScaleTo(initial_scale);
this.RotateTo(0);
using (BeginDelayedSequence(spinner.TimePreempt / 2, true))
{
// constant ambient rotation to give the spinner "spinning" character.
this.RotateTo((float)(25 * spinner.Duration / 2000), spinner.TimePreempt + spinner.Duration);
}
using (BeginDelayedSequence(spinner.TimePreempt + spinner.Duration + drawableHitObject.Result.TimeOffset, true))
{
switch (state)
{
case ArmedState.Hit:
this.ScaleTo(initial_scale * 1.2f, 320, Easing.Out);
this.RotateTo(mainContainer.Rotation + 180, 320);
break;
case ArmedState.Miss:
this.ScaleTo(initial_scale * 0.8f, 320, Easing.In);
break;
}
}
}
using (BeginAbsoluteSequence(spinner.StartTime - spinner.TimePreempt, true))
{
centre.ScaleTo(0);
mainContainer.ScaleTo(0);
using (BeginDelayedSequence(spinner.TimePreempt / 2, true))
{
centre.ScaleTo(0.3f, spinner.TimePreempt / 4, Easing.OutQuint);
mainContainer.ScaleTo(0.2f, spinner.TimePreempt / 4, Easing.OutQuint);
using (BeginDelayedSequence(spinner.TimePreempt / 2, true))
{
centre.ScaleTo(0.5f, spinner.TimePreempt / 2, Easing.OutQuint);
mainContainer.ScaleTo(1, spinner.TimePreempt / 2, Easing.OutQuint);
}
}
}
// transforms we have from completing the spinner will be rolled back, so reapply immediately.
using (BeginAbsoluteSequence(spinner.StartTime - spinner.TimePreempt, true))
updateComplete(state == ArmedState.Hit, 0);
}
private void updateComplete(bool complete, double duration)
{
var colour = complete ? completeColour : normalColour;
ticks.FadeAccent(colour.Darken(1), duration);
fill.FadeAccent(colour.Darken(1), duration);
background.FadeAccent(colour, duration);
centre.FadeAccent(colour, duration);
}
private bool checkNewRotationCount
{
get
{
int rotations = (int)(drawableSpinner.Result.RateAdjustedRotation / 360);
if (wholeRotationCount == rotations) return false;
wholeRotationCount = rotations;
return true;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (drawableSpinner != null)
drawableSpinner.ApplyCustomUpdateState -= updateStateTransforms;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedHealthChecksClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListHealthChecksRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
AggregatedListHealthChecksRequest request = new AggregatedListHealthChecksRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, HealthChecksScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (HealthChecksAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, HealthChecksScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListHealthChecksRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
AggregatedListHealthChecksRequest request = new AggregatedListHealthChecksRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, HealthChecksScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((HealthChecksAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, HealthChecksScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, HealthChecksScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (HealthChecksAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, HealthChecksScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, HealthChecksScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((HealthChecksAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, HealthChecksScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteHealthCheckRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
DeleteHealthCheckRequest request = new DeleteHealthCheckRequest
{
RequestId = "",
Project = "",
HealthCheck = "",
};
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteHealthCheckRequest, CallSettings)
// Additional: DeleteAsync(DeleteHealthCheckRequest, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
DeleteHealthCheckRequest request = new DeleteHealthCheckRequest
{
RequestId = "",
Project = "",
HealthCheck = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Delete(project, healthCheck);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.DeleteAsync(project, healthCheck);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetHealthCheckRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
GetHealthCheckRequest request = new GetHealthCheckRequest
{
Project = "",
HealthCheck = "",
};
// Make the request
HealthCheck response = healthChecksClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetHealthCheckRequest, CallSettings)
// Additional: GetAsync(GetHealthCheckRequest, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
GetHealthCheckRequest request = new GetHealthCheckRequest
{
Project = "",
HealthCheck = "",
};
// Make the request
HealthCheck response = await healthChecksClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
// Make the request
HealthCheck response = healthChecksClient.Get(project, healthCheck);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
// Make the request
HealthCheck response = await healthChecksClient.GetAsync(project, healthCheck);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertHealthCheckRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
InsertHealthCheckRequest request = new InsertHealthCheckRequest
{
RequestId = "",
HealthCheckResource = new HealthCheck(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertHealthCheckRequest, CallSettings)
// Additional: InsertAsync(InsertHealthCheckRequest, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
InsertHealthCheckRequest request = new InsertHealthCheckRequest
{
RequestId = "",
HealthCheckResource = new HealthCheck(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, HealthCheck, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
string project = "";
HealthCheck healthCheckResource = new HealthCheck();
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Insert(project, healthCheckResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, HealthCheck, CallSettings)
// Additional: InsertAsync(string, HealthCheck, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
string project = "";
HealthCheck healthCheckResource = new HealthCheck();
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.InsertAsync(project, healthCheckResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListHealthChecksRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
ListHealthChecksRequest request = new ListHealthChecksRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (HealthCheck item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (HealthCheckList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheck item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheck> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheck item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListHealthChecksRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
ListHealthChecksRequest request = new ListHealthChecksRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((HealthCheck item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((HealthCheckList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheck item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheck> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheck item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (HealthCheck item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (HealthCheckList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheck item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheck> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheck item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((HealthCheck item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((HealthCheckList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (HealthCheck item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<HealthCheck> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (HealthCheck item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void PatchRequestObject()
{
// Snippet: Patch(PatchHealthCheckRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
PatchHealthCheckRequest request = new PatchHealthCheckRequest
{
RequestId = "",
HealthCheckResource = new HealthCheck(),
Project = "",
HealthCheck = "",
};
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Patch(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchRequestObjectAsync()
{
// Snippet: PatchAsync(PatchHealthCheckRequest, CallSettings)
// Additional: PatchAsync(PatchHealthCheckRequest, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
PatchHealthCheckRequest request = new PatchHealthCheckRequest
{
RequestId = "",
HealthCheckResource = new HealthCheck(),
Project = "",
HealthCheck = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.PatchAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Patch</summary>
public void Patch()
{
// Snippet: Patch(string, string, HealthCheck, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
HealthCheck healthCheckResource = new HealthCheck();
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Patch(project, healthCheck, healthCheckResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOncePatch(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PatchAsync</summary>
public async Task PatchAsync()
{
// Snippet: PatchAsync(string, string, HealthCheck, CallSettings)
// Additional: PatchAsync(string, string, HealthCheck, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
HealthCheck healthCheckResource = new HealthCheck();
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.PatchAsync(project, healthCheck, healthCheckResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOncePatchAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Update</summary>
public void UpdateRequestObject()
{
// Snippet: Update(UpdateHealthCheckRequest, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
UpdateHealthCheckRequest request = new UpdateHealthCheckRequest
{
RequestId = "",
HealthCheckResource = new HealthCheck(),
Project = "",
HealthCheck = "",
};
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Update(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceUpdate(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateAsync</summary>
public async Task UpdateRequestObjectAsync()
{
// Snippet: UpdateAsync(UpdateHealthCheckRequest, CallSettings)
// Additional: UpdateAsync(UpdateHealthCheckRequest, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
UpdateHealthCheckRequest request = new UpdateHealthCheckRequest
{
RequestId = "",
HealthCheckResource = new HealthCheck(),
Project = "",
HealthCheck = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.UpdateAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceUpdateAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Update</summary>
public void Update()
{
// Snippet: Update(string, string, HealthCheck, CallSettings)
// Create client
HealthChecksClient healthChecksClient = HealthChecksClient.Create();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
HealthCheck healthCheckResource = new HealthCheck();
// Make the request
lro::Operation<Operation, Operation> response = healthChecksClient.Update(project, healthCheck, healthCheckResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceUpdate(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateAsync</summary>
public async Task UpdateAsync()
{
// Snippet: UpdateAsync(string, string, HealthCheck, CallSettings)
// Additional: UpdateAsync(string, string, HealthCheck, CancellationToken)
// Create client
HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string healthCheck = "";
HealthCheck healthCheckResource = new HealthCheck();
// Make the request
lro::Operation<Operation, Operation> response = await healthChecksClient.UpdateAsync(project, healthCheck, healthCheckResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceUpdateAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// .NET Compact Framework has no support for Win32 Console API's
#if !NETCF
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using log4net.Layout;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to the console.
/// </summary>
/// <remarks>
/// <para>
/// ColoredConsoleAppender appends log events to the standard output stream
/// or the error output stream using a layout specified by the
/// user. It also allows the color of a specific type of message to be set.
/// </para>
/// <para>
/// By default, all output is written to the console's standard output stream.
/// The <see cref="Target"/> property can be set to direct the output to the
/// error stream.
/// </para>
/// <para>
/// NOTE: This appender writes directly to the application's attached console
/// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>.
/// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be
/// programmatically redirected (for example NUnit does this to capture program output).
/// This appender will ignore these redirections because it needs to use Win32
/// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/>
/// must be used.
/// </para>
/// <para>
/// When configuring the colored console appender, mapping should be
/// specified to map a logging level to a color. For example:
/// </para>
/// <code lang="XML" escaped="true">
/// <mapping>
/// <level value="ERROR" />
/// <foreColor value="White" />
/// <backColor value="Red, HighIntensity" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <backColor value="Green" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard log4net logging level and ForeColor and BackColor can be any
/// combination of the following values:
/// <list type="bullet">
/// <item><term>Blue</term><description></description></item>
/// <item><term>Green</term><description></description></item>
/// <item><term>Red</term><description></description></item>
/// <item><term>White</term><description></description></item>
/// <item><term>Yellow</term><description></description></item>
/// <item><term>Purple</term><description></description></item>
/// <item><term>Cyan</term><description></description></item>
/// <item><term>HighIntensity</term><description></description></item>
/// </list>
/// </para>
/// </remarks>
/// <author>Rick Hobbs</author>
/// <author>Nicko Cadell</author>
public class ColoredConsoleAppender : AppenderSkeleton
{
#region Colors Enum
/// <summary>
/// The enum of possible color values for use with the color mapping method
/// </summary>
/// <remarks>
/// <para>
/// The following flags can be combined together to
/// form the colors.
/// </para>
/// </remarks>
/// <seealso cref="ColoredConsoleAppender" />
[Flags]
public enum Colors : int
{
/// <summary>
/// color is blue
/// </summary>
Blue = 0x0001,
/// <summary>
/// color is green
/// </summary>
Green = 0x0002,
/// <summary>
/// color is red
/// </summary>
Red = 0x0004,
/// <summary>
/// color is white
/// </summary>
White = Blue | Green | Red,
/// <summary>
/// color is yellow
/// </summary>
Yellow = Red | Green,
/// <summary>
/// color is purple
/// </summary>
Purple = Red | Blue,
/// <summary>
/// color is cyan
/// </summary>
Cyan = Green | Blue,
/// <summary>
/// color is intensified
/// </summary>
HighIntensity = 0x0008,
}
#endregion // Colors Enum
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class.
/// </summary>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
public ColoredConsoleAppender()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout property")]
public ColoredConsoleAppender(ILayout layout) : this(layout, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param>
/// <remarks>
/// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to
/// the standard error output stream. Otherwise, output is written to the standard
/// output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout & Target properties")]
public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream)
{
Layout = layout;
m_writeToErrorStream = writeToErrorStream;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </summary>
/// <value>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </value>
/// <remarks>
/// <para>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </para>
/// </remarks>
virtual public string Target
{
get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; }
set
{
string v = value.Trim();
if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0)
{
m_writeToErrorStream = true;
}
else
{
m_writeToErrorStream = false;
}
}
}
/// <summary>
/// Add a mapping of level to color - done by the config file
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="LevelColors"/> mapping to this appender.
/// Each mapping defines the foreground and background colors
/// for a level.
/// </para>
/// </remarks>
public void AddMapping(LevelColors mapping)
{
m_levelMapping.Add(mapping);
}
#endregion // Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to the console.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
override protected void Append(log4net.Core.LoggingEvent loggingEvent)
{
if (m_consoleOutputWriter != null)
{
IntPtr consoleHandle = IntPtr.Zero;
if (m_writeToErrorStream)
{
// Write to the error stream
consoleHandle = GetStdHandle(STD_ERROR_HANDLE);
}
else
{
// Write to the output stream
consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
}
// Default to white on black
ushort colorInfo = (ushort)Colors.White;
// see if there is a specified lookup
LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
if (levelColors != null)
{
colorInfo = levelColors.CombinedColor;
}
// Render the event to a string
string strLoggingMessage = RenderLoggingEvent(loggingEvent);
// get the current console color - to restore later
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo);
// set the console colors
SetConsoleTextAttribute(consoleHandle, colorInfo);
// Using WriteConsoleW seems to be unreliable.
// If a large buffer is written, say 15,000 chars
// Followed by a larger buffer, say 20,000 chars
// then WriteConsoleW will fail, last error 8
// 'Not enough storage is available to process this command.'
//
// Although the documentation states that the buffer must
// be less that 64KB (i.e. 32,000 WCHARs) the longest string
// that I can write out a the first call to WriteConsoleW
// is only 30,704 chars.
//
// Unlike the WriteFile API the WriteConsoleW method does not
// seem to be able to partially write out from the input buffer.
// It does have a lpNumberOfCharsWritten parameter, but this is
// either the length of the input buffer if any output was written,
// or 0 when an error occurs.
//
// All results above were observed on Windows XP SP1 running
// .NET runtime 1.1 SP1.
//
// Old call to WriteConsoleW:
//
// WriteConsoleW(
// consoleHandle,
// strLoggingMessage,
// (UInt32)strLoggingMessage.Length,
// out (UInt32)ignoreWrittenCount,
// IntPtr.Zero);
//
// Instead of calling WriteConsoleW we use WriteFile which
// handles large buffers correctly. Because WriteFile does not
// handle the codepage conversion as WriteConsoleW does we
// need to use a System.IO.StreamWriter with the appropriate
// Encoding. The WriteFile calls are wrapped up in the
// System.IO.__ConsoleStream internal class obtained through
// the System.Console.OpenStandardOutput method.
//
// See the ActivateOptions method below for the code that
// retrieves and wraps the stream.
// The windows console uses ScrollConsoleScreenBuffer internally to
// scroll the console buffer when the display buffer of the console
// has been used up. ScrollConsoleScreenBuffer fills the area uncovered
// by moving the current content with the background color
// currently specified on the console. This means that it fills the
// whole line in front of the cursor position with the current
// background color.
// This causes an issue when writing out text with a non default
// background color. For example; We write a message with a Blue
// background color and the scrollable area of the console is full.
// When we write the newline at the end of the message the console
// needs to scroll the buffer to make space available for the new line.
// The ScrollConsoleScreenBuffer internals will fill the newly created
// space with the current background color: Blue.
// We then change the console color back to default (White text on a
// Black background). We write some text to the console, the text is
// written correctly in White with a Black background, however the
// remainder of the line still has a Blue background.
//
// This causes a disjointed appearance to the output where the background
// colors change.
//
// This can be remedied by restoring the console colors before causing
// the buffer to scroll, i.e. before writing the last newline. This does
// assume that the rendered message will end with a newline.
//
// Therefore we identify a trailing newline in the message and don't
// write this to the output, then we restore the console color and write
// a newline. Note that we must AutoFlush before we restore the console
// color otherwise we will have no effect.
//
// There will still be a slight artefact for the last line of the message
// will have the background extended to the end of the line, however this
// is unlikely to cause any user issues.
//
// Note that none of the above is visible while the console buffer is scrollable
// within the console window viewport, the effects only arise when the actual
// buffer is full and needs to be scrolled.
char[] messageCharArray = strLoggingMessage.ToCharArray();
int arrayLength = messageCharArray.Length;
bool appendNewline = false;
// Trim off last newline, if it exists
if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n')
{
arrayLength -= 2;
appendNewline = true;
}
// Write to the output stream
m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength);
// Restore the console back to its previous color scheme
SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes);
if (appendNewline)
{
// Write the newline, after changing the color scheme
m_consoleOutputWriter.Write(s_windowsNewline, 0, 2);
}
}
}
private static readonly char[] s_windowsNewline = {'\r', '\n'};
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Initialize the options for this appender
/// </summary>
/// <remarks>
/// <para>
/// Initialize the level to color mappings set on this appender.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)]
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
System.IO.Stream consoleOutputStream = null;
// Use the Console methods to open a Stream over the console std handle
if (m_writeToErrorStream)
{
// Write to the error stream
consoleOutputStream = Console.OpenStandardError();
}
else
{
// Write to the output stream
consoleOutputStream = Console.OpenStandardOutput();
}
// Lookup the codepage encoding for the console
System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP());
// Create a writer around the console stream
m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100);
m_consoleOutputWriter.AutoFlush = true;
// SuppressFinalize on m_consoleOutputWriter because all it will do is flush
// and close the file handle. Because we have set AutoFlush the additional flush
// is not required. The console file handle should not be closed, so we don't call
// Dispose, Close or the finalizer.
GC.SuppressFinalize(m_consoleOutputWriter);
}
#endregion // Override implementation of AppenderSkeleton
#region Public Static Fields
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </para>
/// </remarks>
public const string ConsoleOut = "Console.Out";
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </para>
/// </remarks>
public const string ConsoleError = "Console.Error";
#endregion // Public Static Fields
#region Private Instances Fields
/// <summary>
/// Flag to write output to the error stream rather than the standard output stream
/// </summary>
private bool m_writeToErrorStream = false;
/// <summary>
/// Mapping from level object to color value
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// The console output stream writer to write to
/// </summary>
/// <remarks>
/// <para>
/// This writer is not thread safe.
/// </para>
/// </remarks>
private System.IO.StreamWriter m_consoleOutputWriter = null;
#endregion // Private Instances Fields
#region Win32 Methods
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern int GetConsoleOutputCP();
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool SetConsoleTextAttribute(
IntPtr consoleHandle,
ushort attributes);
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool GetConsoleScreenBufferInfo(
IntPtr consoleHandle,
out CONSOLE_SCREEN_BUFFER_INFO bufferInfo);
// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
// private static extern bool WriteConsoleW(
// IntPtr hConsoleHandle,
// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer,
// UInt32 bufferLen,
// out UInt32 written,
// IntPtr reserved);
//private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10));
private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12));
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern IntPtr GetStdHandle(
UInt32 type);
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public UInt16 x;
public UInt16 y;
}
[StructLayout(LayoutKind.Sequential)]
private struct SMALL_RECT
{
public UInt16 Left;
public UInt16 Top;
public UInt16 Right;
public UInt16 Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct CONSOLE_SCREEN_BUFFER_INFO
{
public COORD dwSize;
public COORD dwCursorPosition;
public ushort wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
#endregion // Win32 Methods
#region LevelColors LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and the color it should be displayed in.
/// </para>
/// </remarks>
public class LevelColors : LevelMappingEntry
{
private Colors m_foreColor;
private Colors m_backColor;
private ushort m_combinedColor = 0;
/// <summary>
/// The mapped foreground color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped foreground color for the specified level.
/// </para>
/// </remarks>
public Colors ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
/// <summary>
/// The mapped background color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped background color for the specified level.
/// </para>
/// </remarks>
public Colors BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
/// <summary>
/// Initialize the options for the object
/// </summary>
/// <remarks>
/// <para>
/// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) );
}
/// <summary>
/// The combined <see cref="ForeColor"/> and <see cref="BackColor"/> suitable for
/// setting the console color.
/// </summary>
internal ushort CombinedColor
{
get { return m_combinedColor; }
}
}
#endregion // LevelColors LevelMapping Entry
}
}
#endif // !NETCF
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_3_4_4 : EcmaTest
{
[Fact]
[Trait("Category", "15.3.4.4")]
public void StrictModeThisValueIsAStringWhichCannotBeConvertedToWrapperObjectsWhenTheFunctionIsCalledWithoutAnArrayOfArguments()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/15.3.4.4-1-s.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void StrictModeThisValueIsANumberWhichCannotBeConvertedToWrapperObjectsWhenTheFunctionIsCalledWithoutAnArrayArgument()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/15.3.4.4-2-s.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void StrictModeThisValueIsABooleanWhichCannotBeConvertedToWrapperObjectsWhenTheFunctionIsCalledWithoutAnArrayOfArguments()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/15.3.4.4-3-s.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheFunctionPrototypeCallLengthPropertyHasTheAttributeReadonly()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A10.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheFunctionPrototypeCallLengthPropertyHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A11.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void FunctionPrototypeCallHasNotPrototypeProperty()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A12.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A13.js", true);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A14.js", true);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A15.js", true);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfIscallableFuncIsFalseThenThrowATypeerrorException4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A16.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodPerformsAFunctionCallUsingTheCallPropertyOfTheObjectIfTheObjectDoesNotHaveACallPropertyATypeerrorExceptionIsThrown()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A1_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodPerformsAFunctionCallUsingTheCallPropertyOfTheObjectIfTheObjectDoesNotHaveACallPropertyATypeerrorExceptionIsThrown2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A1_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheLengthPropertyOfTheCallMethodIs1()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A2_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheLengthPropertyOfTheCallMethodIs12()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A2_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T10.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue5()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue6()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue7()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue8()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T7.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue9()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T8.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNullOrUndefinedTheCalledFunctionIsPassedTheGlobalObjectAsTheThisValue10()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A3_T9.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue5()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue6()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue7()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T7.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void IfThisargIsNotNullDefinedTheCalledFunctionIsPassedToobjectThisargAsTheThisValue8()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A5_T8.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T10.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject5()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject6()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject7()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject8()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T7.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject9()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T8.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheCallMethodTakesOneOrMoreArgumentsThisargAndOptionallyArg1Arg2EtcAndPerformsAFunctionCallUsingTheCallPropertyOfTheObject10()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A6_T9.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void FunctionPrototypeCallCanTBeUsedAsCreateCaller()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A7_T1.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void FunctionPrototypeCallCanTBeUsedAsCreateCaller2()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A7_T2.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void FunctionPrototypeCallCanTBeUsedAsCreateCaller3()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A7_T3.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void FunctionPrototypeCallCanTBeUsedAsCreateCaller4()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A7_T4.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void FunctionPrototypeCallCanTBeUsedAsCreateCaller5()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A7_T5.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void FunctionPrototypeCallCanTBeUsedAsCreateCaller6()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A7_T6.js", false);
}
[Fact]
[Trait("Category", "15.3.4.4")]
public void TheFunctionPrototypeCallLengthPropertyHasTheAttributeDontdelete()
{
RunTest(@"TestCases/ch15/15.3/15.3.4/15.3.4.4/S15.3.4.4_A9.js", false);
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lunet.Helpers;
public class CommandLineApplication
{
// Indicates whether the parser should throw an exception when it runs into an unexpected argument.
// If this field is set to false, the parser will stop parsing when it sees an unexpected argument, and all
// remaining arguments, including the first unexpected argument, will be stored in RemainingArguments property.
private readonly bool _throwOnUnexpectedArg;
public CommandLineApplication(bool throwOnUnexpectedArg = true)
{
_throwOnUnexpectedArg = throwOnUnexpectedArg;
Options = new List<CommandOption>();
Arguments = new List<CommandArgument>();
Commands = new List<CommandLineApplication>();
RemainingArguments = new List<string>();
Invoke = () => {};
}
public CommandLineApplication Parent { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public string Syntax { get; set; }
public string Description { get; set; }
public List<CommandOption> Options { get; private set; }
public CommandOption OptionHelp { get; private set; }
public CommandOption OptionVersion { get; private set; }
public List<CommandArgument> Arguments { get; private set; }
public List<string> RemainingArguments { get; private set; }
public bool IsShowingInformation { get; protected set; } // Is showing help or version?
public Action Invoke { get; set; }
public Func<string> LongVersionGetter { get; set; }
public Func<string> ShortVersionGetter { get; set; }
public List<CommandLineApplication> Commands { get; private set; }
public bool HandleResponseFiles { get; set; }
public bool AllowArgumentSeparator { get; set; }
public CommandLineApplication Command(string name, Action<CommandLineApplication> configuration,
bool throwOnUnexpectedArg = true)
{
var command = new CommandLineApplication(throwOnUnexpectedArg) { Name = name, Parent = this };
Commands.Add(command);
configuration(command);
return command;
}
public CommandOption Option(string template, string description, CommandOptionType optionType)
{
return Option(template, description, optionType, _ => { });
}
public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration)
{
var option = new CommandOption(template, optionType) { Description = description };
Options.Add(option);
configuration(option);
return option;
}
public CommandArgument Argument(string name, string description, bool multipleValues = false)
{
return Argument(name, description, _ => { }, multipleValues);
}
public CommandArgument Argument(string name, string description, Action<CommandArgument> configuration, bool multipleValues = false)
{
var lastArg = Arguments.LastOrDefault();
if (lastArg != null && lastArg.MultipleValues)
{
var message = string.Format("The last argument '{0}' accepts multiple values. No more argument can be added.",
lastArg.Name);
throw new InvalidOperationException(message);
}
var argument = new CommandArgument { Name = name, Description = description, MultipleValues = multipleValues };
Arguments.Add(argument);
configuration(argument);
return argument;
}
public void Parse(params string[] args)
{
CommandLineApplication command = this;
CommandOption option = null;
IEnumerator<CommandArgument> arguments = null;
if (HandleResponseFiles)
{
args = ExpandResponseFiles(args).ToArray();
}
for (var index = 0; index < args.Length; index++)
{
var arg = args[index];
var processed = false;
if (!processed && option == null)
{
string[] longOption = null;
string[] shortOption = null;
if (arg.StartsWith("--"))
{
longOption = arg.Substring(2).Split(new[] { ':', '=' }, 2);
}
else if (arg.StartsWith("-"))
{
shortOption = arg.Substring(1).Split(new[] { ':', '=' }, 2);
}
if (longOption != null)
{
processed = true;
string longOptionName = longOption[0];
option = command.Options.SingleOrDefault(opt => string.Equals(opt.LongName, longOptionName, StringComparison.Ordinal));
if (option == null)
{
if (string.IsNullOrEmpty(longOptionName) && !command._throwOnUnexpectedArg && AllowArgumentSeparator)
{
// a stand-alone "--" is the argument separator, so skip it and
// handle the rest of the args as unexpected args
index++;
}
HandleUnexpectedArg(command, args, index, argTypeName: "option");
break;
}
// If we find a help/version option, show information and stop parsing
if (command.OptionHelp == option)
{
command.ShowHelp();
return;
}
else if (command.OptionVersion == option)
{
command.ShowVersion();
return;
}
if (longOption.Length == 2)
{
if (!option.TryParse(longOption[1]))
{
command.ShowHint();
throw new CommandParsingException(command, $"Unexpected value '{longOption[1]}' for option '{option.LongName}'");
}
option = null;
}
else if (option.OptionType == CommandOptionType.NoValue || option.OptionType == CommandOptionType.BoolValue)
{
// No value is needed for this option
option.TryParse(null);
option = null;
}
}
if (shortOption != null)
{
processed = true;
option = command.Options.SingleOrDefault(opt => string.Equals(opt.ShortName, shortOption[0], StringComparison.Ordinal));
// If not a short option, try symbol option
if (option == null)
{
option = command.Options.SingleOrDefault(opt => string.Equals(opt.SymbolName, shortOption[0], StringComparison.Ordinal));
}
if (option == null)
{
HandleUnexpectedArg(command, args, index, argTypeName: "option");
break;
}
// If we find a help/version option, show information and stop parsing
if (command.OptionHelp == option)
{
command.ShowHelp();
return;
}
else if (command.OptionVersion == option)
{
command.ShowVersion();
return;
}
if (shortOption.Length == 2)
{
if (!option.TryParse(shortOption[1]))
{
command.ShowHint();
throw new CommandParsingException(command, $"Unexpected value '{shortOption[1]}' for option '{option.LongName}'");
}
option = null;
}
else if (option.OptionType == CommandOptionType.NoValue || option.OptionType == CommandOptionType.BoolValue)
{
// No value is needed for this option
option.TryParse(null);
option = null;
}
}
}
if (!processed && option != null)
{
processed = true;
if (!option.TryParse(arg))
{
command.ShowHint();
throw new CommandParsingException(command, $"Unexpected value '{arg}' for option '{option.LongName}'");
}
option = null;
}
if (!processed && arguments == null)
{
var currentCommand = command;
foreach (var subcommand in command.Commands)
{
if (string.Equals(subcommand.Name, arg, StringComparison.OrdinalIgnoreCase))
{
processed = true;
command = subcommand;
break;
}
}
// If we detect a subcommand
if (command != currentCommand)
{
processed = true;
}
}
if (!processed)
{
if (arguments == null)
{
arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator());
}
if (arguments.MoveNext())
{
processed = true;
arguments.Current.Values.Add(arg);
}
}
if (!processed)
{
HandleUnexpectedArg(command, args, index, argTypeName: "command or argument");
break;
}
}
if (option != null)
{
command.ShowHint();
throw new CommandParsingException(command, $"Missing value for option '{option.LongName}'");
}
command.Invoke();
}
// Helper method that adds a help option
public CommandOption HelpOption(string template)
{
// Help option is special because we stop parsing once we see it
// So we store it separately for further use
OptionHelp = Option(template, "Show help information", CommandOptionType.NoValue);
return OptionHelp;
}
public CommandOption VersionOption(string template,
string shortFormVersion,
string longFormVersion = null)
{
if (longFormVersion == null)
{
return VersionOption(template, () => shortFormVersion);
}
else
{
return VersionOption(template, () => shortFormVersion, () => longFormVersion);
}
}
// Helper method that adds a version option
public CommandOption VersionOption(string template,
Func<string> shortFormVersionGetter,
Func<string> longFormVersionGetter = null)
{
// Version option is special because we stop parsing once we see it
// So we store it separately for further use
OptionVersion = Option(template, "Show version information", CommandOptionType.NoValue);
ShortVersionGetter = shortFormVersionGetter;
LongVersionGetter = longFormVersionGetter ?? shortFormVersionGetter;
return OptionVersion;
}
// Show short hint that reminds users to use help option
public void ShowHint()
{
if (OptionHelp != null)
{
Console.WriteLine(string.Format("Specify --{0} for a list of available options and commands.", OptionHelp.LongName));
}
}
// Show full help
public void ShowHelp(string commandName = null)
{
var headerBuilder = new StringBuilder("Usage:");
for (var cmd = this; cmd != null; cmd = cmd.Parent)
{
cmd.IsShowingInformation = true;
headerBuilder.Insert(6, string.Format(" {0}", cmd.Name));
}
CommandLineApplication target;
if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase))
{
target = this;
}
else
{
target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase));
if (target != null)
{
headerBuilder.AppendFormat(" {0}", commandName);
}
else
{
// The command name is invalid so don't try to show help for something that doesn't exist
target = this;
}
}
var optionsBuilder = new StringBuilder();
var commandsBuilder = new StringBuilder();
var argumentsBuilder = new StringBuilder();
if (target.Arguments.Any())
{
headerBuilder.Append(" [arguments]");
argumentsBuilder.AppendLine();
argumentsBuilder.AppendLine("Arguments:");
var maxArgLen = MaxArgumentLength(target.Arguments);
var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxArgLen + 2);
foreach (var arg in target.Arguments)
{
argumentsBuilder.AppendFormat(outputFormat, arg.Name, arg.Description);
argumentsBuilder.AppendLine();
}
}
if (target.Options.Any())
{
headerBuilder.Append(" [options]");
optionsBuilder.AppendLine();
optionsBuilder.AppendLine("Options:");
var maxOptLen = MaxOptionTemplateLength(target.Options);
var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxOptLen + 2);
foreach (var opt in target.Options)
{
optionsBuilder.AppendFormat(outputFormat, opt.Template, opt.Description);
optionsBuilder.AppendLine();
}
}
if (target.Commands.Any())
{
headerBuilder.Append(" [command]");
commandsBuilder.AppendLine();
commandsBuilder.AppendLine("Commands:");
var maxCmdLen = MaxCommandLength(target.Commands);
var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxCmdLen + 2);
foreach (var cmd in target.Commands.OrderBy(c => c.Name))
{
commandsBuilder.AppendFormat(outputFormat, cmd.Name, cmd.Description);
commandsBuilder.AppendLine();
}
if (OptionHelp != null)
{
commandsBuilder.AppendLine();
commandsBuilder.AppendFormat("Use \"{0} [command] --help\" for more information about a command.", Name);
commandsBuilder.AppendLine();
}
}
if (target.AllowArgumentSeparator)
{
headerBuilder.Append(" [[--] <arg>...]]");
}
headerBuilder.AppendLine();
var nameAndVersion = new StringBuilder();
nameAndVersion.AppendLine(GetFullNameAndVersion());
nameAndVersion.AppendLine();
Console.Write("{0}{1}{2}{3}{4}", nameAndVersion, headerBuilder, argumentsBuilder, optionsBuilder, commandsBuilder);
}
public void ShowVersion()
{
for (var cmd = this; cmd != null; cmd = cmd.Parent)
{
cmd.IsShowingInformation = true;
}
Console.WriteLine(FullName);
Console.WriteLine(LongVersionGetter());
}
public string GetFullNameAndVersion()
{
return ShortVersionGetter == null ? FullName : string.Format("{0} {1}", FullName, ShortVersionGetter());
}
public void ShowRootCommandFullNameAndVersion()
{
var rootCmd = this;
while (rootCmd.Parent != null)
{
rootCmd = rootCmd.Parent;
}
Console.WriteLine(rootCmd.GetFullNameAndVersion());
Console.WriteLine();
}
private int MaxOptionTemplateLength(IEnumerable<CommandOption> options)
{
var maxLen = 0;
foreach (var opt in options)
{
maxLen = opt.Template.Length > maxLen ? opt.Template.Length : maxLen;
}
return maxLen;
}
private int MaxCommandLength(IEnumerable<CommandLineApplication> commands)
{
var maxLen = 0;
foreach (var cmd in commands)
{
maxLen = cmd.Name.Length > maxLen ? cmd.Name.Length : maxLen;
}
return maxLen;
}
private int MaxArgumentLength(IEnumerable<CommandArgument> arguments)
{
var maxLen = 0;
foreach (var arg in arguments)
{
maxLen = arg.Name.Length > maxLen ? arg.Name.Length : maxLen;
}
return maxLen;
}
private void HandleUnexpectedArg(CommandLineApplication command, string[] args, int index, string argTypeName)
{
if (command._throwOnUnexpectedArg)
{
command.ShowHint();
throw new CommandParsingException(command, $"Unrecognized {argTypeName} '{args[index]}'");
}
else
{
// All remaining arguments are stored for further use
command.RemainingArguments.AddRange(new ArraySegment<string>(args, index, args.Length - index));
}
}
private IEnumerable<string> ExpandResponseFiles(IEnumerable<string> args)
{
foreach (var arg in args)
{
if (!arg.StartsWith("@", StringComparison.Ordinal))
{
yield return arg;
}
else
{
var fileName = arg.Substring(1);
var responseFileArguments = ParseResponseFile(fileName);
// ParseResponseFile can suppress expanding this response file by
// returning null. In that case, we'll treat the response
// file token as a regular argument.
if (responseFileArguments == null)
{
yield return arg;
}
else
{
foreach (var responseFileArgument in responseFileArguments)
yield return responseFileArgument.Trim();
}
}
}
}
private IEnumerable<string> ParseResponseFile(string fileName)
{
if (!HandleResponseFiles)
return null;
if (!File.Exists(fileName))
{
throw new InvalidOperationException($"Response file '{fileName}' doesn't exist.");
}
return File.ReadLines(fileName);
}
private class CommandArgumentEnumerator : IEnumerator<CommandArgument>
{
private readonly IEnumerator<CommandArgument> _enumerator;
public CommandArgumentEnumerator(IEnumerator<CommandArgument> enumerator)
{
_enumerator = enumerator;
}
public CommandArgument Current
{
get
{
return _enumerator.Current;
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public void Dispose()
{
_enumerator.Dispose();
}
public bool MoveNext()
{
if (Current == null || !Current.MultipleValues)
{
return _enumerator.MoveNext();
}
// If current argument allows multiple values, we don't move forward and
// all later values will be added to current CommandArgument.Values
return true;
}
public void Reset()
{
_enumerator.Reset();
}
}
}
| |
#define USE_TRACING
#define DEBUG
using System;
using System.Collections.Generic;
using Google.AccessControl;
using Google.Contacts;
using Google.Documents;
using Google.GData.AccessControl;
using Google.GData.Calendar;
using Google.GData.Client.UnitTests;
using Google.GData.Extensions;
using NUnit.Framework;
namespace Google.GData.Client.LiveTests
{
[TestFixture]
[Category("LiveTest")]
public class OAuthTestSuite : BaseLiveTestClass
{
/// <summary>
/// the setup method
/// </summary>
[SetUp]
public override void InitTest()
{
Tracing.TraceCall();
base.InitTest();
}
/// <summary>
/// the end it all method
/// </summary>
[TearDown]
public override void EndTest()
{
Tracing.ExitTracing();
}
protected string oAuthConsumerKey;
protected string oAuthConsumerSecret;
protected string oAuthDomain;
protected string oAuthUser;
protected string oAuthToken;
protected string oAuthTokenSecret;
protected string oAuthScope;
protected string oAuthSignatureMethod;
/// <summary>
/// private void ReadConfigFile()
/// </summary>
/// <returns> </returns>
protected override void ReadConfigFile()
{
base.ReadConfigFile();
if (unitTestConfiguration.Contains("OAUTHCONSUMERKEY"))
{
oAuthConsumerKey = (string) unitTestConfiguration["OAUTHCONSUMERKEY"];
}
if (unitTestConfiguration.Contains("OAUTHCONSUMERSECRET"))
{
oAuthConsumerSecret = (string) unitTestConfiguration["OAUTHCONSUMERSECRET"];
}
if (unitTestConfiguration.Contains("OAUTHDOMAIN"))
{
oAuthDomain = (string) unitTestConfiguration["OAUTHDOMAIN"];
}
if (unitTestConfiguration.Contains("OAUTHUSER"))
{
oAuthUser = (string) unitTestConfiguration["OAUTHUSER"];
}
if (unitTestConfiguration.Contains("OAUTHTOKEN"))
{
oAuthToken = (string) unitTestConfiguration["OAUTHTOKEN"];
}
if (unitTestConfiguration.Contains("OAUTHTOKENSECRET"))
{
oAuthTokenSecret = (string) unitTestConfiguration["OAUTHTOKENSECRET"];
}
if (unitTestConfiguration.Contains("OAUTHSCOPE"))
{
oAuthScope = (string) unitTestConfiguration["OAUTHSCOPE"];
}
if (unitTestConfiguration.Contains("OAUTHSIGNATUREMETHOD"))
{
oAuthSignatureMethod = (string) unitTestConfiguration["OAUTHSIGNATUREMETHOD"];
}
}
/// <summary>
/// runs an authentication test with 2 legged oauth
/// </summary>
[Test]
public void OAuth2LeggedAuthenticationTest()
{
Tracing.TraceMsg("Entering OAuth2LeggedAuthenticationTest");
CalendarService service = new CalendarService("OAuthTestcode");
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode");
requestFactory.ConsumerKey = oAuthConsumerKey;
requestFactory.ConsumerSecret = oAuthConsumerSecret;
requestFactory.UseSSL = true;
service.RequestFactory = requestFactory;
CalendarEntry calendar = new CalendarEntry();
calendar.Title.Text = "Test OAuth";
OAuthUri postUri = new OAuthUri("https://www.google.com/calendar/feeds/default/owncalendars/full",
oAuthUser,
oAuthDomain);
CalendarEntry createdCalendar = service.Insert(postUri, calendar);
}
[Test]
public void OAuth2LeggedContactsTest()
{
Tracing.TraceMsg("Entering OAuth2LeggedContactsTest");
RequestSettings rs = new RequestSettings(ApplicationName, oAuthConsumerKey,
oAuthConsumerSecret, oAuthUser, oAuthDomain);
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
// modify one
foreach (Contact c in f.Entries)
{
c.Title = "new title";
cr.Update(c);
break;
}
Contact entry = new Contact();
entry.AtomEntry = ObjectModelHelper.CreateContactEntry(1);
entry.PrimaryEmail.Address = "[email protected]";
Contact e = cr.Insert(f, entry);
cr.Delete(e);
}
[Test]
public void OAuth2LeggedDocumentsTest()
{
Tracing.TraceMsg("Entering OAuth2LeggedDocumentsTest");
RequestSettings rs = new RequestSettings(ApplicationName, oAuthConsumerKey,
oAuthConsumerSecret, oAuthUser, oAuthDomain);
DocumentsRequest dr = new DocumentsRequest(rs);
Feed<Document> f = dr.GetDocuments();
// modify one
foreach (Document d in f.Entries)
{
string s = d.AtomEntry.EditUri.ToString();
d.AtomEntry.EditUri = new AtomUri(s.Replace("@", "%40"));
dr.Update(d);
AclQuery q = new AclQuery();
q.Uri = d.AccessControlList;
Feed<Acl> facl = dr.Get<Acl>(q);
foreach (Acl a in facl.Entries)
{
s = a.AclEntry.EditUri.ToString();
a.AclEntry.EditUri = new AtomUri(s.Replace("@", "%40"));
dr.Update(a);
}
}
}
/// <summary>
/// runs an authentication test using OAUTH, inserts lots of new contacts
/// and deletes them again
/// </summary>
[Test]
public void OAuth2LeggedModelContactsBatchInsertTest()
{
const int numberOfInserts = 10;
Tracing.TraceMsg("Entering OAuth2LeggedModelContactsBatchInsertTest");
RequestSettings rs = new RequestSettings(ApplicationName, oAuthConsumerKey,
oAuthConsumerSecret, oAuthUser, oAuthDomain);
ContactsTestSuite.DeleteAllContacts(rs);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
int originalCount = f.TotalResults;
PhoneNumber p = null;
List<Contact> inserted = new List<Contact>();
if (f != null)
{
Assert.IsTrue(f.Entries != null, "the contacts needs entries");
for (int i = 0; i < numberOfInserts; i++)
{
Contact entry = new Contact();
entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i);
entry.PrimaryEmail.Address = "joe" + i + "@doe.com";
p = entry.PrimaryPhonenumber;
inserted.Add(cr.Insert(f, entry));
}
}
List<Contact> list = new List<Contact>();
f = cr.GetContacts();
foreach (Contact e in f.Entries)
{
list.Add(e);
}
Assert.AreEqual(numberOfInserts, inserted.Count);
// now delete them again
ContactsTestSuite.DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch));
}
/// <summary>
/// runs an authentication test with 3-legged oauth
/// </summary>
[Test]
public void OAuth3LeggedAuthenticationTest()
{
Tracing.TraceMsg("Entering OAuth3LeggedAuthenticationTest");
CalendarService service = new CalendarService("OAuthTestcode");
OAuthParameters parameters = new OAuthParameters
{
ConsumerKey = oAuthConsumerKey,
ConsumerSecret = oAuthConsumerSecret,
Token = oAuthToken,
TokenSecret = oAuthTokenSecret,
Scope = oAuthScope,
SignatureMethod = oAuthSignatureMethod
};
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode", parameters);
service.RequestFactory = requestFactory;
CalendarEntry calendar = new CalendarEntry();
calendar.Title.Text = "Test OAuth";
Uri postUri = new Uri("https://www.google.com/calendar/feeds/default/owncalendars/full");
CalendarEntry createdCalendar = service.Insert(postUri, calendar);
// delete the new entry
createdCalendar.Delete();
}
/// <summary>
/// Verifies the signature generation
/// </summary>
[Test]
public void OAuthBaseGenerateOAuthSignatureTest()
{
Tracing.TraceMsg("Entering OAuthBaseGenerateOAuthSignatureTest");
string sig = OAuthBase.GenerateOAuthSignatureEncoded("djr9rjt0jd78jf88", "");
Assert.AreEqual("djr9rjt0jd78jf88%26", sig);
sig = OAuthBase.GenerateOAuthSignatureEncoded("djr9rjt0jd78jf88", "jjd99$tj88uiths3");
Assert.AreEqual("djr9rjt0jd78jf88%26jjd99%2524tj88uiths3", sig);
sig = OAuthBase.GenerateOAuthSignatureEncoded("djr9rjt0jd78jf88", "jjd999tj88uiths3");
Assert.AreEqual("djr9rjt0jd78jf88%26jjd999tj88uiths3", sig);
}
/// <summary>
/// Verifies the signature generation
/// </summary>
[Test]
public void OAuthBaseSignatureTest()
{
Tracing.TraceMsg("Entering OAuthBaseSignatureTest");
Uri uri = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original");
string sig = OAuthBase.GenerateSignatureBase(
uri,
"dpf43f3p2l4k3l03",
"nnch734d00sl2jdk",
null,
"GET",
"1191242096",
"kllo9940pd9333jh",
"HMAC-SHA1");
Assert.AreEqual(
"GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal",
sig);
// the file parameter is set twice, only the last value counts
uri = new Uri("http://photos.example.net/photos?file=party.jpg&size=original&file=vacation.jpg");
sig = OAuthBase.GenerateSignatureBase(
uri,
"dpf43f3p2l4k3l03",
"nnch734d00sl2jdk",
null,
"GET",
"1191242096",
"kllo9940pd9333jh",
"HMAC-SHA1");
Assert.AreEqual(
"GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal",
sig);
}
/// <summary>
/// Verifies the signed signature generation
/// </summary>
[Test]
public void OAuthBaseSigningTest()
{
Tracing.TraceMsg("Entering OAuthBaseSigningTest");
Uri uri = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original");
string sig = OAuthBase.GenerateSignature(
uri,
"dpf43f3p2l4k3l03",
"kd94hf93k423kf44",
"nnch734d00sl2jdk",
"pfkkdhi9sl3r4s00",
"GET",
"1191242096",
"kllo9940pd9333jh",
OAuthBase.HMACSHA1SignatureType);
Assert.AreEqual("tR3+Ty81lMeYAr/Fid0kMTYa/WM=", sig);
}
}
}
| |
// 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;
using System.Threading;
namespace System.ServiceModel.Channels
{
internal enum LifetimeState
{
Opened,
Closing,
Closed
}
internal class LifetimeManager
{
private bool _aborted;
private ICommunicationWaiter _busyWaiter;
private int _busyWaiterCount;
private LifetimeState _state;
public LifetimeManager(object mutex)
{
ThisLock = mutex;
_state = LifetimeState.Opened;
}
public int BusyCount { get; private set; }
protected LifetimeState State
{
get { return _state; }
}
protected object ThisLock { get; }
public void Abort()
{
lock (ThisLock)
{
if (State == LifetimeState.Closed || _aborted)
{
return;
}
_aborted = true;
_state = LifetimeState.Closing;
}
OnAbort();
_state = LifetimeState.Closed;
}
private void ThrowIfNotOpened()
{
if (!_aborted && _state != LifetimeState.Opened)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(GetType().ToString()));
}
}
public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
lock (ThisLock)
{
ThrowIfNotOpened();
_state = LifetimeState.Closing;
}
return OnBeginClose(timeout, callback, state);
}
public void Close(TimeSpan timeout)
{
lock (ThisLock)
{
ThrowIfNotOpened();
_state = LifetimeState.Closing;
}
OnClose(timeout);
_state = LifetimeState.Closed;
}
private CommunicationWaitResult CloseCore(TimeSpan timeout, bool aborting)
{
ICommunicationWaiter busyWaiter = null;
CommunicationWaitResult result = CommunicationWaitResult.Succeeded;
lock (ThisLock)
{
if (BusyCount > 0)
{
if (_busyWaiter != null)
{
if (!aborting && _aborted)
{
return CommunicationWaitResult.Aborted;
}
busyWaiter = _busyWaiter;
}
else
{
busyWaiter = new SyncCommunicationWaiter(ThisLock);
_busyWaiter = busyWaiter;
}
Interlocked.Increment(ref _busyWaiterCount);
}
}
if (busyWaiter != null)
{
result = busyWaiter.Wait(timeout, aborting);
if (Interlocked.Decrement(ref _busyWaiterCount) == 0)
{
busyWaiter.Dispose();
_busyWaiter = null;
}
}
return result;
}
protected void DecrementBusyCount()
{
ICommunicationWaiter busyWaiter = null;
bool empty = false;
lock (ThisLock)
{
if (BusyCount <= 0)
{
throw Fx.AssertAndThrow("LifetimeManager.DecrementBusyCount: (this.busyCount > 0)");
}
if (--BusyCount == 0)
{
if (_busyWaiter != null)
{
busyWaiter = _busyWaiter;
Interlocked.Increment(ref _busyWaiterCount);
}
empty = true;
}
}
if (busyWaiter != null)
{
busyWaiter.Signal();
if (Interlocked.Decrement(ref _busyWaiterCount) == 0)
{
busyWaiter.Dispose();
_busyWaiter = null;
}
}
if (empty && State == LifetimeState.Opened)
{
OnEmpty();
}
}
public void EndClose(IAsyncResult result)
{
OnEndClose(result);
_state = LifetimeState.Closed;
}
protected virtual void IncrementBusyCount()
{
lock (ThisLock)
{
Fx.Assert(State == LifetimeState.Opened, "LifetimeManager.IncrementBusyCount: (this.State == LifetimeState.Opened)");
BusyCount++;
}
}
protected virtual void IncrementBusyCountWithoutLock()
{
Fx.Assert(State == LifetimeState.Opened, "LifetimeManager.IncrementBusyCountWithoutLock: (this.State == LifetimeState.Opened)");
BusyCount++;
}
protected virtual void OnAbort()
{
// We have decided not to make this configurable
CloseCore(TimeSpan.FromSeconds(1), true);
}
protected virtual IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
CloseCommunicationAsyncResult closeResult = null;
lock (ThisLock)
{
if (BusyCount > 0)
{
if (_busyWaiter != null)
{
Fx.Assert(_aborted, "LifetimeManager.OnBeginClose: (this.aborted == true)");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(GetType().ToString()));
}
else
{
closeResult = new CloseCommunicationAsyncResult(timeout, callback, state, ThisLock);
Fx.Assert(_busyWaiter == null, "LifetimeManager.OnBeginClose: (this.busyWaiter == null)");
_busyWaiter = closeResult;
Interlocked.Increment(ref _busyWaiterCount);
}
}
}
if (closeResult != null)
{
return closeResult;
}
else
{
return new CompletedAsyncResult(callback, state);
}
}
protected virtual void OnClose(TimeSpan timeout)
{
switch (CloseCore(timeout, false))
{
case CommunicationWaitResult.Expired:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(SR.SFxCloseTimedOut1, timeout)));
case CommunicationWaitResult.Aborted:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(GetType().ToString()));
}
}
protected virtual void OnEmpty()
{
}
protected virtual void OnEndClose(IAsyncResult result)
{
if (result is CloseCommunicationAsyncResult)
{
CloseCommunicationAsyncResult.End(result);
if (Interlocked.Decrement(ref _busyWaiterCount) == 0)
{
_busyWaiter.Dispose();
_busyWaiter = null;
}
}
else
{
CompletedAsyncResult.End(result);
}
}
}
internal enum CommunicationWaitResult
{
Waiting,
Succeeded,
Expired,
Aborted
}
internal interface ICommunicationWaiter : IDisposable
{
void Signal();
CommunicationWaitResult Wait(TimeSpan timeout, bool aborting);
}
internal class CloseCommunicationAsyncResult : AsyncResult, ICommunicationWaiter
{
private CommunicationWaitResult _result;
private Timer _timer;
private TimeoutHelper _timeoutHelper;
private TimeSpan _timeout;
public CloseCommunicationAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, object mutex)
: base(callback, state)
{
_timeout = timeout;
_timeoutHelper = new TimeoutHelper(timeout);
ThisLock = mutex;
if (timeout < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(SR.SFxCloseTimedOut1, timeout)));
}
_timer = new Timer(new TimerCallback(new Action<object>(TimeoutCallback)), this, timeout, TimeSpan.FromMilliseconds(-1));
}
private object ThisLock { get; }
public void Dispose()
{
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseCommunicationAsyncResult>(result);
}
public void Signal()
{
lock (ThisLock)
{
if (_result != CommunicationWaitResult.Waiting)
{
return;
}
_result = CommunicationWaitResult.Succeeded;
}
_timer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1));
Complete(false);
}
private void Timeout()
{
lock (ThisLock)
{
if (_result != CommunicationWaitResult.Waiting)
{
return;
}
_result = CommunicationWaitResult.Expired;
}
Complete(false, new TimeoutException(SR.Format(SR.SFxCloseTimedOut1, _timeout)));
}
private static void TimeoutCallback(object state)
{
CloseCommunicationAsyncResult closeResult = (CloseCommunicationAsyncResult)state;
closeResult.Timeout();
}
public CommunicationWaitResult Wait(TimeSpan timeout, bool aborting)
{
if (timeout < TimeSpan.Zero)
{
return CommunicationWaitResult.Expired;
}
// Synchronous Wait on AsyncResult should only be called in Abort code-path
Fx.Assert(aborting, "CloseCommunicationAsyncResult.Wait: (aborting == true)");
lock (ThisLock)
{
if (_result != CommunicationWaitResult.Waiting)
{
return _result;
}
_result = CommunicationWaitResult.Aborted;
}
_timer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1));
TimeoutHelper.WaitOne(AsyncWaitHandle, timeout);
Complete(false, new ObjectDisposedException(GetType().ToString()));
return _result;
}
}
internal class SyncCommunicationWaiter : ICommunicationWaiter
{
private bool _closed;
private CommunicationWaitResult _result;
private ManualResetEvent _waitHandle;
public SyncCommunicationWaiter(object mutex)
{
ThisLock = mutex;
_waitHandle = new ManualResetEvent(false);
}
private object ThisLock { get; }
public void Dispose()
{
lock (ThisLock)
{
if (_closed)
{
return;
}
_closed = true;
_waitHandle.Dispose();
}
}
public void Signal()
{
lock (ThisLock)
{
if (_closed)
{
return;
}
_waitHandle.Set();
}
}
public CommunicationWaitResult Wait(TimeSpan timeout, bool aborting)
{
if (_closed)
{
return CommunicationWaitResult.Aborted;
}
if (timeout < TimeSpan.Zero)
{
return CommunicationWaitResult.Expired;
}
if (aborting)
{
_result = CommunicationWaitResult.Aborted;
}
bool expired = !TimeoutHelper.WaitOne(_waitHandle, timeout);
lock (ThisLock)
{
if (_result == CommunicationWaitResult.Waiting)
{
_result = (expired ? CommunicationWaitResult.Expired : CommunicationWaitResult.Succeeded);
}
}
lock (ThisLock)
{
if (!_closed)
{
_waitHandle.Set(); // unblock other waiters if there are any
}
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class AverageTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.Average(), q.Average());
}
[Fact]
public void SameResultsRepeatCallsNullableLongQuery()
{
var q = from x in new long?[] { Int32.MaxValue, 0, 255, 127, 128, 1, 33, 99, null, Int32.MinValue }
select x;
Assert.Equal(q.Average(), q.Average());
}
[Fact]
public void EmptyNullableFloatSource()
{
float?[] source = { };
float? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void EmptyNullableFloatSourceWithSelector()
{
float?[] source = { };
float? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullNFloatSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Average());
}
[Fact]
public void NullNFloatSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float?>)null).Average(i => i));
}
[Fact]
public void NullNFloatFunc()
{
Func<float?, float?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().Average(selector));
}
[Fact]
public void SingleNullableFloatSource()
{
float?[] source = { float.MinValue };
float? expected = float.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatAllZeroSource()
{
float?[] source = { 0f, 0f, 0f, 0f, 0f };
float? expected = 0f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatSource()
{
float?[] source = { 5.5f, 0, null, null, null, 15.5f, 40.5f, null, null, -23.5f };
float? expected = 7.6f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatSourceOnlyOneNotNull()
{
float?[] source = { null, null, null, null, 45f };
float? expected = 45f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatSourceAllNull()
{
float?[] source = { null, null, null, null, null };
float? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableFloatSourceAllNullWithSelector()
{
float?[] source = { null, null, null, null, null };
float? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullableFloatFromSelector()
{
var source = new []
{
new { name = "Tim", num = (float?)5.5f },
new { name = "John", num = (float?)15.5f },
new { name = "Bob", num = default(float?) }
};
float? expected = 10.5f;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyIntSource()
{
int[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void EmptyIntSourceWithSelector()
{
int[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void NullIntSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Average());
}
[Fact]
public void NullIntSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Average(i => i));
}
[Fact]
public void NullIntFunc()
{
Func<int, int> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().Average(selector));
}
[Fact]
public void SingleElementIntSource()
{
int[] source = { 5 };
double expected = 5;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleIntValuesAllZero()
{
int[] source = { 0, 0, 0, 0, 0 };
double expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleIntSouce()
{
int[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleIntFromSelector()
{
var source = new []
{
new { name="Tim", num = 10 },
new { name="John", num = -10 },
new { name="Bob", num = 15 }
};
double expected = 5;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyNullableIntSource()
{
int?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void EmptyNullableIntSourceWithSelector()
{
int?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullNIntSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Average());
}
[Fact]
public void NullNIntSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int?>)null).Average(i => i));
}
[Fact]
public void NullNIntFunc()
{
Func<int?, int?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().Average(selector));
}
[Fact]
public void SingleNullableIntSource()
{
int?[] source = { -5 };
double? expected = -5;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntAllZeroSource()
{
int?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntSource()
{
int?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntSourceOnlyOneNotNull()
{
int?[] source = { null, null, null, null, 50 };
double? expected = 50;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntSourceAllNull()
{
int?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableIntSourceAllNullWithSelector()
{
int?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullableIntFromSelector()
{
var source = new []
{
new { name = "Tim", num = (int?)10 },
new { name = "John", num = default(int?) },
new { name = "Bob", num = (int?)10 }
};
double? expected = 10;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyLongSource()
{
long[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void EmptyLongSourceWithSelector()
{
long[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void NullLongSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Average());
}
[Fact]
public void NullLongSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long>)null).Average(i => i));
}
[Fact]
public void NullLongFunc()
{
Func<long, long> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().Average(selector));
}
[Fact]
public void SingleElementLongSource()
{
long[] source = { Int64.MaxValue };
double expected = Int64.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleLongValuesAllZero()
{
long[] source = { 0, 0, 0, 0, 0 };
double expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleLongValues()
{
long[] source = { 5, -10, 15, 40, 28 };
double expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleLongFromSelector()
{
var source = new []
{
new { name = "Tim", num = 40L },
new { name = "John", num = 50L },
new { name = "Bob", num = 60L }
};
double expected = 50;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void OverflowFromSummingLong()
{
long[] source = { Int64.MaxValue, Int64.MaxValue };
Assert.Throws<OverflowException>(() => source.Average());
}
[Fact]
public void EmptyNullableLongSource()
{
long?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void EmptyNullableLongSourceWithSelector()
{
long?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullNLongSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Average());
}
[Fact]
public void NullNLongSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<long?>)null).Average(i => i));
}
[Fact]
public void NullNLongFunc()
{
Func<long?, long?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().Average(selector));
}
[Fact]
public void SingleNullableLongSource()
{
long?[] source = { Int64.MinValue };
double? expected = Int64.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongAllZeroSource()
{
long?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongSource()
{
long?[] source = { 5, -10, null, null, null, 15, 40, 28, null, null };
double? expected = 15.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongSourceOnlyOneNotNull()
{
long?[] source = { null, null, null, null, 50 };
double? expected = 50;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongSourceAllNull()
{
long?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableLongSourceAllNullWithSelector()
{
long?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullableLongFromSelector()
{
var source = new []
{
new { name = "Tim", num = (long?)40L },
new { name = "John", num = default(long?) },
new { name = "Bob", num = (long?)30L }
};
double? expected = 35;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyDoubleSource()
{
double[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void EmptyDoubleSourceWithSelector()
{
double[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void NullDoubleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Average());
}
[Fact]
public void NullDoubleSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double>)null).Average(i => i));
}
[Fact]
public void NullDoubleFunc()
{
Func<double, double> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().Average(selector));
}
[Fact]
public void SingleElementDoubleSource()
{
double[] source = { Double.MaxValue };
double expected = Double.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleValuesAllZero()
{
double[] source = { 0.0, 0.0, 0.0, 0.0, 0.0 };
double expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleValues()
{
double[] source = { 5.5, -10, 15.5, 40.5, 28.5 };
double expected = 16;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleValuesIncludingNaN()
{
double[] source = { 5.58, Double.NaN, 30, 4.55, 19.38 };
double expected = Double.NaN;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDoubleFromSelector()
{
var source = new []
{
new { name = "Tim", num = 5.5},
new { name = "John", num = 15.5},
new { name = "Bob", num = 3.0}
};
double expected = 8.0;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyNullableDoubleSource()
{
double?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void EmptyNullableDoubleSourceWithSelector()
{
double?[] source = { };
double? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullNDoubleSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Average());
}
[Fact]
public void NullNDoubleSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<double?>)null).Average(i => i));
}
[Fact]
public void NullNDoubleFunc()
{
Func<double?, double?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().Average(selector));
}
[Fact]
public void SingleNullableDoubleSource()
{
double?[] source = { Double.MinValue };
double? expected = Double.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleAllZeroSource()
{
double?[] source = { 0, 0, 0, 0, 0 };
double? expected = 0;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSource()
{
double?[] source = { 5.5, 0, null, null, null, 15.5, 40.5, null, null, -23.5 };
double? expected = 7.6;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSourceOnlyOneNotNull()
{
double?[] source = { null, null, null, null, 45 };
double? expected = 45;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSourceAllNull()
{
double?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDoubleSourceAllNullWithSelector()
{
double?[] source = { null, null, null, null, null };
double? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void MultipleNullableDoubleSourceIncludingNaN()
{
double?[] source = { -23.5, 0, Double.NaN, 54.3, 0.56 };
double? expected = Double.NaN;
Assert.Equal(expected, source.Average());
}
[Fact]
public void NullableDoubleFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = (double?)5.5 },
new{ name = "John", num = (double?)15.5 },
new{ name = "Bob", num = default(double?) }
};
double? expected = 10.5;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyDecimalSource()
{
decimal[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void EmptyDecimalSourceWithSelector()
{
decimal[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void NullDecimalSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Average());
}
[Fact]
public void NullDecimalSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal>)null).Average(i => i));
}
[Fact]
public void NullDecimalFunc()
{
Func<decimal, decimal> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().Average(selector));
}
[Fact]
public void SingleElementDecimalSource()
{
decimal[] source = { Decimal.MaxValue };
decimal expected = Decimal.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDecimalValuesAllZero()
{
decimal[] source = { 0.0m, 0.0m, 0.0m, 0.0m, 0.0m };
decimal expected = 0m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDecimalValues()
{
decimal[] source = { 5.5m, -10m, 15.5m, 40.5m, 28.5m };
decimal expected = 16m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleDecimalFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = 5.5m},
new{ name = "John", num = 15.5m},
new{ name = "Bob", num = 3.0m}
};
decimal expected = 8.0m;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void EmptyNullableDecimalSource()
{
decimal?[] source = { };
decimal? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void EmptyNullableDecimalSourceWithSelector()
{
decimal?[] source = { };
decimal? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullNDecimalSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Average());
}
[Fact]
public void NullNDecimalSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<decimal?>)null).Average(i => i));
}
[Fact]
public void NullNDecimalFunc()
{
Func<decimal?, decimal?> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().Average(selector));
}
[Fact]
public void SingleNullableDecimalSource()
{
decimal?[] source = { Decimal.MinValue };
decimal? expected = Decimal.MinValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableeDecimalAllZeroSource()
{
decimal?[] source = { 0m, 0m, 0m, 0m, 0m };
decimal? expected = 0m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableeDecimalSource()
{
decimal?[] source = { 5.5m, 0, null, null, null, 15.5m, 40.5m, null, null, -23.5m };
decimal? expected = 7.6m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDecimalSourceOnlyOneNotNull()
{
decimal?[] source = { null, null, null, null, 45m };
decimal? expected = 45m;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDecimalSourceAllNull()
{
decimal?[] source = { null, null, null, null, null };
decimal? expected = null;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleNullableDecimalSourceAllNullWithSelector()
{
decimal?[] source = { null, null, null, null, null };
decimal? expected = null;
Assert.Equal(expected, source.Average(i => i));
}
[Fact]
public void NullableDecimalFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = (decimal?)5.5m},
new{ name = "John", num = (decimal?)15.5m},
new{ name = "Bob", num = (decimal?)null}
};
decimal? expected = 10.5m;
Assert.Equal(expected, source.Average(e => e.num));
}
[Fact]
public void OverflowFromSummingDecimal()
{
decimal?[] source = { decimal.MaxValue, decimal.MaxValue };
Assert.Throws<OverflowException>(() => source.Average());
}
[Fact]
public void EmptyFloatSource()
{
float[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average());
}
[Fact]
public void EmptyFloatSourceWithSelector()
{
float[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Average(i => i));
}
[Fact]
public void NullFloatSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Average());
}
[Fact]
public void NullFloatSourceWithFunc()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<float>)null).Average(i => i));
}
[Fact]
public void NullFloatFunc()
{
Func<float, float> selector = null;
Assert.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float>().Average(selector));
}
[Fact]
public void SingleElementFloatSource()
{
float[] source = { float.MaxValue };
float expected = float.MaxValue;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleFloatValuesAllZero()
{
float[] source = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float expected = 0f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleFloatValues()
{
float[] source = { 5.5f, -10f, 15.5f, 40.5f, 28.5f };
float expected = 16f;
Assert.Equal(expected, source.Average());
}
[Fact]
public void MultipleFloatFromSelector()
{
var source = new[]
{
new{ name = "Tim", num = 5.5f},
new{ name = "John", num = 15.5f},
new{ name = "Bob", num = 3.0f}
};
float expected = 8.0f;
Assert.Equal(expected, source.Average(e => e.num));
}
}
}
| |
using System;
using System.IdentityModel.Tokens.Jwt;
using AspNet.Security.OAuth.Validation;
using AspNet.Security.OpenIdConnect.Primitives;
using AspNet.Security.OpenIdConnect.Server;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenIddict;
using OrchardCore.Environment.Shell;
using OrchardCore.OpenId.Models;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.Settings;
namespace OrchardCore.OpenId
{
public class OpenIdConfiguration : IConfigureOptions<AuthenticationOptions>,
IConfigureNamedOptions<OpenIddictOptions>,
IConfigureNamedOptions<JwtBearerOptions>,
IConfigureNamedOptions<OAuthValidationOptions>
{
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly ILogger<OpenIdConfiguration> _logger;
private readonly IOpenIdService _openIdService;
public OpenIdConfiguration(
IDataProtectionProvider dataProtectionProvider,
ILogger<OpenIdConfiguration> logger,
IOpenIdService openIdService,
ShellSettings shellSettings)
{
_dataProtectionProvider = dataProtectionProvider.CreateProtector(shellSettings.Name);
_logger = logger;
_openIdService = openIdService;
}
public void Configure(AuthenticationOptions options)
{
var settings = _openIdService.GetOpenIdSettingsAsync().GetAwaiter().GetResult();
if (!_openIdService.IsValidOpenIdSettings(settings))
{
_logger.LogWarning("The OpenID Connect module is not correctly configured.");
return;
}
// Register the OpenIddict handler in the authentication handlers collection.
options.AddScheme(OpenIdConnectServerDefaults.AuthenticationScheme, builder =>
{
builder.HandlerType = typeof(OpenIddictHandler);
});
// Register the JWT or validation handler in the authentication handlers collection.
if (settings.AccessTokenFormat == OpenIdSettings.TokenFormat.Encrypted)
{
options.AddScheme(OAuthValidationDefaults.AuthenticationScheme, builder =>
{
builder.HandlerType = typeof(OAuthValidationHandler);
});
}
else if (settings.AccessTokenFormat == OpenIdSettings.TokenFormat.JWT)
{
// Note: unlike most authentication handlers in ASP.NET Core 2.0,
// the JWT bearer handler is not public (which is likely an oversight).
// To work around this issue, the handler type is resolved using reflection.
options.AddScheme(JwtBearerDefaults.AuthenticationScheme, builder =>
{
builder.HandlerType = typeof(JwtBearerOptions).Assembly
.GetType("Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler");
});
}
else
{
throw new InvalidOperationException("The specified access token format is not valid.");
}
}
public void Configure(string name, OpenIddictOptions options)
{
// Ignore OpenIddict handler instances that don't correspond to the instance managed by the OpenID module.
if (!string.Equals(name, OpenIdConnectServerDefaults.AuthenticationScheme, StringComparison.Ordinal))
{
return;
}
var settings = _openIdService.GetOpenIdSettingsAsync().GetAwaiter().GetResult();
if (!_openIdService.IsValidOpenIdSettings(settings))
{
return;
}
options.ProviderType = typeof(OpenIddictProvider<OpenIdApplication, OpenIdAuthorization, OpenIdScope, OpenIdToken>);
options.DataProtectionProvider = _dataProtectionProvider;
options.RequireClientIdentification = true;
options.EnableRequestCaching = true;
if (settings.AccessTokenFormat == OpenIdSettings.TokenFormat.JWT)
{
options.AccessTokenHandler = new JwtSecurityTokenHandler();
}
if (settings.TestingModeEnabled)
{
options.SigningCredentials.AddEphemeralKey();
options.AllowInsecureHttp = true;
}
else if (settings.CertificateStoreLocation.HasValue && settings.CertificateStoreName.HasValue && !string.IsNullOrEmpty(settings.CertificateThumbPrint))
{
try
{
options.AllowInsecureHttp = false;
options.SigningCredentials.Clear();
options.SigningCredentials.AddCertificate(settings.CertificateThumbPrint, settings.CertificateStoreName.Value, settings.CertificateStoreLocation.Value);
}
catch (Exception exception)
{
_logger.LogError("An error occurred while trying to register a X.509 certificate.", exception);
throw;
}
}
if (settings.EnableAuthorizationEndpoint)
{
options.AuthorizationEndpointPath = "/OrchardCore.OpenId/Access/Authorize";
}
if (settings.EnableTokenEndpoint)
{
options.TokenEndpointPath = "/OrchardCore.OpenId/Access/Token";
}
if (settings.EnableLogoutEndpoint)
{
options.LogoutEndpointPath = "/OrchardCore.OpenId/Access/Logout";
}
if (settings.EnableUserInfoEndpoint)
{
options.UserinfoEndpointPath = "/OrchardCore.OpenId/UserInfo/Me";
}
if (settings.AllowPasswordFlow)
{
options.GrantTypes.Add(OpenIdConnectConstants.GrantTypes.Password);
}
if (settings.AllowClientCredentialsFlow)
{
options.GrantTypes.Add(OpenIdConnectConstants.GrantTypes.ClientCredentials);
}
if (settings.AllowAuthorizationCodeFlow || settings.AllowHybridFlow)
{
options.GrantTypes.Add(OpenIdConnectConstants.GrantTypes.AuthorizationCode);
}
if (settings.AllowRefreshTokenFlow)
{
options.GrantTypes.Add(OpenIdConnectConstants.GrantTypes.RefreshToken);
}
if (settings.AllowImplicitFlow || settings.AllowHybridFlow)
{
options.GrantTypes.Add(OpenIdConnectConstants.GrantTypes.Implicit);
}
}
public void Configure(OpenIddictOptions options) { }
public void Configure(string name, JwtBearerOptions options)
{
// Ignore JWT handler instances that don't correspond to the instance managed by the OpenID module.
if (!string.Equals(name, JwtBearerDefaults.AuthenticationScheme, StringComparison.Ordinal))
{
return;
}
var settings = _openIdService.GetOpenIdSettingsAsync().GetAwaiter().GetResult();
if (!_openIdService.IsValidOpenIdSettings(settings))
{
return;
}
options.RequireHttpsMetadata = !settings.TestingModeEnabled;
options.Authority = settings.Authority;
options.TokenValidationParameters.ValidAudiences = settings.Audiences;
}
public void Configure(JwtBearerOptions options) { }
public void Configure(string name, OAuthValidationOptions options)
{
// Ignore validation handler instances that don't correspond to the instance managed by the OpenID module.
if (!string.Equals(name, OAuthValidationDefaults.AuthenticationScheme, StringComparison.Ordinal))
{
return;
}
var settings = _openIdService.GetOpenIdSettingsAsync().GetAwaiter().GetResult();
if (!_openIdService.IsValidOpenIdSettings(settings))
{
return;
}
options.Audiences.UnionWith(settings.Audiences);
options.DataProtectionProvider = _dataProtectionProvider;
}
public void Configure(OAuthValidationOptions options) { }
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Text;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Filters specification: used for DataRegions (List, Chart, Table, Matrix), DataSets, group instances
/// </summary>
internal class FiltersCtl : System.Windows.Forms.UserControl, IProperty
{
private DesignXmlDraw _Draw;
private XmlNode _FilterParent;
private DataGridViewTextBoxColumn dgtbFE;
private DataGridViewComboBoxColumn dgtbOP;
private DataGridViewTextBoxColumn dgtbFV;
private System.Windows.Forms.Button bDelete;
private System.Windows.Forms.DataGridView dgFilters;
private System.Windows.Forms.Button bUp;
private System.Windows.Forms.Button bDown;
private System.Windows.Forms.Button bValueExpr;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal FiltersCtl(DesignXmlDraw dxDraw, XmlNode filterParent)
{
_Draw = dxDraw;
_FilterParent = filterParent;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
// Initialize the DataGrid columns
dgtbFE = new DataGridViewTextBoxColumn();
dgtbOP = new DataGridViewComboBoxColumn();
dgtbOP.Items.AddRange(new string[]
{ "Equal", "Like", "NotEqual", "GreaterThan", "GreaterThanOrEqual", "LessThan",
"LessThanOrEqual", "TopN", "BottomN", "TopPercent", "BottomPercent", "In", "Between" });
dgtbFV = new DataGridViewTextBoxColumn();
dgFilters.Columns.Add(dgtbFE);
dgFilters.Columns.Add(dgtbOP);
dgFilters.Columns.Add(dgtbFV);
//
// dgtbFE
//
dgtbFE.HeaderText = "Filter Expression";
dgtbFE.Width = 130;
// Get the parent's dataset name
//string dataSetName = _Draw.GetDataSetNameValue(_FilterParent);
// unfortunately no way to make combo box editable
//string[] fields = _Draw.GetFields(dataSetName, true);
//if (fields != null)
// dgtbFE.Items.AddRange(fields);
dgtbOP.HeaderText = "Operator";
dgtbOP.Width = 100;
dgtbOP.DropDownWidth = 140;
//
// dgtbFV
//
this.dgtbFV.HeaderText = "Value(s)";
this.dgtbFV.Width = 130;
//string[] parms = _Draw.GetReportParameters(true);
//if (parms != null)
// dgtbFV.Items.AddRange(parms);
XmlNode filters = _Draw.GetNamedChildNode(_FilterParent, "Filters");
if (filters != null)
foreach (XmlNode fNode in filters.ChildNodes)
{
if (fNode.NodeType != XmlNodeType.Element ||
fNode.Name != "Filter")
continue;
// Get the values
XmlNode vNodes = _Draw.GetNamedChildNode(fNode, "FilterValues");
StringBuilder sb = new StringBuilder();
if (vNodes != null)
{
foreach (XmlNode v in vNodes.ChildNodes)
{
if (v.InnerText.Length <= 0)
continue;
if (sb.Length != 0)
sb.Append(", ");
sb.Append(v.InnerText);
}
}
// Add the row
dgFilters.Rows.Add(_Draw.GetElementValue(fNode, "FilterExpression", ""),
_Draw.GetElementValue(fNode, "Operator", "Equal"),
sb.ToString());
}
if (dgFilters.Rows.Count == 0)
dgFilters.Rows.Add("","Equal","");
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FiltersCtl));
this.dgFilters = new System.Windows.Forms.DataGridView();
this.bDelete = new System.Windows.Forms.Button();
this.bUp = new System.Windows.Forms.Button();
this.bDown = new System.Windows.Forms.Button();
this.bValueExpr = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dgFilters)).BeginInit();
this.SuspendLayout();
//
// dgFilters
//
resources.ApplyResources(this.dgFilters, "dgFilters");
this.dgFilters.Name = "dgFilters";
//
// bDelete
//
resources.ApplyResources(this.bDelete, "bDelete");
this.bDelete.Name = "bDelete";
this.bDelete.Click += new System.EventHandler(this.bDelete_Click);
//
// bUp
//
resources.ApplyResources(this.bUp, "bUp");
this.bUp.Name = "bUp";
this.bUp.Click += new System.EventHandler(this.bUp_Click);
//
// bDown
//
resources.ApplyResources(this.bDown, "bDown");
this.bDown.Name = "bDown";
this.bDown.Click += new System.EventHandler(this.bDown_Click);
//
// bValueExpr
//
resources.ApplyResources(this.bValueExpr, "bValueExpr");
this.bValueExpr.Name = "bValueExpr";
this.bValueExpr.Tag = "value";
this.bValueExpr.Click += new System.EventHandler(this.bValueExpr_Click);
//
// FiltersCtl
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.bValueExpr);
this.Controls.Add(this.bDown);
this.Controls.Add(this.bUp);
this.Controls.Add(this.bDelete);
this.Controls.Add(this.dgFilters);
this.Name = "FiltersCtl";
((System.ComponentModel.ISupportInitialize)(this.dgFilters)).EndInit();
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// Remove the old filters
XmlNode filters = null;
_Draw.RemoveElement(_FilterParent, "Filters");
// Loop thru and add all the filters
foreach (DataGridViewRow dr in this.dgFilters.Rows)
{
string fe = dr.Cells[0].Value as string;
string op = dr.Cells[1].Value as string;
string fv = dr.Cells[2].Value as string;
if (fe == null || fe.Length <= 0 ||
op == null || op.Length <= 0 ||
fv == null || fv.Length <= 0)
continue;
if (filters == null)
filters = _Draw.CreateElement(_FilterParent, "Filters", null);
XmlNode fNode = _Draw.CreateElement(filters, "Filter", null);
_Draw.CreateElement(fNode, "FilterExpression", fe);
_Draw.CreateElement(fNode, "Operator", op);
XmlNode fvNode = _Draw.CreateElement(fNode, "FilterValues", null);
if (op == "In")
{
string[] vs = fv.Split(',');
foreach (string v in vs)
_Draw.CreateElement(fvNode, "FilterValue", v.Trim());
}
else if (op == "Between")
{
string[] vs = fv.Split(new char[] {','}, 2);
foreach (string v in vs)
_Draw.CreateElement(fvNode, "FilterValue", v.Trim());
}
else
{
_Draw.CreateElement(fvNode, "FilterValue", fv);
}
}
}
private void bDelete_Click(object sender, System.EventArgs e)
{
if (dgFilters.CurrentRow == null)
return;
if (!dgFilters.Rows[dgFilters.CurrentRow.Index].IsNewRow) // can't delete the new row
dgFilters.Rows.RemoveAt(this.dgFilters.CurrentRow.Index);
else
{ // just empty out the values
DataGridViewRow dgrv = dgFilters.Rows[this.dgFilters.CurrentRow.Index];
dgrv.Cells[0].Value = null;
dgrv.Cells[1].Value = "Equal";
dgrv.Cells[2].Value = null;
}
}
private void bUp_Click(object sender, System.EventArgs e)
{
int cr = dgFilters.CurrentRow == null ? 0 : dgFilters.CurrentRow.Index;
if (cr <= 0) // already at the top
return;
SwapRow(dgFilters.Rows[cr - 1], dgFilters.Rows[cr]);
dgFilters.CurrentCell =
dgFilters.Rows[cr-1].Cells[dgFilters.CurrentCell.ColumnIndex];
}
private void bDown_Click(object sender, System.EventArgs e)
{
int cr = dgFilters.CurrentRow == null ? 0 : dgFilters.CurrentRow.Index;
if (cr < 0) // invalid index
return;
if (cr + 1 >= dgFilters.Rows.Count)
return; // already at end
SwapRow(dgFilters.Rows[cr+1], dgFilters.Rows[cr]);
dgFilters.CurrentCell =
dgFilters.Rows[cr + 1].Cells[dgFilters.CurrentCell.ColumnIndex];
}
private void SwapRow(DataGridViewRow tdr, DataGridViewRow fdr)
{
// column 1
object save = tdr.Cells[0].Value;
tdr.Cells[0].Value = fdr.Cells[0].Value;
fdr.Cells[0].Value = save;
// column 2
save = tdr.Cells[1].Value;
tdr.Cells[1].Value = fdr.Cells[1].Value;
fdr.Cells[1].Value = save;
// column 3
save = tdr.Cells[2].Value;
tdr.Cells[2].Value = fdr.Cells[2].Value;
fdr.Cells[2].Value = save;
return;
}
private void bValueExpr_Click(object sender, System.EventArgs e)
{
if (dgFilters.CurrentCell == null)
dgFilters.Rows.Add("", "Equal", "");
DataGridViewCell dgc = dgFilters.CurrentCell;
int cc = dgc.ColumnIndex;
string cv = dgc.Value as string;
if (cc == 1)
{ // This is the FilterOperator
DialogFilterOperator fo = new DialogFilterOperator(cv);
try
{
DialogResult dlgr = fo.ShowDialog();
if (dlgr == DialogResult.OK)
dgc.Value = fo.Operator;
}
finally
{
fo.Dispose();
}
}
else
{
DialogExprEditor ee = new DialogExprEditor(_Draw, cv, _FilterParent, false);
try
{
DialogResult dlgr = ee.ShowDialog();
if (dlgr == DialogResult.OK)
dgc.Value = ee.Expression;
}
finally
{
ee.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using AllReady.Areas.Admin.ViewModels.Validators;
using AllReady.Areas.Admin.ViewModels.Validators.Task;
using AllReady.Controllers;
using AllReady.DataAccess;
using AllReady.Hangfire;
using AllReady.Models;
using AllReady.Providers;
using AllReady.Providers.ExternalUserInformationProviders;
using AllReady.Providers.ExternalUserInformationProviders.Providers;
using AllReady.Security;
using AllReady.Services;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Features.Variance;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using AllReady.Security.Middleware;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Hangfire;
using Hangfire.SqlServer;
using AllReady.ModelBinding;
using AllReady.Services.Mapping;
using AllReady.Services.Mapping.GeoCoding;
using AllReady.Services.Mapping.Routing;
using Microsoft.AspNetCore.Localization;
using AllReady.Services.Twitter;
using CsvHelper;
using AllReady.Services.Sms;
namespace AllReady
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("version.json")
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
//builder.AddApplicationInsightsSettings(developerMode: true);
builder.AddApplicationInsightsSettings(developerMode: false);
}
else if (env.IsStaging() || env.IsProduction())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: false);
}
Configuration = builder.Build();
Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//Add CORS support.
// Must be first to avoid OPTIONS issues when calling from Angular/Browser
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin();
corsBuilder.AllowCredentials();
services.AddCors(options =>
{
options.AddPolicy("allReady", corsBuilder.Build());
});
// Add Application Insights data collection services to the services container.
services.AddApplicationInsightsTelemetry(Configuration);
// Add Entity Framework services to the services container.
services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.Configure<AzureStorageSettings>(Configuration.GetSection("Data:Storage"));
services.Configure<DatabaseSettings>(Configuration.GetSection("Data:DefaultConnection"));
services.Configure<EmailSettings>(Configuration.GetSection("Email"));
services.Configure<SampleDataSettings>(Configuration.GetSection("SampleData"));
services.Configure<GeneralSettings>(Configuration.GetSection("General"));
services.Configure<GetASmokeAlarmApiSettings>(Configuration.GetSection("GetASmokeAlarmApiSettings"));
services.Configure<TwitterAuthenticationSettings>(Configuration.GetSection("Authentication:Twitter"));
services.Configure<TwilioSettings>(Configuration.GetSection("Authentication:Twilio"));
services.Configure<MappingSettings>(Configuration.GetSection("Mapping"));
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 10;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireDigit = true;
options.Password.RequireUppercase = false;
options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied");
})
.AddEntityFrameworkStores<AllReadyContext>()
.AddDefaultTokenProviders();
// Add Authorization rules for the app
services.AddAuthorization(options =>
{
options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin"));
options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin"));
});
services.AddLocalization();
//Currently AllReady only supports en-US culture. This forces datetime and number formats to the en-US culture regardless of local culture
var usCulture = new CultureInfo("en-US");
var supportedCultures = new[] { usCulture };
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture(usCulture, usCulture);
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
// Add MVC services to the services container.
// config add to get passed Angular failing on Options request when logging in.
services.AddMvc(config =>
{
config.ModelBinderProviders.Insert(0, new AdjustToTimezoneModelBinderProvider());
})
.AddJsonOptions(options =>
options.SerializerSettings.ContractResolver = new DefaultContractResolver());
//Hangfire
services.AddHangfire(configuration => configuration.UseSqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"]));
// configure IoC support
var container = CreateIoCContainer(services);
return container.Resolve<IServiceProvider>();
}
private IContainer CreateIoCContainer(IServiceCollection services)
{
// todo: move these to a proper autofac module
// Register application services.
services.AddSingleton(x => Configuration);
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<IDetermineIfATaskIsEditable, DetermineIfATaskIsEditable>();
services.AddTransient<IValidateEventEditViewModels, EventEditViewModelValidator>();
services.AddTransient<ITaskEditViewModelValidator, TaskEditViewModelValidator>();
services.AddTransient<IItineraryEditModelValidator, ItineraryEditModelValidator>();
services.AddTransient<IOrganizationEditModelValidator, OrganizationEditModelValidator>();
services.AddTransient<IRedirectAccountControllerRequests, RedirectAccountControllerRequests>();
services.AddSingleton<IImageService, ImageService>();
services.AddSingleton<ICsvFactory, CsvFactory>();
services.AddTransient<SampleDataGenerator>();
services.AddSingleton<IHttpClient, StaticHttpClient>();
services.AddSingleton<ITwitterService, TwitterService>();
if (Configuration["Mapping:EnableGoogleGeocodingService"] == "true")
{
services.AddSingleton<IGeocodeService,GoogleGeocodeService>();
}
else
{
services.AddSingleton<IGeocodeService, FakeGeocodeService>();
}
if (Configuration["Data:Storage:EnableAzureQueueService"] == "true")
{
// This setting is false by default. To enable queue processing you will
// need to override the setting in your user secrets or env vars.
services.AddTransient<IQueueStorageService, QueueStorageService>();
}
else
{
// this writer service will just write to the default logger
services.AddTransient<IQueueStorageService, FakeQueueWriterService>();
}
if (Configuration["Authentication:Twilio:EnableTwilio"] == "true")
{
services.AddSingleton<IPhoneNumberLookupService, TwilioPhoneNumberLookupService>();
services.AddSingleton<ITwilioWrapper, TwilioWrapper>();
}
else
{
services.AddSingleton<IPhoneNumberLookupService, FakePhoneNumberLookupService>();
}
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterSource(new ContravariantRegistrationSource());
containerBuilder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();
containerBuilder.RegisterAssemblyTypes(typeof(Startup).GetTypeInfo().Assembly).AsImplementedInterfaces();
containerBuilder.Register<SingleInstanceFactory>(ctx =>
{
var c = ctx.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
containerBuilder.Register<MultiInstanceFactory>(ctx =>
{
var c = ctx.Resolve<IComponentContext>();
return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
});
//ExternalUserInformationProviderFactory registration
containerBuilder.RegisterType<TwitterExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Twitter");
containerBuilder.RegisterType<GoogleExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Google");
containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Microsoft");
containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Facebook");
containerBuilder.RegisterType<ExternalUserInformationProviderFactory>().As<IExternalUserInformationProviderFactory>();
//Hangfire
containerBuilder.Register(icomponentcontext => new BackgroundJobClient(new SqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"])))
.As<IBackgroundJobClient>();
//auto-register Hangfire jobs by convention
//http://docs.autofac.org/en/latest/register/scanning.html
var assembly = typeof(Startup).GetTypeInfo().Assembly;
containerBuilder
.RegisterAssemblyTypes(assembly)
.Where(t => t.Namespace == "AllReady.Hangfire.Jobs" && t.GetTypeInfo().IsInterface)
.AsImplementedInterfaces();
containerBuilder.RegisterType<GoogleOptimizeRouteService>().As<IOptimizeRouteService>().SingleInstance();
//Populate the container with services that were previously registered
containerBuilder.Populate(services);
var container = containerBuilder.Build();
return container;
}
// Configure is called after ConfigureServices is called.
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, IConfiguration configuration)
{
// Put first to avoid issues with OPTIONS when calling from Angular/Browser.
app.UseCors("allReady");
// todo: in RC update we can read from a logging.json config file
loggerFactory.AddConsole((category, level) =>
{
if (category.StartsWith("Microsoft."))
{
return level >= LogLevel.Information;
}
return true;
});
if (env.IsDevelopment())
{
// this will go to the VS output window
loggerFactory.AddDebug((category, level) =>
{
if (category.StartsWith("Microsoft."))
{
return level >= LogLevel.Information;
}
return true;
});
}
// Add Application Insights to the request pipeline to track HTTP request telemetry data.
app.UseApplicationInsightsRequestTelemetry();
// Add the following to the request pipeline only in development environment.
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else if (env.IsStaging())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
// Add Error handling middleware which catches all application specific errors and
// sends the request to the following path or controller action.
app.UseExceptionHandler("/Home/Error");
}
// Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
app.UseApplicationInsightsExceptionTelemetry();
// Add static files to the request pipeline.
app.UseStaticFiles();
app.UseRequestLocalization();
// Add cookie-based authentication to the request pipeline.
app.UseIdentity();
// Add token-based protection to the request inject pipeline
app.UseTokenProtection(new TokenProtectedResourceOptions
{
Path = "/api/request",
PolicyName = "api-request-injest"
});
// Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
// For more information see http://go.microsoft.com/fwlink/?LinkID=532715
if (Configuration["Authentication:Facebook:AppId"] != null)
{
var options = new FacebookOptions
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"],
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name"
};
options.Scope.Add("email");
app.UseFacebookAuthentication(options);
}
if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
{
var options = new MicrosoftAccountOptions
{
ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"],
ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
};
app.UseMicrosoftAccountAuthentication(options);
}
//http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap
if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
{
var options = new TwitterOptions
{
ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"],
ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"]
};
app.UseTwitterAuthentication(options);
}
if (Configuration["Authentication:Google:ClientId"] != null)
{
var options = new GoogleOptions
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"]
};
app.UseGoogleAuthentication(options);
}
//call Migrate here to force the creation of the AllReady database so Hangfire can create its schema under it
if (!env.IsProduction())
{
context.Database.Migrate();
}
//Hangfire
app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangireDashboardAuthorizationFilter() } });
app.UseHangfireServer();
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}");
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});
// Add sample data and test admin accounts if specified in Config.Json.
// for production applications, this should either be set to false or deleted.
if (Configuration["SampleData:InsertSampleData"] == "true")
{
sampleData.InsertTestData();
}
if (Configuration["SampleData:InsertTestUsers"] == "true")
{
await sampleData.CreateAdminUser();
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using OpenSource.UPnP;
namespace UPnPRelay
{
/// <summary>
/// Summary description for DeviceSelector.
/// </summary>
public class DeviceSelector : System.Windows.Forms.Form
{
private UPnPDevice selectedDevice = null;
public UPnPDevice SelectedDevice {get {return selectedDevice;}}
private UPnPSmartControlPoint scp;
protected TreeNode UPnpRoot = new TreeNode("UPnP Devices",0,0);
private System.Windows.Forms.TreeView DeviceTree;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.Label label1;
private System.ComponentModel.IContainer components;
public delegate void UpdateTreeDelegate(TreeNode node);
public DeviceSelector()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
DeviceTree.Nodes.Add(UPnpRoot);
scp = new UPnPSmartControlPoint(new UPnPSmartControlPoint.DeviceHandler(AddSink));
scp.OnRemovedDevice += new UPnPSmartControlPoint.DeviceHandler(RemoveSink);
}
private void AddSink(UPnPSmartControlPoint sender, UPnPDevice d)
{
HandleCreate(d,d.BaseURL);
}
private void RemoveSink(UPnPSmartControlPoint sender, UPnPDevice device)
{
ArrayList TempList = new ArrayList();
TreeNode tn;
IEnumerator en = UPnpRoot.Nodes.GetEnumerator();
while (en.MoveNext())
{
tn = (TreeNode)en.Current;
if (((UPnPDevice)tn.Tag).UniqueDeviceName == device.UniqueDeviceName)
{
TempList.Add(tn);
}
}
for (int x=0;x<TempList.Count;++x)
{
UPnpRoot.Nodes.Remove((TreeNode)TempList[x]);
}
}
protected void HandleCreate(UPnPDevice device, Uri URL)
{
TreeNode parent = new TreeNode(device.FriendlyName,1,1);
parent.Tag = device;
Object[] args = new Object[1];
args[0] = parent;
if (this.IsHandleCreated == true)
{
this.Invoke(new UpdateTreeDelegate(HandleTreeUpdate),args);
}
else
{
HandleTreeUpdate(parent);
}
}
protected void HandleTreeUpdate(TreeNode node)
{
// Insert this node into the tree
if(UPnpRoot.Nodes.Count==0)
{
UPnpRoot.Nodes.Add(node);
}
else
{
for (int i=0;i<UPnpRoot.Nodes.Count;++i)
{
if (UPnpRoot.Nodes[i].Text.CompareTo(node.Text)>0)
{
UPnpRoot.Nodes.Insert(i,node);
break;
}
if (i == UPnpRoot.Nodes.Count-1)
{
UPnpRoot.Nodes.Add(node);
break;
}
}
}
UPnpRoot.Expand();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DeviceSelector));
this.DeviceTree = new System.Windows.Forms.TreeView();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.cancelButton = new System.Windows.Forms.Button();
this.okButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// DeviceTree
//
this.DeviceTree.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.DeviceTree.ImageList = this.imageList;
this.DeviceTree.Location = new System.Drawing.Point(8, 40);
this.DeviceTree.Name = "DeviceTree";
this.DeviceTree.Size = new System.Drawing.Size(312, 216);
this.DeviceTree.TabIndex = 0;
this.DeviceTree.DoubleClick += new System.EventHandler(this.OnDoubleClick);
this.DeviceTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.DeviceTree_AfterSelect);
//
// imageList
//
this.imageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth16Bit;
this.imageList.ImageSize = new System.Drawing.Size(16, 16);
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Transparent;
//
// cancelButton
//
this.cancelButton.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(152, 264);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(80, 24);
this.cancelButton.TabIndex = 3;
this.cancelButton.Text = "Cancel";
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// okButton
//
this.okButton.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.okButton.Location = new System.Drawing.Point(240, 264);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(80, 24);
this.okButton.TabIndex = 2;
this.okButton.Text = "OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(312, 32);
this.label1.TabIndex = 4;
this.label1.Text = "Select a UPnP network device that will be accessible from outside the network.";
//
// DeviceSelector
//
this.AcceptButton = this.okButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(326, 292);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label1,
this.cancelButton,
this.okButton,
this.DeviceTree});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DeviceSelector";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "UPnP Device Selection";
this.ResumeLayout(false);
}
#endregion
private void OnDoubleClick(object sender, System.EventArgs e)
{
object Selected = DeviceTree.SelectedNode;
if (((TreeNode)Selected).Tag.GetType() == typeof(UPnPDevice))
{
selectedDevice = (UPnPDevice)((TreeNode)Selected).Tag;
this.DialogResult = DialogResult.OK;
}
}
private void okButton_Click(object sender, System.EventArgs e)
{
if (selectedDevice != null) this.DialogResult = DialogResult.OK;
}
private void cancelButton_Click(object sender, System.EventArgs e)
{
selectedDevice = null;
this.DialogResult = DialogResult.Cancel;
}
private void DeviceTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TreeNode node = (TreeNode)DeviceTree.SelectedNode;
if (node != null && node.Tag != null && node.Tag.GetType() == typeof(UPnPDevice))
{
selectedDevice = (UPnPDevice)node.Tag;
okButton.Enabled = true;
}
else
{
selectedDevice = null;
okButton.Enabled = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class OperatorOverloadsHaveNamedAlternatesTests : DiagnosticAnalyzerTestBase
{
#region Boilerplate
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new OperatorOverloadsHaveNamedAlternatesAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new OperatorOverloadsHaveNamedAlternatesAnalyzer();
}
private static DiagnosticResult GetCA2225CSharpDefaultResultAt(int line, int column, string alternateName, string operatorName)
{
// Provide a method named '{0}' as a friendly alternate for operator {1}.
string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageDefault, alternateName, operatorName);
return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCA2225CSharpPropertyResultAt(int line, int column, string alternateName, string operatorName)
{
// Provide a property named '{0}' as a friendly alternate for operator {1}.
string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageProperty, alternateName, operatorName);
return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCA2225CSharpMultipleResultAt(int line, int column, string alternateName1, string alternateName2, string operatorName)
{
// Provide a method named '{0}' or '{1}' as an alternate for operator {2}
string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageMultiple, alternateName1, alternateName2, operatorName);
return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCA2225CSharpVisibilityResultAt(int line, int column, string alternateName, string operatorName)
{
// Mark {0} as public because it is a friendly alternate for operator {1}.
string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageVisibility, alternateName, operatorName);
return GetCSharpResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCA2225BasicDefaultResultAt(int line, int column, string alternateName, string operatorName)
{
// Provide a method named '{0}' as a friendly alternate for operator {1}.
string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageDefault, alternateName, operatorName);
return GetBasicResultAt(line, column, OperatorOverloadsHaveNamedAlternatesAnalyzer.RuleId, message);
}
#endregion
#region C# tests
[Fact]
public void HasAlternateMethod_CSharp()
{
VerifyCSharp(@"
class C
{
public static C operator +(C left, C right) { return new C(); }
public static C Add(C left, C right) { return new C(); }
}
");
}
[Fact]
public void HasMultipleAlternatePrimary_CSharp()
{
VerifyCSharp(@"
class C
{
public static C operator %(C left, C right) { return new C(); }
public static C Mod(C left, C right) { return new C(); }
}
");
}
[Fact]
public void HasMultipleAlternateSecondary_CSharp()
{
VerifyCSharp(@"
class C
{
public static C operator %(C left, C right) { return new C(); }
public static C Remainder(C left, C right) { return new C(); }
}
");
}
[Fact]
public void HasAppropriateConversionAlternate_CSharp()
{
VerifyCSharp(@"
class C
{
public static implicit operator int(C item) { return 0; }
public int ToInt32() { return 0; }
}
");
}
[Fact]
public void MissingAlternateMethod_CSharp()
{
VerifyCSharp(@"
class C
{
public static C operator +(C left, C right) { return new C(); }
}
",
GetCA2225CSharpDefaultResultAt(4, 30, "Add", "op_Addition"));
}
[Fact]
public void MissingAlternateProperty_CSharp()
{
VerifyCSharp(@"
class C
{
public static bool operator true(C item) { return true; }
public static bool operator false(C item) { return false; }
}
",
GetCA2225CSharpPropertyResultAt(4, 33, "IsTrue", "op_True"));
}
[Fact]
public void MissingMultipleAlternates_CSharp()
{
VerifyCSharp(@"
class C
{
public static C operator %(C left, C right) { return new C(); }
}
",
GetCA2225CSharpMultipleResultAt(4, 30, "Mod", "Remainder", "op_Modulus"));
}
[Fact]
public void ImproperAlternateMethodVisibility_CSharp()
{
VerifyCSharp(@"
class C
{
public static C operator +(C left, C right) { return new C(); }
protected static C Add(C left, C right) { return new C(); }
}
",
GetCA2225CSharpVisibilityResultAt(5, 24, "Add", "op_Addition"));
}
[Fact]
public void ImproperAlternatePropertyVisibility_CSharp()
{
VerifyCSharp(@"
class C
{
public static bool operator true(C item) { return true; }
public static bool operator false(C item) { return false; }
private bool IsTrue => true;
}
",
GetCA2225CSharpVisibilityResultAt(6, 18, "IsTrue", "op_True"));
}
[Fact]
public void StructHasAlternateMethod_CSharp()
{
VerifyCSharp(@"
struct C
{
public static C operator +(C left, C right) { return new C(); }
public static C Add(C left, C right) { return new C(); }
}
");
}
#endregion
//
// Since the analyzer is symbol-based, only a few VB tests are added as a sanity check
//
#region VB tests
[Fact]
public void HasAlternateMethod_VisualBasic()
{
VerifyBasic(@"
Class C
Public Shared Operator +(left As C, right As C) As C
Return New C()
End Operator
Public Shared Function Add(left As C, right As C) As C
Return New C()
End Function
End Class
");
}
[Fact]
public void MissingAlternateMethod_VisualBasic()
{
VerifyBasic(@"
Class C
Public Shared Operator +(left As C, right As C) As C
Return New C()
End Operator
End Class
",
GetCA2225BasicDefaultResultAt(3, 28, "Add", "op_Addition"));
}
[Fact]
public void StructHasAlternateMethod_VisualBasic()
{
VerifyBasic(@"
Structure C
Public Shared Operator +(left As C, right As C) As C
Return New C()
End Operator
Public Shared Function Add(left As C, right As C) As C
Return New C()
End Function
End Structure
");
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Cryptography {
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Globalization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public class PasswordDeriveBytes : DeriveBytes {
private int _extraCount;
private int _prefix;
private int _iterations;
private byte[] _baseValue;
private byte[] _extra;
private byte[] _salt;
private string _hashName;
private byte[] _password;
private HashAlgorithm _hash;
private CspParameters _cspParams;
[System.Security.SecurityCritical] // auto-generated
private SafeProvHandle _safeProvHandle = null;
private SafeProvHandle ProvHandle {
[System.Security.SecurityCritical] // auto-generated
get {
if (_safeProvHandle == null) {
lock (this) {
if (_safeProvHandle == null) {
SafeProvHandle safeProvHandle = Utils.AcquireProvHandle(_cspParams);
System.Threading.Thread.MemoryBarrier();
_safeProvHandle = safeProvHandle;
}
}
}
return _safeProvHandle;
}
}
//
// public constructors
//
public PasswordDeriveBytes (String strPassword, byte[] rgbSalt) : this (strPassword, rgbSalt, new CspParameters()) {}
public PasswordDeriveBytes (byte[] password, byte[] salt) : this (password, salt, new CspParameters()) {}
public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, string strHashName, int iterations) :
this (strPassword, rgbSalt, strHashName, iterations, new CspParameters()) {}
public PasswordDeriveBytes (byte[] password, byte[] salt, string hashName, int iterations) :
this (password, salt, hashName, iterations, new CspParameters()) {}
public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, CspParameters cspParams) :
this (strPassword, rgbSalt, "SHA1", 100, cspParams) {}
public PasswordDeriveBytes (byte[] password, byte[] salt, CspParameters cspParams) :
this (password, salt, "SHA1", 100, cspParams) {}
public PasswordDeriveBytes (string strPassword, byte[] rgbSalt, String strHashName, int iterations, CspParameters cspParams) :
this ((new UTF8Encoding(false)).GetBytes(strPassword), rgbSalt, strHashName, iterations, cspParams) {}
// This method needs to be safe critical, because in debug builds the C# compiler will include null
// initialization of the _safeProvHandle field in the method. Since SafeProvHandle is critical, a
// transparent reference triggers an error using PasswordDeriveBytes.
[SecuritySafeCritical]
public PasswordDeriveBytes (byte[] password, byte[] salt, String hashName, int iterations, CspParameters cspParams) {
this.IterationCount = iterations;
this.Salt = salt;
this.HashName = hashName;
_password = password;
_cspParams = cspParams;
}
//
// public properties
//
public String HashName {
get { return _hashName; }
set {
if (_baseValue != null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "HashName"));
_hashName = value;
_hash = (HashAlgorithm) CryptoConfig.CreateFromName(_hashName);
}
}
public int IterationCount {
get { return _iterations; }
set {
if (value <= 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
if (_baseValue != null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "IterationCount"));
_iterations = value;
}
}
public byte[] Salt {
get {
if (_salt == null)
return null;
return (byte[]) _salt.Clone();
}
set {
if (_baseValue != null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_ValuesFixed", "Salt"));
if (value == null)
_salt = null;
else
_salt = (byte[]) value.Clone();
}
}
//
// public methods
//
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("Rfc2898DeriveBytes replaces PasswordDeriveBytes for deriving key material from a password and is preferred in new applications.")]
// disable csharp compiler warning #0809: obsolete member overrides non-obsolete member
#pragma warning disable 0809
public override byte[] GetBytes(int cb) {
int ib = 0;
byte[] rgb;
byte[] rgbOut = new byte[cb];
if (_baseValue == null) {
ComputeBaseValue();
}
else if (_extra != null) {
ib = _extra.Length - _extraCount;
if (ib >= cb) {
Buffer.InternalBlockCopy(_extra, _extraCount, rgbOut, 0, cb);
if (ib > cb)
_extraCount += cb;
else
_extra = null;
return rgbOut;
}
else {
//
// Note: The second parameter should really be _extraCount instead
// However, changing this would constitute a breaking change compared
// to what has shipped in V1.x.
//
Buffer.InternalBlockCopy(_extra, ib, rgbOut, 0, ib);
_extra = null;
}
}
rgb = ComputeBytes(cb-ib);
Buffer.InternalBlockCopy(rgb, 0, rgbOut, ib, cb-ib);
if (rgb.Length + ib > cb) {
_extra = rgb;
_extraCount = cb-ib;
}
return rgbOut;
}
#pragma warning restore 0809
public override void Reset() {
_prefix = 0;
_extra = null;
_baseValue = null;
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (disposing) {
if (_hash != null) {
_hash.Dispose();
}
if (_baseValue != null) {
Array.Clear(_baseValue, 0, _baseValue.Length);
}
if (_extra != null) {
Array.Clear(_extra, 0, _extra.Length);
}
if (_password != null) {
Array.Clear(_password, 0, _password.Length);
}
if (_salt != null) {
Array.Clear(_salt, 0, _salt.Length);
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
{
if (keySize < 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
int algidhash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm);
if (algidhash == 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups);
if (algid == 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
// Validate the rgbIV array
if (rgbIV == null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidIV"));
byte[] key = null;
DeriveKey(ProvHandle, algid, algidhash,
_password, _password.Length, keySize << 16, rgbIV, rgbIV.Length,
JitHelpers.GetObjectHandleOnStack(ref key));
return key;
}
//
// private methods
//
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void DeriveKey(SafeProvHandle hProv, int algid, int algidHash,
byte[] password, int cbPassword, int dwFlags, byte[] IV, int cbIV,
ObjectHandleOnStack retKey);
private byte[] ComputeBaseValue() {
_hash.Initialize();
_hash.TransformBlock(_password, 0, _password.Length, _password, 0);
if (_salt != null)
_hash.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
_hash.TransformFinalBlock(EmptyArray<Byte>.Value, 0, 0);
_baseValue = _hash.Hash;
_hash.Initialize();
for (int i=1; i<(_iterations-1); i++) {
_hash.ComputeHash(_baseValue);
_baseValue = _hash.Hash;
}
return _baseValue;
}
[System.Security.SecurityCritical] // auto-generated
private byte[] ComputeBytes(int cb) {
int cbHash;
int ib = 0;
byte[] rgb;
_hash.Initialize();
cbHash = _hash.HashSize / 8;
rgb = new byte[((cb+cbHash-1)/cbHash)*cbHash];
using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write)) {
HashPrefix(cs);
cs.Write(_baseValue, 0, _baseValue.Length);
cs.Close();
}
Buffer.InternalBlockCopy(_hash.Hash, 0, rgb, ib, cbHash);
ib += cbHash;
while (cb > ib) {
_hash.Initialize();
using (CryptoStream cs = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write)) {
HashPrefix(cs);
cs.Write(_baseValue, 0, _baseValue.Length);
cs.Close();
}
Buffer.InternalBlockCopy(_hash.Hash, 0, rgb, ib, cbHash);
ib += cbHash;
}
return rgb;
}
void HashPrefix(CryptoStream cs) {
int cb = 0;
byte[] rgb = {(byte)'0', (byte)'0', (byte)'0'};
if (_prefix > 999)
throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_TooManyBytes"));
if (_prefix >= 100) {
rgb[0] += (byte) (_prefix /100);
cb += 1;
}
if (_prefix >= 10) {
rgb[cb] += (byte) ((_prefix % 100) / 10);
cb += 1;
}
if (_prefix > 0) {
rgb[cb] += (byte) (_prefix % 10);
cb += 1;
cs.Write(rgb, 0, cb);
}
_prefix += 1;
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace Irony.Parsing {
#region notes
//Identifier terminal. Matches alpha-numeric sequences that usually represent identifiers and keywords.
// c#: @ prefix signals to not interpret as a keyword; allows \u escapes
//
#endregion
[Flags]
public enum IdOptions : short {
None = 0,
AllowsEscapes = 0x01,
CanStartWithEscape = 0x03,
IsNotKeyword = 0x10,
NameIncludesPrefix = 0x20,
}
public enum CaseRestriction {
None,
FirstUpper,
FirstLower,
AllUpper,
AllLower
}
public class UnicodeCategoryList : List<UnicodeCategory> { }
public class IdentifierTerminal : CompoundTerminalBase {
//Id flags for internal use
internal enum IdFlagsInternal : short {
HasEscapes = 0x100,
}
#region constructors and initialization
public IdentifierTerminal(string name) : this(name, IdOptions.None) {
}
public IdentifierTerminal(string name, IdOptions options) : this(name, "_", "_") {
Options = options;
}
public IdentifierTerminal(string name, string extraChars, string extraFirstChars = ""): base(name) {
AllFirstChars = Strings.AllLatinLetters + extraFirstChars;
AllChars = Strings.AllLatinLetters + Strings.DecimalDigits + extraChars;
}
public void AddPrefix(string prefix, IdOptions options) {
base.AddPrefixFlag(prefix, (short)options);
}
#endregion
#region properties: AllChars, AllFirstChars
CharHashSet _allCharsSet;
CharHashSet _allFirstCharsSet;
public string AllFirstChars;
public string AllChars;
public TokenEditorInfo KeywordEditorInfo = new TokenEditorInfo(TokenType.Keyword, TokenColor.Keyword, TokenTriggers.None);
public IdOptions Options; //flags for the case when there are no prefixes
public CaseRestriction CaseRestriction;
public readonly UnicodeCategoryList StartCharCategories = new UnicodeCategoryList(); //categories of first char
public readonly UnicodeCategoryList CharCategories = new UnicodeCategoryList(); //categories of all other chars
public readonly UnicodeCategoryList CharsToRemoveCategories = new UnicodeCategoryList(); //categories of chars to remove from final id, usually formatting category
#endregion
#region overrides
public override void Init(GrammarData grammarData) {
base.Init(grammarData);
_allCharsSet = new CharHashSet(Grammar.CaseSensitive);
_allCharsSet.UnionWith(AllChars.ToCharArray());
//Adjust case restriction. We adjust only first chars; if first char is ok, we will scan the rest without restriction
// and then check casing for entire identifier
switch(CaseRestriction) {
case CaseRestriction.AllLower:
case CaseRestriction.FirstLower:
_allFirstCharsSet = new CharHashSet(true);
_allFirstCharsSet.UnionWith(AllFirstChars.ToLowerInvariant().ToCharArray());
break;
case CaseRestriction.AllUpper:
case CaseRestriction.FirstUpper:
_allFirstCharsSet = new CharHashSet(true);
_allFirstCharsSet.UnionWith(AllFirstChars.ToUpperInvariant().ToCharArray());
break;
default: //None
_allFirstCharsSet = new CharHashSet(Grammar.CaseSensitive);
_allFirstCharsSet.UnionWith(AllFirstChars.ToCharArray());
break;
}
//if there are "first" chars defined by categories, add the terminal to FallbackTerminals
if (this.StartCharCategories.Count > 0)
grammarData.NoPrefixTerminals.Add(this);
if (this.EditorInfo == null)
this.EditorInfo = new TokenEditorInfo(TokenType.Identifier, TokenColor.Identifier, TokenTriggers.None);
}
public override IList<string> GetFirsts() {
// new scanner: identifier has no prefixes
return null;
/*
var list = new StringList();
list.AddRange(Prefixes);
foreach (char ch in _allFirstCharsSet)
list.Add(ch.ToString());
if ((Options & IdOptions.CanStartWithEscape) != 0)
list.Add(this.EscapeChar.ToString());
return list;
*/
}
protected override void InitDetails(ParsingContext context, CompoundTokenDetails details) {
base.InitDetails(context, details);
details.Flags = (short)Options;
}
//Override to assign IsKeyword flag to keyword tokens
protected override Token CreateToken(ParsingContext context, ISourceStream source, CompoundTokenDetails details) {
Token token = base.CreateToken(context, source, details);
if (details.IsSet((short)IdOptions.IsNotKeyword))
return token;
//check if it is keyword
CheckReservedWord(token);
return token;
}
private void CheckReservedWord(Token token) {
KeyTerm keyTerm;
if (Grammar.KeyTerms.TryGetValue(token.Text, out keyTerm)) {
token.KeyTerm = keyTerm;
//if it is reserved word, then overwrite terminal
if (keyTerm.Flags.IsSet(TermFlags.IsReservedWord))
token.SetTerminal(keyTerm);
}
}
protected override Token QuickParse(ParsingContext context, ISourceStream source) {
if (!_allFirstCharsSet.Contains(source.PreviewChar))
return null;
source.PreviewPosition++;
while (_allCharsSet.Contains(source.PreviewChar) && !source.EOF())
source.PreviewPosition++;
//if it is not a terminator then cancel; we need to go through full algorithm
if (!this.Grammar.IsWhitespaceOrDelimiter(source.PreviewChar))
return null;
var token = source.CreateToken(this.OutputTerminal);
if(CaseRestriction != CaseRestriction.None && !CheckCaseRestriction(token.ValueString))
return null;
//!!! Do not convert to common case (all-lower) for case-insensitive grammar. Let identifiers remain as is,
// it is responsibility of interpreter to provide case-insensitive read/write operations for identifiers
// if (!this.GrammarData.Grammar.CaseSensitive)
// token.Value = token.Text.ToLower(context.Culture);
CheckReservedWord(token);
return token;
}
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) {
int start = source.PreviewPosition;
bool allowEscapes = details.IsSet((short)IdOptions.AllowsEscapes);
CharList outputChars = new CharList();
while (!source.EOF()) {
char current = source.PreviewChar;
if (Grammar.IsWhitespaceOrDelimiter(current))
break;
if (allowEscapes && current == this.EscapeChar) {
current = ReadUnicodeEscape(source, details);
//We need to back off the position. ReadUnicodeEscape sets the position to symbol right after escape digits.
//This is the char that we should process in next iteration, so we must backup one char, to pretend the escaped
// char is at position of last digit of escape sequence.
source.PreviewPosition--;
if (details.Error != null)
return false;
}
//Check if current character is OK
if (!CharOk(current, source.PreviewPosition == start))
break;
//Check if we need to skip this char
UnicodeCategory currCat = CharUnicodeInfo.GetUnicodeCategory(current); //I know, it suxx, we do it twice, fix it later
if (!this.CharsToRemoveCategories.Contains(currCat))
outputChars.Add(current); //add it to output (identifier)
source.PreviewPosition++;
}//while
if (outputChars.Count == 0)
return false;
//Convert collected chars to string
details.Body = new string(outputChars.ToArray());
if (!CheckCaseRestriction(details.Body))
return false;
return !string.IsNullOrEmpty(details.Body);
}
private bool CharOk(char ch, bool first) {
//first check char lists, then categories
var charSet = first? _allFirstCharsSet : _allCharsSet;
if(charSet.Contains(ch)) return true;
//check categories
if (CharCategories.Count > 0) {
UnicodeCategory chCat = CharUnicodeInfo.GetUnicodeCategory(ch);
UnicodeCategoryList catList = first ? StartCharCategories : CharCategories;
if (catList.Contains(chCat)) return true;
}
return false;
}
private bool CheckCaseRestriction(string body) {
switch(CaseRestriction) {
case CaseRestriction.FirstLower: return Char.IsLower(body, 0);
case CaseRestriction.FirstUpper: return Char.IsUpper(body, 0);
case CaseRestriction.AllLower: return body.ToLower() == body;
case CaseRestriction.AllUpper: return body.ToUpper() == body;
default : return true;
}
}//method
private char ReadUnicodeEscape(ISourceStream source, CompoundTokenDetails details) {
//Position is currently at "\" symbol
source.PreviewPosition++; //move to U/u char
int len;
switch (source.PreviewChar) {
case 'u': len = 4; break;
case 'U': len = 8; break;
default:
details.Error = Resources.ErrInvEscSymbol; // "Invalid escape symbol, expected 'u' or 'U' only."
return '\0';
}
if (source.PreviewPosition + len > source.Text.Length) {
details.Error = Resources.ErrInvEscSeq; // "Invalid escape sequence";
return '\0';
}
source.PreviewPosition++; //move to the first digit
string digits = source.Text.Substring(source.PreviewPosition, len);
char result = (char)Convert.ToUInt32(digits, 16);
source.PreviewPosition += len;
details.Flags |= (int) IdFlagsInternal.HasEscapes;
return result;
}
protected override bool ConvertValue(CompoundTokenDetails details, ParsingContext context) {
if (details.IsSet((short)IdOptions.NameIncludesPrefix))
details.Value = details.Prefix + details.Body;
else
details.Value = details.Body;
return true;
}
#endregion
}//class
} //namespace
| |
using SevenZip.Compression.LZ;
using SevenZip.Compression.RangeCoder;
using System;
using System.IO;
namespace SevenZip.Compression.LZMA
{
public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties
{
private enum EMatchFinderType
{
BT2,
BT4
}
private class LiteralEncoder
{
public struct Encoder2
{
private BitEncoder[] m_Encoders;
public void Create()
{
this.m_Encoders = new BitEncoder[768];
}
public void Init()
{
for (int i = 0; i < 768; i++)
{
this.m_Encoders[i].Init();
}
}
public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte symbol)
{
uint num = 1u;
for (int i = 7; i >= 0; i--)
{
uint num2 = (uint)(symbol >> i & 1);
this.m_Encoders[(int)((UIntPtr)num)].Encode(rangeEncoder, num2);
num = (num << 1 | num2);
}
}
public void EncodeMatched(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
{
uint num = 1u;
bool flag = true;
for (int i = 7; i >= 0; i--)
{
uint num2 = (uint)(symbol >> i & 1);
uint num3 = num;
if (flag)
{
uint num4 = (uint)(matchByte >> i & 1);
num3 += 1u + num4 << 8;
flag = (num4 == num2);
}
this.m_Encoders[(int)((UIntPtr)num3)].Encode(rangeEncoder, num2);
num = (num << 1 | num2);
}
}
public uint GetPrice(bool matchMode, byte matchByte, byte symbol)
{
uint num = 0u;
uint num2 = 1u;
int i = 7;
if (matchMode)
{
while (i >= 0)
{
uint num3 = (uint)(matchByte >> i & 1);
uint num4 = (uint)(symbol >> i & 1);
num += this.m_Encoders[(int)((UIntPtr)((1u + num3 << 8) + num2))].GetPrice(num4);
num2 = (num2 << 1 | num4);
if (num3 != num4)
{
i--;
break;
}
i--;
}
}
while (i >= 0)
{
uint num5 = (uint)(symbol >> i & 1);
num += this.m_Encoders[(int)((UIntPtr)num2)].GetPrice(num5);
num2 = (num2 << 1 | num5);
i--;
}
return num;
}
}
private Encoder.LiteralEncoder.Encoder2[] m_Coders;
private int m_NumPrevBits;
private int m_NumPosBits;
private uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (this.m_Coders != null && this.m_NumPrevBits == numPrevBits && this.m_NumPosBits == numPosBits)
{
return;
}
this.m_NumPosBits = numPosBits;
this.m_PosMask = (1u << numPosBits) - 1u;
this.m_NumPrevBits = numPrevBits;
uint num = 1u << this.m_NumPrevBits + this.m_NumPosBits;
this.m_Coders = new Encoder.LiteralEncoder.Encoder2[num];
for (uint num2 = 0u; num2 < num; num2 += 1u)
{
this.m_Coders[(int)((UIntPtr)num2)].Create();
}
}
public void Init()
{
uint num = 1u << this.m_NumPrevBits + this.m_NumPosBits;
for (uint num2 = 0u; num2 < num; num2 += 1u)
{
this.m_Coders[(int)((UIntPtr)num2)].Init();
}
}
public Encoder.LiteralEncoder.Encoder2 GetSubCoder(uint pos, byte prevByte)
{
return this.m_Coders[(int)((UIntPtr)(((pos & this.m_PosMask) << this.m_NumPrevBits) + (uint)(prevByte >> 8 - this.m_NumPrevBits)))];
}
}
private class LenEncoder
{
private BitEncoder _choice = default(BitEncoder);
private BitEncoder _choice2 = default(BitEncoder);
private BitTreeEncoder[] _lowCoder = new BitTreeEncoder[16];
private BitTreeEncoder[] _midCoder = new BitTreeEncoder[16];
private BitTreeEncoder _highCoder = new BitTreeEncoder(8);
public LenEncoder()
{
for (uint num = 0u; num < 16u; num += 1u)
{
this._lowCoder[(int)((UIntPtr)num)] = new BitTreeEncoder(3);
this._midCoder[(int)((UIntPtr)num)] = new BitTreeEncoder(3);
}
}
public void Init(uint numPosStates)
{
this._choice.Init();
this._choice2.Init();
for (uint num = 0u; num < numPosStates; num += 1u)
{
this._lowCoder[(int)((UIntPtr)num)].Init();
this._midCoder[(int)((UIntPtr)num)].Init();
}
this._highCoder.Init();
}
public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, uint symbol, uint posState)
{
if (symbol < 8u)
{
this._choice.Encode(rangeEncoder, 0u);
this._lowCoder[(int)((UIntPtr)posState)].Encode(rangeEncoder, symbol);
}
else
{
symbol -= 8u;
this._choice.Encode(rangeEncoder, 1u);
if (symbol < 8u)
{
this._choice2.Encode(rangeEncoder, 0u);
this._midCoder[(int)((UIntPtr)posState)].Encode(rangeEncoder, symbol);
}
else
{
this._choice2.Encode(rangeEncoder, 1u);
this._highCoder.Encode(rangeEncoder, symbol - 8u);
}
}
}
public void SetPrices(uint posState, uint numSymbols, uint[] prices, uint st)
{
uint price = this._choice.GetPrice0();
uint price2 = this._choice.GetPrice1();
uint num = price2 + this._choice2.GetPrice0();
uint num2 = price2 + this._choice2.GetPrice1();
uint num3;
for (num3 = 0u; num3 < 8u; num3 += 1u)
{
if (num3 >= numSymbols)
{
return;
}
prices[(int)((UIntPtr)(st + num3))] = price + this._lowCoder[(int)((UIntPtr)posState)].GetPrice(num3);
}
while (num3 < 16u)
{
if (num3 >= numSymbols)
{
return;
}
prices[(int)((UIntPtr)(st + num3))] = num + this._midCoder[(int)((UIntPtr)posState)].GetPrice(num3 - 8u);
num3 += 1u;
}
while (num3 < numSymbols)
{
prices[(int)((UIntPtr)(st + num3))] = num2 + this._highCoder.GetPrice(num3 - 8u - 8u);
num3 += 1u;
}
}
}
private class LenPriceTableEncoder : Encoder.LenEncoder
{
private uint[] _prices = new uint[4352];
private uint _tableSize;
private uint[] _counters = new uint[16];
public void SetTableSize(uint tableSize)
{
this._tableSize = tableSize;
}
public uint GetPrice(uint symbol, uint posState)
{
return this._prices[(int)((UIntPtr)(posState * 272u + symbol))];
}
private void UpdateTable(uint posState)
{
base.SetPrices(posState, this._tableSize, this._prices, posState * 272u);
this._counters[(int)((UIntPtr)posState)] = this._tableSize;
}
public void UpdateTables(uint numPosStates)
{
for (uint num = 0u; num < numPosStates; num += 1u)
{
this.UpdateTable(num);
}
}
public new void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, uint symbol, uint posState)
{
base.Encode(rangeEncoder, symbol, posState);
if ((this._counters[(int)((UIntPtr)posState)] -= 1u) == 0u)
{
this.UpdateTable(posState);
}
}
}
private class Optimal
{
public Base.State State;
public bool Prev1IsChar;
public bool Prev2;
public uint PosPrev2;
public uint BackPrev2;
public uint Price;
public uint PosPrev;
public uint BackPrev;
public uint Backs0;
public uint Backs1;
public uint Backs2;
public uint Backs3;
public void MakeAsChar()
{
this.BackPrev = 4294967295u;
this.Prev1IsChar = false;
}
public void MakeAsShortRep()
{
this.BackPrev = 0u;
this.Prev1IsChar = false;
}
public bool IsShortRep()
{
return this.BackPrev == 0u;
}
}
private const uint kIfinityPrice = 268435455u;
private const int kDefaultDictionaryLogSize = 22;
private const uint kNumFastBytesDefault = 32u;
private const uint kNumLenSpecSymbols = 16u;
private const uint kNumOpts = 4096u;
private const int kPropSize = 5;
private static byte[] g_FastPos;
private Base.State _state = default(Base.State);
private byte _previousByte;
private uint[] _repDistances = new uint[4];
private Encoder.Optimal[] _optimum = new Encoder.Optimal[4096];
private IMatchFinder _matchFinder;
private SevenZip.Compression.RangeCoder.Encoder _rangeEncoder = new SevenZip.Compression.RangeCoder.Encoder();
private BitEncoder[] _isMatch = new BitEncoder[192];
private BitEncoder[] _isRep = new BitEncoder[12];
private BitEncoder[] _isRepG0 = new BitEncoder[12];
private BitEncoder[] _isRepG1 = new BitEncoder[12];
private BitEncoder[] _isRepG2 = new BitEncoder[12];
private BitEncoder[] _isRep0Long = new BitEncoder[192];
private BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[4];
private BitEncoder[] _posEncoders = new BitEncoder[114];
private BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(4);
private Encoder.LenPriceTableEncoder _lenEncoder = new Encoder.LenPriceTableEncoder();
private Encoder.LenPriceTableEncoder _repMatchLenEncoder = new Encoder.LenPriceTableEncoder();
private Encoder.LiteralEncoder _literalEncoder = new Encoder.LiteralEncoder();
private uint[] _matchDistances = new uint[548];
private uint _numFastBytes = 32u;
private uint _longestMatchLength;
private uint _numDistancePairs;
private uint _additionalOffset;
private uint _optimumEndIndex;
private uint _optimumCurrentIndex;
private bool _longestMatchWasFound;
private uint[] _posSlotPrices = new uint[256];
private uint[] _distancesPrices = new uint[512];
private uint[] _alignPrices = new uint[16];
private uint _alignPriceCount;
private uint _distTableSize = 44u;
private int _posStateBits = 2;
private uint _posStateMask = 3u;
private int _numLiteralPosStateBits;
private int _numLiteralContextBits = 3;
private uint _dictionarySize = 4194304u;
private uint _dictionarySizePrev = 4294967295u;
private uint _numFastBytesPrev = 4294967295u;
private long nowPos64;
private bool _finished;
private Stream _inStream;
private Encoder.EMatchFinderType _matchFinderType = Encoder.EMatchFinderType.BT4;
private bool _writeEndMark;
private bool _needReleaseMFStream;
private uint[] reps = new uint[4];
private uint[] repLens = new uint[4];
private byte[] properties = new byte[5];
private uint[] tempPrices = new uint[128];
private uint _matchPriceCount;
private static string[] kMatchFinderIDs;
private uint _trainSize;
public Encoder()
{
int num = 0;
while ((long)num < 4096L)
{
this._optimum[num] = new Encoder.Optimal();
num++;
}
int num2 = 0;
while ((long)num2 < 4L)
{
this._posSlotEncoder[num2] = new BitTreeEncoder(6);
num2++;
}
}
static Encoder()
{
Encoder.g_FastPos = new byte[2048];
Encoder.kMatchFinderIDs = new string[]
{
"BT2",
"BT4"
};
int num = 2;
Encoder.g_FastPos[0] = 0;
Encoder.g_FastPos[1] = 1;
for (byte b = 2; b < 22; b += 1)
{
uint num2 = 1u << (b >> 1) - 1;
uint num3 = 0u;
while (num3 < num2)
{
Encoder.g_FastPos[num] = b;
num3 += 1u;
num++;
}
}
}
private static uint GetPosSlot(uint pos)
{
if (pos < 2048u)
{
return (uint)Encoder.g_FastPos[(int)((UIntPtr)pos)];
}
if (pos < 2097152u)
{
return (uint)(Encoder.g_FastPos[(int)((UIntPtr)(pos >> 10))] + 20);
}
return (uint)(Encoder.g_FastPos[(int)((UIntPtr)(pos >> 20))] + 40);
}
private static uint GetPosSlot2(uint pos)
{
if (pos < 131072u)
{
return (uint)(Encoder.g_FastPos[(int)((UIntPtr)(pos >> 6))] + 12);
}
if (pos < 134217728u)
{
return (uint)(Encoder.g_FastPos[(int)((UIntPtr)(pos >> 16))] + 32);
}
return (uint)(Encoder.g_FastPos[(int)((UIntPtr)(pos >> 26))] + 52);
}
private void BaseInit()
{
this._state.Init();
this._previousByte = 0;
for (uint num = 0u; num < 4u; num += 1u)
{
this._repDistances[(int)((UIntPtr)num)] = 0u;
}
}
private void Create()
{
if (this._matchFinder == null)
{
BinTree binTree = new BinTree();
int type = 4;
if (this._matchFinderType == Encoder.EMatchFinderType.BT2)
{
type = 2;
}
binTree.SetType(type);
this._matchFinder = binTree;
}
this._literalEncoder.Create(this._numLiteralPosStateBits, this._numLiteralContextBits);
if (this._dictionarySize == this._dictionarySizePrev && this._numFastBytesPrev == this._numFastBytes)
{
return;
}
this._matchFinder.Create(this._dictionarySize, 4096u, this._numFastBytes, 274u);
this._dictionarySizePrev = this._dictionarySize;
this._numFastBytesPrev = this._numFastBytes;
}
private void SetWriteEndMarkerMode(bool writeEndMarker)
{
this._writeEndMark = writeEndMarker;
}
private void Init()
{
this.BaseInit();
this._rangeEncoder.Init();
for (uint num = 0u; num < 12u; num += 1u)
{
for (uint num2 = 0u; num2 <= this._posStateMask; num2 += 1u)
{
uint num3 = (num << 4) + num2;
this._isMatch[(int)((UIntPtr)num3)].Init();
this._isRep0Long[(int)((UIntPtr)num3)].Init();
}
this._isRep[(int)((UIntPtr)num)].Init();
this._isRepG0[(int)((UIntPtr)num)].Init();
this._isRepG1[(int)((UIntPtr)num)].Init();
this._isRepG2[(int)((UIntPtr)num)].Init();
}
this._literalEncoder.Init();
for (uint num = 0u; num < 4u; num += 1u)
{
this._posSlotEncoder[(int)((UIntPtr)num)].Init();
}
for (uint num = 0u; num < 114u; num += 1u)
{
this._posEncoders[(int)((UIntPtr)num)].Init();
}
this._lenEncoder.Init(1u << this._posStateBits);
this._repMatchLenEncoder.Init(1u << this._posStateBits);
this._posAlignEncoder.Init();
this._longestMatchWasFound = false;
this._optimumEndIndex = 0u;
this._optimumCurrentIndex = 0u;
this._additionalOffset = 0u;
}
private void ReadMatchDistances(out uint lenRes, out uint numDistancePairs)
{
lenRes = 0u;
numDistancePairs = this._matchFinder.GetMatches(this._matchDistances);
if (numDistancePairs > 0u)
{
lenRes = this._matchDistances[(int)((UIntPtr)(numDistancePairs - 2u))];
if (lenRes == this._numFastBytes)
{
lenRes += this._matchFinder.GetMatchLen((int)(lenRes - 1u), this._matchDistances[(int)((UIntPtr)(numDistancePairs - 1u))], 273u - lenRes);
}
}
this._additionalOffset += 1u;
}
private void MovePos(uint num)
{
if (num > 0u)
{
this._matchFinder.Skip(num);
this._additionalOffset += num;
}
}
private uint GetRepLen1Price(Base.State state, uint posState)
{
return this._isRepG0[(int)((UIntPtr)state.Index)].GetPrice0() + this._isRep0Long[(int)((UIntPtr)((state.Index << 4) + posState))].GetPrice0();
}
private uint GetPureRepPrice(uint repIndex, Base.State state, uint posState)
{
uint num;
if (repIndex == 0u)
{
num = this._isRepG0[(int)((UIntPtr)state.Index)].GetPrice0();
num += this._isRep0Long[(int)((UIntPtr)((state.Index << 4) + posState))].GetPrice1();
}
else
{
num = this._isRepG0[(int)((UIntPtr)state.Index)].GetPrice1();
if (repIndex == 1u)
{
num += this._isRepG1[(int)((UIntPtr)state.Index)].GetPrice0();
}
else
{
num += this._isRepG1[(int)((UIntPtr)state.Index)].GetPrice1();
num += this._isRepG2[(int)((UIntPtr)state.Index)].GetPrice(repIndex - 2u);
}
}
return num;
}
private uint GetRepPrice(uint repIndex, uint len, Base.State state, uint posState)
{
uint price = this._repMatchLenEncoder.GetPrice(len - 2u, posState);
return price + this.GetPureRepPrice(repIndex, state, posState);
}
private uint GetPosLenPrice(uint pos, uint len, uint posState)
{
uint lenToPosState = Base.GetLenToPosState(len);
uint num;
if (pos < 128u)
{
num = this._distancesPrices[(int)((UIntPtr)(lenToPosState * 128u + pos))];
}
else
{
num = this._posSlotPrices[(int)((UIntPtr)((lenToPosState << 6) + Encoder.GetPosSlot2(pos)))] + this._alignPrices[(int)((UIntPtr)(pos & 15u))];
}
return num + this._lenEncoder.GetPrice(len - 2u, posState);
}
private uint Backward(out uint backRes, uint cur)
{
this._optimumEndIndex = cur;
uint posPrev = this._optimum[(int)((UIntPtr)cur)].PosPrev;
uint backPrev = this._optimum[(int)((UIntPtr)cur)].BackPrev;
do
{
if (this._optimum[(int)((UIntPtr)cur)].Prev1IsChar)
{
this._optimum[(int)((UIntPtr)posPrev)].MakeAsChar();
this._optimum[(int)((UIntPtr)posPrev)].PosPrev = posPrev - 1u;
if (this._optimum[(int)((UIntPtr)cur)].Prev2)
{
this._optimum[(int)((UIntPtr)(posPrev - 1u))].Prev1IsChar = false;
this._optimum[(int)((UIntPtr)(posPrev - 1u))].PosPrev = this._optimum[(int)((UIntPtr)cur)].PosPrev2;
this._optimum[(int)((UIntPtr)(posPrev - 1u))].BackPrev = this._optimum[(int)((UIntPtr)cur)].BackPrev2;
}
}
uint num = posPrev;
uint backPrev2 = backPrev;
backPrev = this._optimum[(int)((UIntPtr)num)].BackPrev;
posPrev = this._optimum[(int)((UIntPtr)num)].PosPrev;
this._optimum[(int)((UIntPtr)num)].BackPrev = backPrev2;
this._optimum[(int)((UIntPtr)num)].PosPrev = cur;
cur = num;
}
while (cur > 0u);
backRes = this._optimum[0].BackPrev;
this._optimumCurrentIndex = this._optimum[0].PosPrev;
return this._optimumCurrentIndex;
}
private uint GetOptimum(uint position, out uint backRes)
{
if (this._optimumEndIndex != this._optimumCurrentIndex)
{
uint result = this._optimum[(int)((UIntPtr)this._optimumCurrentIndex)].PosPrev - this._optimumCurrentIndex;
backRes = this._optimum[(int)((UIntPtr)this._optimumCurrentIndex)].BackPrev;
this._optimumCurrentIndex = this._optimum[(int)((UIntPtr)this._optimumCurrentIndex)].PosPrev;
return result;
}
this._optimumCurrentIndex = (this._optimumEndIndex = 0u);
uint longestMatchLength;
uint num;
if (!this._longestMatchWasFound)
{
this.ReadMatchDistances(out longestMatchLength, out num);
}
else
{
longestMatchLength = this._longestMatchLength;
num = this._numDistancePairs;
this._longestMatchWasFound = false;
}
uint num2 = this._matchFinder.GetNumAvailableBytes() + 1u;
if (num2 < 2u)
{
backRes = 4294967295u;
return 1u;
}
if (num2 > 273u)
{
}
uint num3 = 0u;
for (uint num4 = 0u; num4 < 4u; num4 += 1u)
{
this.reps[(int)((UIntPtr)num4)] = this._repDistances[(int)((UIntPtr)num4)];
this.repLens[(int)((UIntPtr)num4)] = this._matchFinder.GetMatchLen(-1, this.reps[(int)((UIntPtr)num4)], 273u);
if (this.repLens[(int)((UIntPtr)num4)] > this.repLens[(int)((UIntPtr)num3)])
{
num3 = num4;
}
}
if (this.repLens[(int)((UIntPtr)num3)] >= this._numFastBytes)
{
backRes = num3;
uint num5 = this.repLens[(int)((UIntPtr)num3)];
this.MovePos(num5 - 1u);
return num5;
}
if (longestMatchLength >= this._numFastBytes)
{
backRes = this._matchDistances[(int)((UIntPtr)(num - 1u))] + 4u;
this.MovePos(longestMatchLength - 1u);
return longestMatchLength;
}
byte indexByte = this._matchFinder.GetIndexByte(-1);
byte indexByte2 = this._matchFinder.GetIndexByte((int)(0u - this._repDistances[0] - 1u - 1u));
if (longestMatchLength < 2u && indexByte != indexByte2 && this.repLens[(int)((UIntPtr)num3)] < 2u)
{
backRes = 4294967295u;
return 1u;
}
this._optimum[0].State = this._state;
uint num6 = position & this._posStateMask;
this._optimum[1].Price = this._isMatch[(int)((UIntPtr)((this._state.Index << 4) + num6))].GetPrice0() + this._literalEncoder.GetSubCoder(position, this._previousByte).GetPrice(!this._state.IsCharState(), indexByte2, indexByte);
this._optimum[1].MakeAsChar();
uint num7 = this._isMatch[(int)((UIntPtr)((this._state.Index << 4) + num6))].GetPrice1();
uint num8 = num7 + this._isRep[(int)((UIntPtr)this._state.Index)].GetPrice1();
if (indexByte2 == indexByte)
{
uint num9 = num8 + this.GetRepLen1Price(this._state, num6);
if (num9 < this._optimum[1].Price)
{
this._optimum[1].Price = num9;
this._optimum[1].MakeAsShortRep();
}
}
uint num10 = (longestMatchLength < this.repLens[(int)((UIntPtr)num3)]) ? this.repLens[(int)((UIntPtr)num3)] : longestMatchLength;
if (num10 < 2u)
{
backRes = this._optimum[1].BackPrev;
return 1u;
}
this._optimum[1].PosPrev = 0u;
this._optimum[0].Backs0 = this.reps[0];
this._optimum[0].Backs1 = this.reps[1];
this._optimum[0].Backs2 = this.reps[2];
this._optimum[0].Backs3 = this.reps[3];
uint num11 = num10;
do
{
this._optimum[(int)((UIntPtr)(num11--))].Price = 268435455u;
}
while (num11 >= 2u);
for (uint num4 = 0u; num4 < 4u; num4 += 1u)
{
uint num12 = this.repLens[(int)((UIntPtr)num4)];
if (num12 >= 2u)
{
uint num13 = num8 + this.GetPureRepPrice(num4, this._state, num6);
do
{
uint num14 = num13 + this._repMatchLenEncoder.GetPrice(num12 - 2u, num6);
Encoder.Optimal optimal = this._optimum[(int)((UIntPtr)num12)];
if (num14 < optimal.Price)
{
optimal.Price = num14;
optimal.PosPrev = 0u;
optimal.BackPrev = num4;
optimal.Prev1IsChar = false;
}
}
while ((num12 -= 1u) >= 2u);
}
}
uint num15 = num7 + this._isRep[(int)((UIntPtr)this._state.Index)].GetPrice0();
num11 = ((this.repLens[0] < 2u) ? 2u : (this.repLens[0] + 1u));
if (num11 <= longestMatchLength)
{
uint num16 = 0u;
while (num11 > this._matchDistances[(int)((UIntPtr)num16)])
{
num16 += 2u;
}
while (true)
{
uint num17 = this._matchDistances[(int)((UIntPtr)(num16 + 1u))];
uint num18 = num15 + this.GetPosLenPrice(num17, num11, num6);
Encoder.Optimal optimal2 = this._optimum[(int)((UIntPtr)num11)];
if (num18 < optimal2.Price)
{
optimal2.Price = num18;
optimal2.PosPrev = 0u;
optimal2.BackPrev = num17 + 4u;
optimal2.Prev1IsChar = false;
}
if (num11 == this._matchDistances[(int)((UIntPtr)num16)])
{
num16 += 2u;
if (num16 == num)
{
break;
}
}
num11 += 1u;
}
}
uint num19 = 0u;
uint num20;
while (true)
{
num19 += 1u;
if (num19 == num10)
{
break;
}
this.ReadMatchDistances(out num20, out num);
if (num20 >= this._numFastBytes)
{
goto Block_26;
}
position += 1u;
uint num21 = this._optimum[(int)((UIntPtr)num19)].PosPrev;
Base.State state;
if (this._optimum[(int)((UIntPtr)num19)].Prev1IsChar)
{
num21 -= 1u;
if (this._optimum[(int)((UIntPtr)num19)].Prev2)
{
state = this._optimum[(int)((UIntPtr)this._optimum[(int)((UIntPtr)num19)].PosPrev2)].State;
if (this._optimum[(int)((UIntPtr)num19)].BackPrev2 < 4u)
{
state.UpdateRep();
}
else
{
state.UpdateMatch();
}
}
else
{
state = this._optimum[(int)((UIntPtr)num21)].State;
}
state.UpdateChar();
}
else
{
state = this._optimum[(int)((UIntPtr)num21)].State;
}
if (num21 == num19 - 1u)
{
if (this._optimum[(int)((UIntPtr)num19)].IsShortRep())
{
state.UpdateShortRep();
}
else
{
state.UpdateChar();
}
}
else
{
uint num22;
if (this._optimum[(int)((UIntPtr)num19)].Prev1IsChar && this._optimum[(int)((UIntPtr)num19)].Prev2)
{
num21 = this._optimum[(int)((UIntPtr)num19)].PosPrev2;
num22 = this._optimum[(int)((UIntPtr)num19)].BackPrev2;
state.UpdateRep();
}
else
{
num22 = this._optimum[(int)((UIntPtr)num19)].BackPrev;
if (num22 < 4u)
{
state.UpdateRep();
}
else
{
state.UpdateMatch();
}
}
Encoder.Optimal optimal3 = this._optimum[(int)((UIntPtr)num21)];
if (num22 < 4u)
{
if (num22 == 0u)
{
this.reps[0] = optimal3.Backs0;
this.reps[1] = optimal3.Backs1;
this.reps[2] = optimal3.Backs2;
this.reps[3] = optimal3.Backs3;
}
else if (num22 == 1u)
{
this.reps[0] = optimal3.Backs1;
this.reps[1] = optimal3.Backs0;
this.reps[2] = optimal3.Backs2;
this.reps[3] = optimal3.Backs3;
}
else if (num22 == 2u)
{
this.reps[0] = optimal3.Backs2;
this.reps[1] = optimal3.Backs0;
this.reps[2] = optimal3.Backs1;
this.reps[3] = optimal3.Backs3;
}
else
{
this.reps[0] = optimal3.Backs3;
this.reps[1] = optimal3.Backs0;
this.reps[2] = optimal3.Backs1;
this.reps[3] = optimal3.Backs2;
}
}
else
{
this.reps[0] = num22 - 4u;
this.reps[1] = optimal3.Backs0;
this.reps[2] = optimal3.Backs1;
this.reps[3] = optimal3.Backs2;
}
}
this._optimum[(int)((UIntPtr)num19)].State = state;
this._optimum[(int)((UIntPtr)num19)].Backs0 = this.reps[0];
this._optimum[(int)((UIntPtr)num19)].Backs1 = this.reps[1];
this._optimum[(int)((UIntPtr)num19)].Backs2 = this.reps[2];
this._optimum[(int)((UIntPtr)num19)].Backs3 = this.reps[3];
uint price = this._optimum[(int)((UIntPtr)num19)].Price;
indexByte = this._matchFinder.GetIndexByte(-1);
indexByte2 = this._matchFinder.GetIndexByte((int)(0u - this.reps[0] - 1u - 1u));
num6 = (position & this._posStateMask);
uint num23 = price + this._isMatch[(int)((UIntPtr)((state.Index << 4) + num6))].GetPrice0() + this._literalEncoder.GetSubCoder(position, this._matchFinder.GetIndexByte(-2)).GetPrice(!state.IsCharState(), indexByte2, indexByte);
Encoder.Optimal optimal4 = this._optimum[(int)((UIntPtr)(num19 + 1u))];
bool flag = false;
if (num23 < optimal4.Price)
{
optimal4.Price = num23;
optimal4.PosPrev = num19;
optimal4.MakeAsChar();
flag = true;
}
num7 = price + this._isMatch[(int)((UIntPtr)((state.Index << 4) + num6))].GetPrice1();
num8 = num7 + this._isRep[(int)((UIntPtr)state.Index)].GetPrice1();
if (indexByte2 == indexByte && (optimal4.PosPrev >= num19 || optimal4.BackPrev != 0u))
{
uint num24 = num8 + this.GetRepLen1Price(state, num6);
if (num24 <= optimal4.Price)
{
optimal4.Price = num24;
optimal4.PosPrev = num19;
optimal4.MakeAsShortRep();
flag = true;
}
}
uint num25 = this._matchFinder.GetNumAvailableBytes() + 1u;
num25 = Math.Min(4095u - num19, num25);
num2 = num25;
if (num2 >= 2u)
{
if (num2 > this._numFastBytes)
{
num2 = this._numFastBytes;
}
if (!flag && indexByte2 != indexByte)
{
uint limit = Math.Min(num25 - 1u, this._numFastBytes);
uint matchLen = this._matchFinder.GetMatchLen(0, this.reps[0], limit);
if (matchLen >= 2u)
{
Base.State state2 = state;
state2.UpdateChar();
uint num26 = position + 1u & this._posStateMask;
uint num27 = num23 + this._isMatch[(int)((UIntPtr)((state2.Index << 4) + num26))].GetPrice1() + this._isRep[(int)((UIntPtr)state2.Index)].GetPrice1();
uint num28 = num19 + 1u + matchLen;
while (num10 < num28)
{
this._optimum[(int)((UIntPtr)(num10 += 1u))].Price = 268435455u;
}
uint num29 = num27 + this.GetRepPrice(0u, matchLen, state2, num26);
Encoder.Optimal optimal5 = this._optimum[(int)((UIntPtr)num28)];
if (num29 < optimal5.Price)
{
optimal5.Price = num29;
optimal5.PosPrev = num19 + 1u;
optimal5.BackPrev = 0u;
optimal5.Prev1IsChar = true;
optimal5.Prev2 = false;
}
}
}
uint num30 = 2u;
for (uint num31 = 0u; num31 < 4u; num31 += 1u)
{
uint num32 = this._matchFinder.GetMatchLen(-1, this.reps[(int)((UIntPtr)num31)], num2);
if (num32 >= 2u)
{
uint num33 = num32;
do
{
while (num10 < num19 + num32)
{
this._optimum[(int)((UIntPtr)(num10 += 1u))].Price = 268435455u;
}
uint num34 = num8 + this.GetRepPrice(num31, num32, state, num6);
Encoder.Optimal optimal6 = this._optimum[(int)((UIntPtr)(num19 + num32))];
if (num34 < optimal6.Price)
{
optimal6.Price = num34;
optimal6.PosPrev = num19;
optimal6.BackPrev = num31;
optimal6.Prev1IsChar = false;
}
}
while ((num32 -= 1u) >= 2u);
num32 = num33;
if (num31 == 0u)
{
num30 = num32 + 1u;
}
if (num32 < num25)
{
uint limit2 = Math.Min(num25 - 1u - num32, this._numFastBytes);
uint matchLen2 = this._matchFinder.GetMatchLen((int)num32, this.reps[(int)((UIntPtr)num31)], limit2);
if (matchLen2 >= 2u)
{
Base.State state3 = state;
state3.UpdateRep();
uint num35 = position + num32 & this._posStateMask;
uint num36 = num8 + this.GetRepPrice(num31, num32, state, num6) + this._isMatch[(int)((UIntPtr)((state3.Index << 4) + num35))].GetPrice0() + this._literalEncoder.GetSubCoder(position + num32, this._matchFinder.GetIndexByte((int)(num32 - 1u - 1u))).GetPrice(true, this._matchFinder.GetIndexByte((int)(num32 - 1u - (this.reps[(int)((UIntPtr)num31)] + 1u))), this._matchFinder.GetIndexByte((int)(num32 - 1u)));
state3.UpdateChar();
num35 = (position + num32 + 1u & this._posStateMask);
uint num37 = num36 + this._isMatch[(int)((UIntPtr)((state3.Index << 4) + num35))].GetPrice1();
uint num38 = num37 + this._isRep[(int)((UIntPtr)state3.Index)].GetPrice1();
uint num39 = num32 + 1u + matchLen2;
while (num10 < num19 + num39)
{
this._optimum[(int)((UIntPtr)(num10 += 1u))].Price = 268435455u;
}
uint num40 = num38 + this.GetRepPrice(0u, matchLen2, state3, num35);
Encoder.Optimal optimal7 = this._optimum[(int)((UIntPtr)(num19 + num39))];
if (num40 < optimal7.Price)
{
optimal7.Price = num40;
optimal7.PosPrev = num19 + num32 + 1u;
optimal7.BackPrev = 0u;
optimal7.Prev1IsChar = true;
optimal7.Prev2 = true;
optimal7.PosPrev2 = num19;
optimal7.BackPrev2 = num31;
}
}
}
}
}
if (num20 > num2)
{
num20 = num2;
num = 0u;
while (num20 > this._matchDistances[(int)((UIntPtr)num)])
{
num += 2u;
}
this._matchDistances[(int)((UIntPtr)num)] = num20;
num += 2u;
}
if (num20 >= num30)
{
num15 = num7 + this._isRep[(int)((UIntPtr)state.Index)].GetPrice0();
while (num10 < num19 + num20)
{
this._optimum[(int)((UIntPtr)(num10 += 1u))].Price = 268435455u;
}
uint num41 = 0u;
while (num30 > this._matchDistances[(int)((UIntPtr)num41)])
{
num41 += 2u;
}
uint num42 = num30;
while (true)
{
uint num43 = this._matchDistances[(int)((UIntPtr)(num41 + 1u))];
uint num44 = num15 + this.GetPosLenPrice(num43, num42, num6);
Encoder.Optimal optimal8 = this._optimum[(int)((UIntPtr)(num19 + num42))];
if (num44 < optimal8.Price)
{
optimal8.Price = num44;
optimal8.PosPrev = num19;
optimal8.BackPrev = num43 + 4u;
optimal8.Prev1IsChar = false;
}
if (num42 == this._matchDistances[(int)((UIntPtr)num41)])
{
if (num42 < num25)
{
uint limit3 = Math.Min(num25 - 1u - num42, this._numFastBytes);
uint matchLen3 = this._matchFinder.GetMatchLen((int)num42, num43, limit3);
if (matchLen3 >= 2u)
{
Base.State state4 = state;
state4.UpdateMatch();
uint num45 = position + num42 & this._posStateMask;
uint num46 = num44 + this._isMatch[(int)((UIntPtr)((state4.Index << 4) + num45))].GetPrice0() + this._literalEncoder.GetSubCoder(position + num42, this._matchFinder.GetIndexByte((int)(num42 - 1u - 1u))).GetPrice(true, this._matchFinder.GetIndexByte((int)(num42 - (num43 + 1u) - 1u)), this._matchFinder.GetIndexByte((int)(num42 - 1u)));
state4.UpdateChar();
num45 = (position + num42 + 1u & this._posStateMask);
uint num47 = num46 + this._isMatch[(int)((UIntPtr)((state4.Index << 4) + num45))].GetPrice1();
uint num48 = num47 + this._isRep[(int)((UIntPtr)state4.Index)].GetPrice1();
uint num49 = num42 + 1u + matchLen3;
while (num10 < num19 + num49)
{
this._optimum[(int)((UIntPtr)(num10 += 1u))].Price = 268435455u;
}
num44 = num48 + this.GetRepPrice(0u, matchLen3, state4, num45);
optimal8 = this._optimum[(int)((UIntPtr)(num19 + num49))];
if (num44 < optimal8.Price)
{
optimal8.Price = num44;
optimal8.PosPrev = num19 + num42 + 1u;
optimal8.BackPrev = 0u;
optimal8.Prev1IsChar = true;
optimal8.Prev2 = true;
optimal8.PosPrev2 = num19;
optimal8.BackPrev2 = num43 + 4u;
}
}
}
num41 += 2u;
if (num41 == num)
{
break;
}
}
num42 += 1u;
}
}
}
}
return this.Backward(out backRes, num19);
Block_26:
this._numDistancePairs = num;
this._longestMatchLength = num20;
this._longestMatchWasFound = true;
return this.Backward(out backRes, num19);
}
private bool ChangePair(uint smallDist, uint bigDist)
{
return smallDist < 33554432u && bigDist >= smallDist << 7;
}
private void WriteEndMarker(uint posState)
{
if (!this._writeEndMark)
{
return;
}
this._isMatch[(int)((UIntPtr)((this._state.Index << 4) + posState))].Encode(this._rangeEncoder, 1u);
this._isRep[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, 0u);
this._state.UpdateMatch();
uint num = 2u;
this._lenEncoder.Encode(this._rangeEncoder, num - 2u, posState);
uint symbol = 63u;
uint lenToPosState = Base.GetLenToPosState(num);
this._posSlotEncoder[(int)((UIntPtr)lenToPosState)].Encode(this._rangeEncoder, symbol);
int num2 = 30;
uint num3 = (1u << num2) - 1u;
this._rangeEncoder.EncodeDirectBits(num3 >> 4, num2 - 4);
this._posAlignEncoder.ReverseEncode(this._rangeEncoder, num3 & 15u);
}
private void Flush(uint nowPos)
{
this.ReleaseMFStream();
this.WriteEndMarker(nowPos & this._posStateMask);
this._rangeEncoder.FlushData();
this._rangeEncoder.FlushStream();
}
public void CodeOneBlock(out long inSize, out long outSize, out bool finished)
{
inSize = 0L;
outSize = 0L;
finished = true;
if (this._inStream != null)
{
this._matchFinder.SetStream(this._inStream);
this._matchFinder.Init();
this._needReleaseMFStream = true;
this._inStream = null;
if (this._trainSize > 0u)
{
this._matchFinder.Skip(this._trainSize);
}
}
if (this._finished)
{
return;
}
this._finished = true;
long num = this.nowPos64;
if (this.nowPos64 == 0L)
{
if (this._matchFinder.GetNumAvailableBytes() == 0u)
{
this.Flush((uint)this.nowPos64);
return;
}
uint num2;
uint num3;
this.ReadMatchDistances(out num2, out num3);
uint num4 = (uint)this.nowPos64 & this._posStateMask;
this._isMatch[(int)((UIntPtr)((this._state.Index << 4) + num4))].Encode(this._rangeEncoder, 0u);
this._state.UpdateChar();
byte indexByte = this._matchFinder.GetIndexByte((int)(0u - this._additionalOffset));
this._literalEncoder.GetSubCoder((uint)this.nowPos64, this._previousByte).Encode(this._rangeEncoder, indexByte);
this._previousByte = indexByte;
this._additionalOffset -= 1u;
this.nowPos64 += 1L;
}
if (this._matchFinder.GetNumAvailableBytes() == 0u)
{
this.Flush((uint)this.nowPos64);
return;
}
while (true)
{
uint num5;
uint optimum = this.GetOptimum((uint)this.nowPos64, out num5);
uint num6 = (uint)this.nowPos64 & this._posStateMask;
uint num7 = (this._state.Index << 4) + num6;
if (optimum == 1u && num5 == 4294967295u)
{
this._isMatch[(int)((UIntPtr)num7)].Encode(this._rangeEncoder, 0u);
byte indexByte2 = this._matchFinder.GetIndexByte((int)(0u - this._additionalOffset));
Encoder.LiteralEncoder.Encoder2 subCoder = this._literalEncoder.GetSubCoder((uint)this.nowPos64, this._previousByte);
if (!this._state.IsCharState())
{
byte indexByte3 = this._matchFinder.GetIndexByte((int)(0u - this._repDistances[0] - 1u - this._additionalOffset));
subCoder.EncodeMatched(this._rangeEncoder, indexByte3, indexByte2);
}
else
{
subCoder.Encode(this._rangeEncoder, indexByte2);
}
this._previousByte = indexByte2;
this._state.UpdateChar();
}
else
{
this._isMatch[(int)((UIntPtr)num7)].Encode(this._rangeEncoder, 1u);
if (num5 < 4u)
{
this._isRep[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, 1u);
if (num5 == 0u)
{
this._isRepG0[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, 0u);
if (optimum == 1u)
{
this._isRep0Long[(int)((UIntPtr)num7)].Encode(this._rangeEncoder, 0u);
}
else
{
this._isRep0Long[(int)((UIntPtr)num7)].Encode(this._rangeEncoder, 1u);
}
}
else
{
this._isRepG0[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, 1u);
if (num5 == 1u)
{
this._isRepG1[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, 0u);
}
else
{
this._isRepG1[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, 1u);
this._isRepG2[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, num5 - 2u);
}
}
if (optimum == 1u)
{
this._state.UpdateShortRep();
}
else
{
this._repMatchLenEncoder.Encode(this._rangeEncoder, optimum - 2u, num6);
this._state.UpdateRep();
}
uint num8 = this._repDistances[(int)((UIntPtr)num5)];
if (num5 != 0u)
{
for (uint num9 = num5; num9 >= 1u; num9 -= 1u)
{
this._repDistances[(int)((UIntPtr)num9)] = this._repDistances[(int)((UIntPtr)(num9 - 1u))];
}
this._repDistances[0] = num8;
}
}
else
{
this._isRep[(int)((UIntPtr)this._state.Index)].Encode(this._rangeEncoder, 0u);
this._state.UpdateMatch();
this._lenEncoder.Encode(this._rangeEncoder, optimum - 2u, num6);
num5 -= 4u;
uint posSlot = Encoder.GetPosSlot(num5);
uint lenToPosState = Base.GetLenToPosState(optimum);
this._posSlotEncoder[(int)((UIntPtr)lenToPosState)].Encode(this._rangeEncoder, posSlot);
if (posSlot >= 4u)
{
int num10 = (int)((posSlot >> 1) - 1u);
uint num11 = (2u | (posSlot & 1u)) << num10;
uint num12 = num5 - num11;
if (posSlot < 14u)
{
BitTreeEncoder.ReverseEncode(this._posEncoders, num11 - posSlot - 1u, this._rangeEncoder, num10, num12);
}
else
{
this._rangeEncoder.EncodeDirectBits(num12 >> 4, num10 - 4);
this._posAlignEncoder.ReverseEncode(this._rangeEncoder, num12 & 15u);
this._alignPriceCount += 1u;
}
}
uint num13 = num5;
for (uint num14 = 3u; num14 >= 1u; num14 -= 1u)
{
this._repDistances[(int)((UIntPtr)num14)] = this._repDistances[(int)((UIntPtr)(num14 - 1u))];
}
this._repDistances[0] = num13;
this._matchPriceCount += 1u;
}
this._previousByte = this._matchFinder.GetIndexByte((int)(optimum - 1u - this._additionalOffset));
}
this._additionalOffset -= optimum;
this.nowPos64 += (long)((ulong)optimum);
if (this._additionalOffset == 0u)
{
if (this._matchPriceCount >= 128u)
{
this.FillDistancesPrices();
}
if (this._alignPriceCount >= 16u)
{
this.FillAlignPrices();
}
inSize = this.nowPos64;
outSize = this._rangeEncoder.GetProcessedSizeAdd();
if (this._matchFinder.GetNumAvailableBytes() == 0u)
{
break;
}
if (this.nowPos64 - num >= 4096L)
{
goto Block_24;
}
}
}
this.Flush((uint)this.nowPos64);
return;
Block_24:
this._finished = false;
finished = false;
}
private void ReleaseMFStream()
{
if (this._matchFinder != null && this._needReleaseMFStream)
{
this._matchFinder.ReleaseStream();
this._needReleaseMFStream = false;
}
}
private void SetOutStream(Stream outStream)
{
this._rangeEncoder.SetStream(outStream);
}
private void ReleaseOutStream()
{
this._rangeEncoder.ReleaseStream();
}
private void ReleaseStreams()
{
this.ReleaseMFStream();
this.ReleaseOutStream();
}
private void SetStreams(Stream inStream, Stream outStream, long inSize, long outSize)
{
this._inStream = inStream;
this._finished = false;
this.Create();
this.SetOutStream(outStream);
this.Init();
this.FillDistancesPrices();
this.FillAlignPrices();
this._lenEncoder.SetTableSize(this._numFastBytes + 1u - 2u);
this._lenEncoder.UpdateTables(1u << this._posStateBits);
this._repMatchLenEncoder.SetTableSize(this._numFastBytes + 1u - 2u);
this._repMatchLenEncoder.UpdateTables(1u << this._posStateBits);
this.nowPos64 = 0L;
}
public void Code(Stream inStream, Stream outStream, long inSize, long outSize, ICodeProgress progress)
{
this._needReleaseMFStream = false;
try
{
this.SetStreams(inStream, outStream, inSize, outSize);
while (true)
{
long inSize2;
long outSize2;
bool flag;
this.CodeOneBlock(out inSize2, out outSize2, out flag);
if (flag)
{
break;
}
if (progress != null)
{
progress.SetProgress(inSize2, outSize2);
}
}
}
finally
{
this.ReleaseStreams();
}
}
public void WriteCoderProperties(Stream outStream)
{
this.properties[0] = (byte)((this._posStateBits * 5 + this._numLiteralPosStateBits) * 9 + this._numLiteralContextBits);
for (int i = 0; i < 4; i++)
{
this.properties[1 + i] = (byte)(this._dictionarySize >> 8 * i & 255u);
}
outStream.Write(this.properties, 0, 5);
}
private void FillDistancesPrices()
{
for (uint num = 4u; num < 128u; num += 1u)
{
uint posSlot = Encoder.GetPosSlot(num);
int num2 = (int)((posSlot >> 1) - 1u);
uint num3 = (2u | (posSlot & 1u)) << num2;
this.tempPrices[(int)((UIntPtr)num)] = BitTreeEncoder.ReverseGetPrice(this._posEncoders, num3 - posSlot - 1u, num2, num - num3);
}
for (uint num4 = 0u; num4 < 4u; num4 += 1u)
{
BitTreeEncoder bitTreeEncoder = this._posSlotEncoder[(int)((UIntPtr)num4)];
uint num5 = num4 << 6;
for (uint num6 = 0u; num6 < this._distTableSize; num6 += 1u)
{
this._posSlotPrices[(int)((UIntPtr)(num5 + num6))] = bitTreeEncoder.GetPrice(num6);
}
for (uint num6 = 14u; num6 < this._distTableSize; num6 += 1u)
{
this._posSlotPrices[(int)((UIntPtr)(num5 + num6))] += (num6 >> 1) - 1u - 4u << 6;
}
uint num7 = num4 * 128u;
uint num8;
for (num8 = 0u; num8 < 4u; num8 += 1u)
{
this._distancesPrices[(int)((UIntPtr)(num7 + num8))] = this._posSlotPrices[(int)((UIntPtr)(num5 + num8))];
}
while (num8 < 128u)
{
this._distancesPrices[(int)((UIntPtr)(num7 + num8))] = this._posSlotPrices[(int)((UIntPtr)(num5 + Encoder.GetPosSlot(num8)))] + this.tempPrices[(int)((UIntPtr)num8)];
num8 += 1u;
}
}
this._matchPriceCount = 0u;
}
private void FillAlignPrices()
{
for (uint num = 0u; num < 16u; num += 1u)
{
this._alignPrices[(int)((UIntPtr)num)] = this._posAlignEncoder.ReverseGetPrice(num);
}
this._alignPriceCount = 0u;
}
private static int FindMatchFinder(string s)
{
for (int i = 0; i < Encoder.kMatchFinderIDs.Length; i++)
{
if (s == Encoder.kMatchFinderIDs[i])
{
return i;
}
}
return -1;
}
public void SetCoderProperties(CoderPropID[] propIDs, object[] properties)
{
uint num = 0u;
while ((ulong)num < (ulong)((long)properties.Length))
{
object obj = properties[(int)((UIntPtr)num)];
switch (propIDs[(int)((UIntPtr)num)])
{
case CoderPropID.DictionarySize:
{
if (!(obj is int))
{
throw new InvalidParamException();
}
int num2 = (int)obj;
if ((long)num2 < 1L || (long)num2 > 1073741824L)
{
throw new InvalidParamException();
}
this._dictionarySize = (uint)num2;
int num3 = 0;
while ((long)num3 < 30L)
{
if ((long)num2 <= (long)(1uL << (num3 & 31)))
{
break;
}
num3++;
}
this._distTableSize = (uint)(num3 * 2);
break;
}
case CoderPropID.UsedMemorySize:
case CoderPropID.Order:
case CoderPropID.BlockSize:
case CoderPropID.MatchFinderCycles:
case CoderPropID.NumPasses:
case CoderPropID.NumThreads:
goto IL_270;
case CoderPropID.PosStateBits:
{
if (!(obj is int))
{
throw new InvalidParamException();
}
int num4 = (int)obj;
if (num4 < 0 || (long)num4 > 4L)
{
throw new InvalidParamException();
}
this._posStateBits = num4;
this._posStateMask = (1u << this._posStateBits) - 1u;
break;
}
case CoderPropID.LitContextBits:
{
if (!(obj is int))
{
throw new InvalidParamException();
}
int num5 = (int)obj;
if (num5 < 0 || (long)num5 > 8L)
{
throw new InvalidParamException();
}
this._numLiteralContextBits = num5;
break;
}
case CoderPropID.LitPosBits:
{
if (!(obj is int))
{
throw new InvalidParamException();
}
int num6 = (int)obj;
if (num6 < 0 || (long)num6 > 4L)
{
throw new InvalidParamException();
}
this._numLiteralPosStateBits = num6;
break;
}
case CoderPropID.NumFastBytes:
{
if (!(obj is int))
{
throw new InvalidParamException();
}
int num7 = (int)obj;
if (num7 < 5 || (long)num7 > 273L)
{
throw new InvalidParamException();
}
this._numFastBytes = (uint)num7;
break;
}
case CoderPropID.MatchFinder:
{
if (!(obj is string))
{
throw new InvalidParamException();
}
Encoder.EMatchFinderType matchFinderType = this._matchFinderType;
int num8 = Encoder.FindMatchFinder(((string)obj).ToUpper());
if (num8 < 0)
{
throw new InvalidParamException();
}
this._matchFinderType = (Encoder.EMatchFinderType)num8;
if (this._matchFinder != null && matchFinderType != this._matchFinderType)
{
this._dictionarySizePrev = 4294967295u;
this._matchFinder = null;
}
break;
}
case CoderPropID.Algorithm:
break;
case CoderPropID.EndMarker:
if (!(obj is bool))
{
throw new InvalidParamException();
}
this.SetWriteEndMarkerMode((bool)obj);
break;
default:
goto IL_270;
}
num += 1u;
continue;
IL_270:
throw new InvalidParamException();
}
}
public void SetTrainSize(uint trainSize)
{
this._trainSize = trainSize;
}
}
}
| |
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.field01.field01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.field01.field01;
// <Title> Compound operator in readonly field.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
char c = (char)2;
d.field *= c;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.AssgReadonly, e.Message))
return 0;
}
return 1;
}
public readonly long field = 10;
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.field02.field02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.field02.field02;
// <Title> Compound operator non-delegate += delegate.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
d.field += new MyDel(Method);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "+=", "int", "Test.MyDel"))
return 0;
}
return 1;
}
public int field = 0;
public static int Method(int i)
{
return i;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property01.property01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property01.property01;
// <Title> Compound operator in readonly property.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
byte b = 10;
d.Field += b;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.AssgReadonlyProp, e.Message, "Test.Field"))
return 0;
}
return 1;
}
public string Field
{
get
{
return "A";
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property02.property02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property02.property02;
// <Title> Compound operator in readonly property.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class TestClass
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
byte b = 10;
d.Field += b;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "Test.Field"))
return 0;
}
return 1;
}
}
public class Test
{
public string Field
{
get
{
return "A";
}
private set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property03.property03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property03.property03;
// <Title> Compound operator in readonly property.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
byte b = 10;
d.Field += b;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.PropertyLacksGet, e.Message, "Test.Field"))
return 0;
}
return 1;
}
public string Field
{
set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property04.property04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.property04.property04;
// <Title> Compound operator: property += delegate.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
d.Field += new MyDel(t.Method); // No exception: string + delegate
try
{
d.FieldInt -= new MyDel(t.Method);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "-=", "int", "Test.MyDel"))
return 0;
}
return 1;
}
public string Field
{
get
{
return "A";
}
set
{
}
}
public int FieldInt
{
get
{
return 10;
}
set
{
}
}
public int Method(int i)
{
return i;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer01.indexer01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer01.indexer01;
// <Title> Compound operator in readonly indexer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
byte b = 10;
d[10] += b;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.AssgReadonlyProp, e.Message, "Test.this[long]"))
return 0;
}
return 1;
}
public string this[long s]
{
get
{
return "A";
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer02.indexer02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer02.indexer02;
// <Title> Compound operator in readonly indexer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class TestClass
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
byte b = 10;
d[10] += b;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "Test.this[long]"))
return 0;
}
return 1;
}
}
public class Test
{
public string this[long s]
{
get
{
return "A";
}
private set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer03.indexer03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer03.indexer03;
// <Title> Compound operator in readonly indexer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
byte b = 10;
d[10] += b;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.PropertyLacksGet, e.Message, "Test.this[long]"))
return 0;
}
return 1;
}
public string this[long s]
{
set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer04.indexer04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.negative.indexer04.indexer04;
// <Title> Compound operator indexer += delegate.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
try
{
d[10] += new MyDel(delegate (int x)
{
return x;
}
);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "+=", "int", "Test.MyDel"))
return 0;
}
return 1;
}
public int this[long s]
{
get
{
return 10;
}
set
{
}
}
}
//</Code>
}
| |
// 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.Contracts;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SecurityUtils = System.ServiceModel.Security.SecurityUtils;
namespace System.ServiceModel.Channels
{
internal class HttpChannelFactory<TChannel>
: TransportChannelFactory<TChannel>,
IHttpTransportFactorySettings
{
private static CacheControlHeaderValue s_requestCacheHeader = new CacheControlHeaderValue { NoCache = true, MaxAge = new TimeSpan(0) };
protected readonly ClientWebSocketFactory _clientWebSocketFactory;
private bool _allowCookies;
private AuthenticationSchemes _authenticationScheme;
private HttpCookieContainerManager _httpCookieContainerManager;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile MruCache<Uri, Uri> _credentialCacheUriPrefixCache;
private volatile MruCache<string, string> _credentialHashCache;
private volatile MruCache<string, HttpClient> _httpClientCache;
private int _maxBufferSize;
private IWebProxy _proxy;
private WebProxyFactory _proxyFactory;
private SecurityCredentialsManager _channelCredentials;
private SecurityTokenManager _securityTokenManager;
private TransferMode _transferMode;
private ISecurityCapabilities _securityCapabilities;
private Func<HttpClientHandler, HttpMessageHandler> _httpMessageHandlerFactory;
private WebSocketTransportSettings _webSocketSettings;
private Lazy<string> _webSocketSoapContentType;
private SHA512 _hashAlgorithm;
private bool _keepAliveEnabled;
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
: base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
{
// validate setting interactions
if (bindingElement.TransferMode == TransferMode.Buffered)
{
if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
SR.MaxReceivedMessageSizeMustBeInIntegerRange));
}
if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
}
}
else
{
if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
}
}
if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.HttpAuthDoesNotSupportRequestStreaming);
}
_allowCookies = bindingElement.AllowCookies;
if (_allowCookies)
{
_httpCookieContainerManager = new HttpCookieContainerManager();
}
if (!bindingElement.AuthenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
bindingElement.AuthenticationScheme));
}
_authenticationScheme = bindingElement.AuthenticationScheme;
_maxBufferSize = bindingElement.MaxBufferSize;
_transferMode = bindingElement.TransferMode;
_keepAliveEnabled = bindingElement.KeepAliveEnabled;
if (bindingElement.ProxyAddress != null)
{
if (bindingElement.UseDefaultWebProxy)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress));
}
if (bindingElement.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous)
{
_proxy = new WebProxy(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal);
}
else
{
_proxy = null;
_proxyFactory =
new WebProxyFactory(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal,
bindingElement.ProxyAuthenticationScheme);
}
}
else if (!bindingElement.UseDefaultWebProxy)
{
_proxy = new WebProxy();
}
_channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
_securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
_httpMessageHandlerFactory = context.BindingParameters.Find<Func<HttpClientHandler, HttpMessageHandler>>();
_webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
_clientWebSocketFactory = ClientWebSocketFactory.GetFactory();
_webSocketSoapContentType = new Lazy<string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
}
public bool AllowCookies
{
get
{
return _allowCookies;
}
}
public AuthenticationSchemes AuthenticationScheme
{
get
{
return _authenticationScheme;
}
}
public virtual bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public SecurityTokenManager SecurityTokenManager
{
get
{
return _securityTokenManager;
}
}
public int MaxBufferSize
{
get
{
return _maxBufferSize;
}
}
public TransferMode TransferMode
{
get
{
return _transferMode;
}
}
public override string Scheme
{
get
{
return UriEx.UriSchemeHttp;
}
}
public WebSocketTransportSettings WebSocketSettings
{
get
{
return _webSocketSettings;
}
}
internal string WebSocketSoapContentType
{
get
{
return _webSocketSoapContentType.Value;
}
}
private HashAlgorithm HashAlgorithm
{
[SecurityCritical]
get
{
if (_hashAlgorithm == null)
{
_hashAlgorithm = SHA512.Create();
}
else
{
_hashAlgorithm.Initialize();
}
return _hashAlgorithm;
}
}
protected ClientWebSocketFactory ClientWebSocketFactory
{
get
{
return _clientWebSocketFactory;
}
}
private bool AuthenticationSchemeMayRequireResend()
{
return AuthenticationScheme != AuthenticationSchemes.Anonymous;
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)_securityCapabilities;
}
if (typeof(T) == typeof(IHttpCookieContainerManager))
{
return (T)(object)GetHttpCookieContainerManager();
}
return base.GetProperty<T>();
}
private HttpCookieContainerManager GetHttpCookieContainerManager()
{
return _httpCookieContainerManager;
}
private Uri GetCredentialCacheUriPrefix(Uri via)
{
Uri result;
if (_credentialCacheUriPrefixCache == null)
{
lock (ThisLock)
{
if (_credentialCacheUriPrefixCache == null)
{
_credentialCacheUriPrefixCache = new MruCache<Uri, Uri>(10);
}
}
}
lock (_credentialCacheUriPrefixCache)
{
if (!_credentialCacheUriPrefixCache.TryGetValue(via, out result))
{
result = new UriBuilder(via.Scheme, via.Host, via.Port).Uri;
_credentialCacheUriPrefixCache.Add(via, result);
}
}
return result;
}
internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via,
SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider,
SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(_authenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken);
if (_httpClientCache == null)
{
lock (ThisLock)
{
if (_httpClientCache == null)
{
_httpClientCache = new MruCache<string, HttpClient>(10);
}
}
}
HttpClient httpClient;
string connectionGroupName = GetConnectionGroupName(credential, authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value,
clientCertificateToken);
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
connectionGroupName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName,
remoteCertificateIdentity.Certificates[0].Thumbprint);
}
connectionGroupName = connectionGroupName ?? string.Empty;
bool foundHttpClient;
lock (_httpClientCache)
{
foundHttpClient = _httpClientCache.TryGetValue(connectionGroupName, out httpClient);
}
if (!foundHttpClient)
{
var clientHandler = GetHttpClientHandler(to, clientCertificateToken);
clientHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
if (clientHandler.SupportsProxy)
{
if (_proxy != null)
{
clientHandler.Proxy = _proxy;
clientHandler.UseProxy = true;
}
else if (_proxyFactory != null)
{
clientHandler.Proxy = await _proxyFactory.CreateWebProxyAsync(authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value, proxyTokenProvider, cancellationToken);
clientHandler.UseProxy = true;
}
}
clientHandler.UseCookies = _allowCookies;
if (_allowCookies)
{
clientHandler.CookieContainer = _httpCookieContainerManager.CookieContainer;
}
clientHandler.PreAuthenticate = true;
clientHandler.UseDefaultCredentials = false;
if (credential == CredentialCache.DefaultCredentials || credential == null)
{
clientHandler.UseDefaultCredentials = true;
}
else
{
CredentialCache credentials = new CredentialCache();
credentials.Add(GetCredentialCacheUriPrefix(via),
AuthenticationSchemesHelper.ToString(_authenticationScheme), credential);
clientHandler.Credentials = credentials;
}
HttpMessageHandler handler = clientHandler;
if(_httpMessageHandlerFactory!= null)
{
handler = _httpMessageHandlerFactory(clientHandler);
}
httpClient = new HttpClient(handler);
if(!_keepAliveEnabled)
httpClient.DefaultRequestHeaders.ConnectionClose = true;
#if !FEATURE_NETNATIVE // Expect continue not correctly supported on UAP
if (IsExpectContinueHeaderRequired)
{
httpClient.DefaultRequestHeaders.ExpectContinue = true;
}
#endif
// We provide our own CancellationToken for each request. Setting HttpClient.Timeout to -1
// prevents a call to CancellationToken.CancelAfter that HttpClient does internally which
// causes TimerQueue contention at high load.
httpClient.Timeout = Timeout.InfiniteTimeSpan;
lock (_httpClientCache)
{
HttpClient tempHttpClient;
if (_httpClientCache.TryGetValue(connectionGroupName, out tempHttpClient))
{
httpClient.Dispose();
httpClient = tempHttpClient;
}
else
{
_httpClientCache.Add(connectionGroupName, httpClient);
}
}
}
return httpClient;
}
internal virtual bool IsExpectContinueHeaderRequired => AuthenticationSchemeMayRequireResend();
internal virtual HttpClientHandler GetHttpClientHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken)
{
return new HttpClientHandler();
}
internal ICredentials GetCredentials()
{
ICredentials creds = null;
if (_authenticationScheme != AuthenticationSchemes.Anonymous)
{
creds = CredentialCache.DefaultCredentials;
ClientCredentials credentials = _channelCredentials as ClientCredentials;
if (credentials != null)
{
switch (_authenticationScheme)
{
case AuthenticationSchemes.Basic:
if (credentials.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("userName");
}
if (credentials.UserName.UserName == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.UserNameCannotBeEmpty);
}
creds = new NetworkCredential(credentials.UserName.UserName, credentials.UserName.Password);
break;
case AuthenticationSchemes.Digest:
if (credentials.HttpDigest.ClientCredential.UserName != string.Empty)
{
creds = credentials.HttpDigest.ClientCredential;
}
break;
case AuthenticationSchemes.Ntlm:
goto case AuthenticationSchemes.Negotiate;
case AuthenticationSchemes.Negotiate:
if (credentials.Windows.ClientCredential.UserName != string.Empty)
{
creds = credentials.Windows.ClientCredential;
}
break;
}
}
}
return creds;
}
internal Exception CreateToMustEqualViaException(Uri to, Uri via)
{
return new ArgumentException(SR.Format(SR.HttpToMustEqualVia, to, via));
}
public override int GetMaxBufferSize()
{
return MaxBufferSize;
}
private SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme,
EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
{
SecurityTokenProvider tokenProvider = null;
switch (authenticationScheme)
{
case AuthenticationSchemes.Anonymous:
break;
case AuthenticationSchemes.Basic:
tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Negotiate:
case AuthenticationSchemes.Ntlm:
tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Digest:
tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
default:
// The setter for this property should prevent this.
throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme");
}
SecurityTokenProviderContainer result;
if (tokenProvider != null)
{
result = new SecurityTokenProviderContainer(tokenProvider);
result.Open(timeout);
}
else
{
result = null;
}
return result;
}
protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (string.Compare(via.Scheme, "ws", StringComparison.OrdinalIgnoreCase) != 0)
{
ValidateScheme(via);
}
if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
if (typeof(TChannel) != typeof(IRequestChannel))
{
remoteAddress = remoteAddress != null && !WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ?
new EndpointAddress(WebSocketHelper.NormalizeHttpSchemeWithWsScheme(remoteAddress.Uri), remoteAddress) :
remoteAddress;
via = !WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeHttpSchemeWithWsScheme(via) : via;
}
return OnCreateChannelCore(remoteAddress, via);
}
protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via)
{
ValidateCreateChannelParameters(remoteAddress, via);
ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpClientRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, remoteAddress, via);
}
}
protected void ValidateWebSocketTransportUsage()
{
Type channelType = typeof(TChannel);
if (channelType == typeof(IRequestChannel) && WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
if (channelType == typeof(IDuplexSessionChannel))
{
if (WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitializeSecurityTokenManager()
{
if (_channelCredentials == null)
{
_channelCredentials = ClientCredentials.CreateDefaultCredentials();
}
_securityTokenManager = _channelCredentials.CreateSecurityTokenManager();
}
protected virtual bool IsSecurityTokenManagerRequired()
{
return _authenticationScheme != AuthenticationSchemes.Anonymous;
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
if (IsSecurityTokenManagerRequired())
{
InitializeSecurityTokenManager();
}
if (AllowCookies &&
!_httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already.
{
_httpCookieContainerManager.CookieContainer = new CookieContainer();
}
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return base.OnCloseAsync(timeout);
}
protected override void OnClosed()
{
base.OnClosed();
if (_httpClientCache != null && !_httpClientCache.IsDisposed)
{
lock (_httpClientCache)
{
_httpClientCache.Dispose();
_httpClientCache = null;
}
}
}
private string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
protected virtual string OnGetConnectionGroupPrefix(SecurityTokenContainer clientCertificateToken)
{
return string.Empty;
}
internal static bool IsWindowsAuth(AuthenticationSchemes authScheme)
{
Contract.Assert(authScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
return authScheme == AuthenticationSchemes.Negotiate ||
authScheme == AuthenticationSchemes.Ntlm;
}
private string GetConnectionGroupName(NetworkCredential credential, AuthenticationLevel authenticationLevel,
TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
{
if (_credentialHashCache == null)
{
lock (ThisLock)
{
if (_credentialHashCache == null)
{
_credentialHashCache = new MruCache<string, string>(5);
}
}
}
string inputString = TransferModeHelper.IsRequestStreamed(TransferMode) ? "streamed" : string.Empty;
if (IsWindowsAuth(_authenticationScheme))
{
inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
inputString = string.Concat(OnGetConnectionGroupPrefix(clientCertificateToken), inputString);
string credentialHash = null;
// we have to lock around each call to TryGetValue since the MruCache modifies the
// contents of it's mruList in a single-threaded manner underneath TryGetValue
if (!string.IsNullOrEmpty(inputString))
{
lock (_credentialHashCache)
{
if (!_credentialHashCache.TryGetValue(inputString, out credentialHash))
{
byte[] inputBytes = new UTF8Encoding().GetBytes(inputString);
byte[] digestBytes = HashAlgorithm.ComputeHash(inputBytes);
credentialHash = Convert.ToBase64String(digestBytes);
_credentialHashCache.Add(inputString, credentialHash);
}
}
}
return credentialHash;
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
Uri httpRequestUri = via;
var requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
if (TransferModeHelper.IsRequestStreamed(TransferMode))
{
requestMessage.Headers.TransferEncodingChunked = true;
}
requestMessage.Headers.CacheControl = s_requestCacheHeader;
return requestMessage;
}
private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message)
{
if (ManualAddressing)
{
Uri toHeader = message.Headers.To;
if (toHeader == null)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.ManualAddressingRequiresAddressedMessages), message);
}
to = new EndpointAddress(toHeader);
if (MessageVersion.Addressing == AddressingVersion.None)
{
via = toHeader;
}
}
// now apply query string property
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
if (!string.IsNullOrEmpty(requestProperty.QueryString))
{
UriBuilder uriBuilder = new UriBuilder(via);
if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal))
{
uriBuilder.Query = requestProperty.QueryString.Substring(1);
}
else
{
uriBuilder.Query = requestProperty.QueryString;
}
via = uriBuilder.Uri;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), AuthenticationScheme, to, via, channelParameters);
if (_proxyFactory != null)
{
proxyTokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), _proxyFactory.AuthenticationScheme, to, via, channelParameters);
}
else
{
proxyTokenProvider = null;
}
}
internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
if (!IsSecurityTokenManagerRequired())
{
tokenProvider = null;
proxyTokenProvider = null;
}
else
{
CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider, out proxyTokenProvider);
}
}
internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme)
{
if (target.Identity == null)
{
return false;
}
return IsWindowsAuth(authenticationScheme);
}
private bool MapIdentity(EndpointAddress target)
{
return MapIdentity(target, AuthenticationScheme);
}
protected class HttpClientRequestChannel : RequestChannel
{
private HttpChannelFactory<IRequestChannel> _factory;
private SecurityTokenProviderContainer _tokenProvider;
private SecurityTokenProviderContainer _proxyTokenProvider;
private ChannelParameterCollection _channelParameters;
public HttpClientRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
_factory = factory;
}
public HttpChannelFactory<IRequestChannel> Factory
{
get { return _factory; }
}
protected ChannelParameterCollection ChannelParameters
{
get
{
return _channelParameters;
}
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
if (State == CommunicationState.Created)
{
lock (ThisLock)
{
if (_channelParameters == null)
{
_channelParameters = new ChannelParameterCollection();
}
}
}
return (T)(object)_channelParameters;
}
return base.GetProperty<T>();
}
private void PrepareOpen()
{
Factory.MapIdentity(RemoteAddress);
}
private void CreateAndOpenTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(RemoteAddress, Via, _channelParameters, timeoutHelper.RemainingTime(), out _tokenProvider, out _proxyTokenProvider);
}
}
private void CloseTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_tokenProvider != null)
{
_tokenProvider.Close(timeoutHelper.RemainingTime());
}
}
private void AbortTokenProviders()
{
if (_tokenProvider != null)
{
_tokenProvider.Abort();
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnOpen(TimeSpan timeout)
{
CommunicationObjectInternal.OnOpen(this, timeout);
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
PrepareOpen();
CreateAndOpenTokenProviders(timeout);
return TaskHelpers.CompletedTask();
}
private void PrepareClose(bool aborting)
{
}
protected override void OnAbort()
{
PrepareClose(true);
AbortTokenProviders();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnClose(TimeSpan timeout)
{
CommunicationObjectInternal.OnClose(this, timeout);
}
protected internal override async Task OnCloseAsync(TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
PrepareClose(false);
CloseTokenProviders(timeoutHelper.RemainingTime());
await WaitForPendingRequestsAsync(timeoutHelper.RemainingTime());
}
protected override IAsyncRequest CreateAsyncRequest(Message message)
{
return new HttpClientChannelAsyncRequest(this);
}
internal virtual Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper)
{
return GetHttpClientAsync(to, via, null, timeoutHelper);
}
protected async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper)
{
SecurityTokenProviderContainer requestTokenProvider;
SecurityTokenProviderContainer requestProxyTokenProvider;
if (ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(to, via, _channelParameters, timeoutHelper.RemainingTime(),
out requestTokenProvider, out requestProxyTokenProvider);
}
else
{
requestTokenProvider = _tokenProvider;
requestProxyTokenProvider = _proxyTokenProvider;
}
try
{
return await Factory.GetHttpClientAsync(to, via, requestTokenProvider, requestProxyTokenProvider, clientCertificateToken, await timeoutHelper.GetCancellationTokenAsync());
}
finally
{
if (ManualAddressing)
{
if (requestTokenProvider != null)
{
requestTokenProvider.Abort();
}
}
}
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
return Factory.GetHttpRequestMessage(via);
}
internal virtual void OnHttpRequestCompleted(HttpRequestMessage request)
{
// empty
}
internal class HttpClientChannelAsyncRequest : IAsyncRequest
{
private static readonly Action<object> s_cancelCts = state =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch (ObjectDisposedException)
{
// ignore
}
};
private HttpClientRequestChannel _channel;
private HttpChannelFactory<IRequestChannel> _factory;
private EndpointAddress _to;
private Uri _via;
private HttpRequestMessage _httpRequestMessage;
private HttpResponseMessage _httpResponseMessage;
private HttpAbortReason _abortReason;
private TimeoutHelper _timeoutHelper;
private int _httpRequestCompleted;
private HttpClient _httpClient;
private readonly CancellationTokenSource _httpSendCts;
public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
{
_channel = channel;
_to = channel.RemoteAddress;
_via = channel.Via;
_factory = channel.Factory;
_httpSendCts = new CancellationTokenSource();
}
public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
{
_timeoutHelper = timeoutHelper;
_factory.ApplyManualAddressing(ref _to, ref _via, message);
_httpClient = await _channel.GetHttpClientAsync(_to, _via, _timeoutHelper);
// The _httpRequestMessage field will be set to null by Cleanup() due to faulting
// or aborting, so use a local copy for exception handling within this method.
HttpRequestMessage httpRequestMessage = _channel.GetHttpRequestMessage(_via);
_httpRequestMessage = httpRequestMessage;
Message request = message;
try
{
if (_channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request or doing correlation,
// we need to abort the request and bail
Cleanup();
_channel.ThrowIfDisposedOrNotOpen();
}
bool suppressEntityBody = PrepareMessageHeaders(request);
if (!suppressEntityBody)
{
httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper);
}
#if FEATURE_NETNATIVE // UAP doesn't support Expect Continue so we do a HEAD request to get authentication done before sending the real request
try
{
// There is a possibility that a HEAD pre-auth request might fail when the actual request
// will succeed. For example, when the web service refuses HEAD requests. We don't want
// to fail the actual request because of some subtlety which causes the HEAD request.
await SendPreauthenticationHeadRequestIfNeeded();
}
catch { /* ignored */ }
#endif
bool success = false;
var timeoutToken = await _timeoutHelper.GetCancellationTokenAsync();
try
{
using (timeoutToken.Register(s_cancelCts, _httpSendCts))
{
_httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _httpSendCts.Token);
}
// As we have the response message and no exceptions have been thrown, the request message has completed it's job.
// Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around
// as we can still query properties once dispose'd.
httpRequestMessage.Dispose();
success = true;
}
catch (HttpRequestException requestException)
{
HttpChannelUtilities.ProcessGetResponseWebException(requestException, httpRequestMessage,
_abortReason);
}
catch (OperationCanceledException)
{
if (timeoutToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpRequestTimedOut, httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutToken and needs to be handled differently.
throw;
}
}
finally
{
if (!success)
{
Abort(_channel);
}
}
}
finally
{
if (!ReferenceEquals(request, message))
{
request.Close();
}
}
}
private void Cleanup()
{
s_cancelCts(_httpSendCts);
if (_httpRequestMessage != null)
{
var httpRequestMessageSnapshot = _httpRequestMessage;
_httpRequestMessage = null;
TryCompleteHttpRequest(httpRequestMessageSnapshot);
httpRequestMessageSnapshot.Dispose();
}
}
public void Abort(RequestChannel channel)
{
Cleanup();
_abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
public async Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
{
try
{
_timeoutHelper = timeoutHelper;
var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory);
var replyMessage = await responseHelper.ParseIncomingResponse(timeoutHelper);
TryCompleteHttpRequest(_httpRequestMessage);
return replyMessage;
}
catch (OperationCanceledException)
{
var cancelToken = _timeoutHelper.GetCancellationToken();
if (cancelToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
}
private bool PrepareMessageHeaders(Message message)
{
string action = message.Headers.Action;
if (action != null)
{
action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action));
}
if (message.Version.Addressing == AddressingVersion.None)
{
message.Headers.Action = null;
message.Headers.To = null;
}
bool suppressEntityBody = message is NullMessage;
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
_httpRequestMessage.Method = new HttpMethod(requestProperty.Method);
// Query string was applied in HttpChannelFactory.ApplyManualAddressing
WebHeaderCollection requestHeaders = requestProperty.Headers;
suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody;
var headerKeys = requestHeaders.AllKeys;
for (int i = 0; i < headerKeys.Length; i++)
{
string name = headerKeys[i];
string value = requestHeaders[name];
if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Accept.TryParseAdd(value);
}
else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ConnectionClose = false;
}
else
{
_httpRequestMessage.Headers.Connection.TryParseAdd(value);
}
}
else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0)
{
if (action == null)
{
action = value;
}
else
{
if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value)));
}
}
}
else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we write to the content
}
else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
{
// Handled by MessageContent
}
else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ExpectContinue = true;
}
else
{
_httpRequestMessage.Headers.Expect.TryParseAdd(value);
}
}
else if (string.Compare(name, "host", StringComparison.OrdinalIgnoreCase) == 0)
{
// this should be controlled through Via
}
else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0)
{
// referrer is proper spelling, but referer is the what is in the protocol.
_httpRequestMessage.Headers.Referrer = new Uri(value);
}
else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.TransferEncodingChunked = true;
}
else
{
_httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value);
}
}
else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Add(name, value);
}
else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0)
{
DateTimeOffset modifiedSinceDate;
if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate))
{
_httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpIfModifiedSinceParseError, value)));
}
}
else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we make the request
}
else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0)
{
throw ExceptionHelper.PlatformNotSupported("proxy-connection");
}
else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0)
{
// specifying a range doesn't make sense in the context of WCF
}
else
{
try
{
_httpRequestMessage.Headers.Add(name, value);
}
catch (Exception addHeaderException)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.CopyHttpHeaderFailed,
name,
value,
HttpChannelUtilities.HttpRequestHeadersTypeName),
addHeaderException));
}
}
}
}
if (action != null)
{
if (message.Version.Envelope == EnvelopeVersion.Soap11)
{
_httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action);
}
else if (message.Version.Envelope == EnvelopeVersion.Soap12)
{
// Handled by MessageContent
}
else if (message.Version.Envelope != EnvelopeVersion.None)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.EnvelopeVersionUnknown,
message.Version.Envelope.ToString())));
}
}
// since we don't get the output stream in send when retVal == true,
// we need to disable chunking for some verbs (DELETE/PUT)
if (suppressEntityBody)
{
_httpRequestMessage.Headers.TransferEncodingChunked = false;
}
return suppressEntityBody;
}
public void OnReleaseRequest()
{
TryCompleteHttpRequest(_httpRequestMessage);
}
private void TryCompleteHttpRequest(HttpRequestMessage request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref _httpRequestCompleted, 1, 0) == 0)
{
_channel.OnHttpRequestCompleted(request);
}
}
private async Task SendPreauthenticationHeadRequestIfNeeded()
{
if (!_factory.AuthenticationSchemeMayRequireResend())
{
return;
}
var requestUri = _httpRequestMessage.RequestUri;
// sends a HEAD request to the specificed requestUri for authentication purposes
Contract.Assert(requestUri != null);
HttpRequestMessage headHttpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Head,
RequestUri = requestUri
};
var cancelToken = await _timeoutHelper.GetCancellationTokenAsync();
await _httpClient.SendAsync(headHttpRequestMessage, cancelToken);
}
}
}
class WebProxyFactory
{
Uri _address;
bool _bypassOnLocal;
AuthenticationSchemes _authenticationScheme;
public WebProxyFactory(Uri address, bool bypassOnLocal, AuthenticationSchemes authenticationScheme)
{
_address = address;
_bypassOnLocal = bypassOnLocal;
if (!authenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(authenticationScheme), SR.Format(SR.HttpRequiresSingleAuthScheme,
authenticationScheme));
}
_authenticationScheme = authenticationScheme;
}
internal AuthenticationSchemes AuthenticationScheme
{
get
{
return _authenticationScheme;
}
}
public async Task<IWebProxy> CreateWebProxyAsync(AuthenticationLevel requestAuthenticationLevel, TokenImpersonationLevel requestImpersonationLevel, SecurityTokenProviderContainer tokenProvider, CancellationToken token)
{
WebProxy result = new WebProxy(_address, _bypassOnLocal);
if (_authenticationScheme != AuthenticationSchemes.Anonymous)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(_authenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, token);
// The impersonation level for target auth is also used for proxy auth (by System.Net). Therefore,
// fail if the level stipulated for proxy auth is more restrictive than that for target auth.
if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevelWrapper.Value, requestImpersonationLevel))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyImpersonationLevelMismatch, impersonationLevelWrapper.Value, requestImpersonationLevel)));
}
// The authentication level for target auth is also used for proxy auth (by System.Net).
// Therefore, fail if proxy auth requires mutual authentication but target auth does not.
if ((authenticationLevelWrapper.Value == AuthenticationLevel.MutualAuthRequired) &&
(requestAuthenticationLevel != AuthenticationLevel.MutualAuthRequired))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyAuthenticationLevelMismatch, authenticationLevelWrapper.Value, requestAuthenticationLevel)));
}
CredentialCache credentials = new CredentialCache();
credentials.Add(_address, AuthenticationSchemesHelper.ToString(_authenticationScheme),
credential);
result.Credentials = credentials;
}
return result;
}
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Collections;
namespace log4net.Core
{
/// <summary>
/// Defines the default set of levels recognized by the system.
/// </summary>
/// <remarks>
/// <para>
/// Each <see cref="LoggingEvent"/> has an associated <see cref="Level"/>.
/// </para>
/// <para>
/// Levels have a numeric <see cref="Level.Value"/> that defines the relative
/// ordering between levels. Two Levels with the same <see cref="Level.Value"/>
/// are deemed to be equivalent.
/// </para>
/// <para>
/// The levels that are recognized by log4net are set for each <see cref="log4net.Repository.ILoggerRepository"/>
/// and each repository can have different levels defined. The levels are stored
/// in the <see cref="log4net.Repository.ILoggerRepository.LevelMap"/> on the repository. Levels are
/// looked up by name from the <see cref="log4net.Repository.ILoggerRepository.LevelMap"/>.
/// </para>
/// <para>
/// When logging at level INFO the actual level used is not <see cref="Level.Info"/> but
/// the value of <c>LoggerRepository.LevelMap["INFO"]</c>. The default value for this is
/// <see cref="Level.Info"/>, but this can be changed by reconfiguring the level map.
/// </para>
/// <para>
/// Each level has a <see cref="DisplayName"/> in addition to its <see cref="Name"/>. The
/// <see cref="DisplayName"/> is the string that is written into the output log. By default
/// the display name is the same as the level name, but this can be used to alias levels
/// or to localize the log output.
/// </para>
/// <para>
/// Some of the predefined levels recognized by the system are:
/// </para>
/// <list type="bullet">
/// <item>
/// <description><see cref="Off"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Fatal"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Error"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Warn"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Info"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Debug"/>.</description>
/// </item>
/// <item>
/// <description><see cref="All"/>.</description>
/// </item>
/// </list>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
#if !NETCF
[Serializable]
#endif
sealed public class Level : IComparable
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="level">Integer value for this level, higher values represent more severe levels.</param>
/// <param name="levelName">The string name of this level.</param>
/// <param name="displayName">The display name for this level. This may be localized or otherwise different from the name</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Level" /> class with
/// the specified level name and value.
/// </para>
/// </remarks>
public Level(int level, string levelName, string displayName)
{
if (levelName == null)
{
throw new ArgumentNullException("levelName");
}
if (displayName == null)
{
throw new ArgumentNullException("displayName");
}
m_levelValue = level;
#if NETSTANDARD1_3
m_levelName = levelName;
#else
m_levelName = string.Intern(levelName);
#endif
m_levelDisplayName = displayName;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="level">Integer value for this level, higher values represent more severe levels.</param>
/// <param name="levelName">The string name of this level.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Level" /> class with
/// the specified level name and value.
/// </para>
/// </remarks>
public Level(int level, string levelName) : this(level, levelName, levelName)
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets the name of this level.
/// </summary>
/// <value>
/// The name of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the name of this level.
/// </para>
/// </remarks>
public string Name
{
get { return m_levelName; }
}
/// <summary>
/// Gets the value of this level.
/// </summary>
/// <value>
/// The value of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the value of this level.
/// </para>
/// </remarks>
public int Value
{
get { return m_levelValue; }
}
/// <summary>
/// Gets the display name of this level.
/// </summary>
/// <value>
/// The display name of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the display name of this level.
/// </para>
/// </remarks>
public string DisplayName
{
get { return m_levelDisplayName; }
}
#endregion Public Instance Properties
#region Override implementation of Object
/// <summary>
/// Returns the <see cref="string" /> representation of the current
/// <see cref="Level" />.
/// </summary>
/// <returns>
/// A <see cref="string" /> representation of the current <see cref="Level" />.
/// </returns>
/// <remarks>
/// <para>
/// Returns the level <see cref="Name"/>.
/// </para>
/// </remarks>
override public string ToString()
{
return m_levelName;
}
/// <summary>
/// Compares levels.
/// </summary>
/// <param name="o">The object to compare against.</param>
/// <returns><c>true</c> if the objects are equal.</returns>
/// <remarks>
/// <para>
/// Compares the levels of <see cref="Level" /> instances, and
/// defers to base class if the target object is not a <see cref="Level" />
/// instance.
/// </para>
/// </remarks>
override public bool Equals(object o)
{
Level otherLevel = o as Level;
if (otherLevel != null)
{
return m_levelValue == otherLevel.m_levelValue;
}
else
{
return base.Equals(o);
}
}
/// <summary>
/// Returns a hash code
/// </summary>
/// <returns>A hash code for the current <see cref="Level" />.</returns>
/// <remarks>
/// <para>
/// Returns a hash code suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </para>
/// <para>
/// Returns the hash code of the level <see cref="Value"/>.
/// </para>
/// </remarks>
override public int GetHashCode()
{
return m_levelValue;
}
#endregion Override implementation of Object
#region Implementation of IComparable
/// <summary>
/// Compares this instance to a specified object and returns an
/// indication of their relative values.
/// </summary>
/// <param name="r">A <see cref="Level"/> instance or <see langword="null" /> to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the
/// values compared. The return value has these meanings:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>Less than zero</term>
/// <description>This instance is less than <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Zero</term>
/// <description>This instance is equal to <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <description>
/// <para>This instance is greater than <paramref name="r" />.</para>
/// <para>-or-</para>
/// <para><paramref name="r" /> is <see langword="null" />.</para>
/// </description>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// <paramref name="r" /> must be an instance of <see cref="Level" />
/// or <see langword="null" />; otherwise, an exception is thrown.
/// </para>
/// </remarks>
/// <exception cref="ArgumentException"><paramref name="r" /> is not a <see cref="Level" />.</exception>
public int CompareTo(object r)
{
Level target = r as Level;
if (target != null)
{
return Compare(this, target);
}
throw new ArgumentException("Parameter: r, Value: [" + r + "] is not an instance of Level");
}
#endregion Implementation of IComparable
#region Operators
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is greater than another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is greater than
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator > (Level l, Level r)
{
return l.m_levelValue > r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is less than another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is less than
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator < (Level l, Level r)
{
return l.m_levelValue < r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is greater than or equal to another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is greater than or equal to
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator >= (Level l, Level r)
{
return l.m_levelValue >= r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is less than or equal to another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is less than or equal to
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator <= (Level l, Level r)
{
return l.m_levelValue <= r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether two specified <see cref="Level" />
/// objects have the same value.
/// </summary>
/// <param name="l">A <see cref="Level" /> or <see langword="null" />.</param>
/// <param name="r">A <see cref="Level" /> or <see langword="null" />.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="l" /> is the same as the
/// value of <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator == (Level l, Level r)
{
if (((object)l) != null && ((object)r) != null)
{
return l.m_levelValue == r.m_levelValue;
}
else
{
return ((object) l) == ((object) r);
}
}
/// <summary>
/// Returns a value indicating whether two specified <see cref="Level" />
/// objects have different values.
/// </summary>
/// <param name="l">A <see cref="Level" /> or <see langword="null" />.</param>
/// <param name="r">A <see cref="Level" /> or <see langword="null" />.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="l" /> is different from
/// the value of <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator != (Level l, Level r)
{
return !(l==r);
}
#endregion Operators
#region Public Static Methods
/// <summary>
/// Compares two specified <see cref="Level"/> instances.
/// </summary>
/// <param name="l">The first <see cref="Level"/> to compare.</param>
/// <param name="r">The second <see cref="Level"/> to compare.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the
/// two values compared. The return value has these meanings:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>Less than zero</term>
/// <description><paramref name="l" /> is less than <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Zero</term>
/// <description><paramref name="l" /> is equal to <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <description><paramref name="l" /> is greater than <paramref name="r" />.</description>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static int Compare(Level l, Level r)
{
// Reference equals
if ((object)l == (object)r)
{
return 0;
}
if (l == null && r == null)
{
return 0;
}
if (l == null)
{
return -1;
}
if (r == null)
{
return 1;
}
return l.m_levelValue.CompareTo(r.m_levelValue);
}
#endregion Public Static Methods
#region Public Static Fields
/// <summary>
/// The <see cref="Off" /> level designates a higher level than all the rest.
/// </summary>
public readonly static Level Off = new Level(int.MaxValue, "OFF");
/// <summary>
/// The <see cref="Log4Net_Debug" /> is only used to debug internals of log4net.
/// </summary>
public readonly static Level Log4Net_Debug = new Level(120000, "log4net:DEBUG");
/// <summary>
/// The <see cref="Emergency" /> level designates very severe error events.
/// System unusable, emergencies.
/// </summary>
public readonly static Level Emergency = new Level(120000, "EMERGENCY");
/// <summary>
/// The <see cref="Fatal" /> level designates very severe error events
/// that will presumably lead the application to abort.
/// </summary>
public readonly static Level Fatal = new Level(110000, "FATAL");
/// <summary>
/// The <see cref="Alert" /> level designates very severe error events.
/// Take immediate action, alerts.
/// </summary>
public readonly static Level Alert = new Level(100000, "ALERT");
/// <summary>
/// The <see cref="Critical" /> level designates very severe error events.
/// Critical condition, critical.
/// </summary>
public readonly static Level Critical = new Level(90000, "CRITICAL");
/// <summary>
/// The <see cref="Severe" /> level designates very severe error events.
/// </summary>
public readonly static Level Severe = new Level(80000, "SEVERE");
/// <summary>
/// The <see cref="Error" /> level designates error events that might
/// still allow the application to continue running.
/// </summary>
public readonly static Level Error = new Level(70000, "ERROR");
/// <summary>
/// The <see cref="Warn" /> level designates potentially harmful
/// situations.
/// </summary>
public readonly static Level Warn = new Level(60000, "WARN");
/// <summary>
/// The <see cref="Notice" /> level designates informational messages
/// that highlight the progress of the application at the highest level.
/// </summary>
public readonly static Level Notice = new Level(50000, "NOTICE");
/// <summary>
/// The <see cref="Info" /> level designates informational messages that
/// highlight the progress of the application at coarse-grained level.
/// </summary>
public readonly static Level Info = new Level(40000, "INFO");
/// <summary>
/// The <see cref="Debug" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Debug = new Level(30000, "DEBUG");
/// <summary>
/// The <see cref="Fine" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Fine = new Level(30000, "FINE");
/// <summary>
/// The <see cref="Trace" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Trace = new Level(20000, "TRACE");
/// <summary>
/// The <see cref="Finer" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Finer = new Level(20000, "FINER");
/// <summary>
/// The <see cref="Verbose" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Verbose = new Level(10000, "VERBOSE");
/// <summary>
/// The <see cref="Finest" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Finest = new Level(10000, "FINEST");
/// <summary>
/// The <see cref="All" /> level designates the lowest level possible.
/// </summary>
public readonly static Level All = new Level(int.MinValue, "ALL");
#endregion Public Static Fields
#region Private Instance Fields
private readonly int m_levelValue;
private readonly string m_levelName;
private readonly string m_levelDisplayName;
#endregion Private Instance Fields
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomAudienceServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomAudienceRequestObject()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
GetCustomAudienceRequest request = new GetCustomAudienceRequest
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
};
gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Id = -6774108720365892680L,
Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled,
CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest,
Description = "description2cf9da67",
Members =
{
new gagvr::CustomAudienceMember(),
},
};
mockGrpcClient.Setup(x => x.GetCustomAudience(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomAudience response = client.GetCustomAudience(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomAudienceRequestObjectAsync()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
GetCustomAudienceRequest request = new GetCustomAudienceRequest
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
};
gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Id = -6774108720365892680L,
Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled,
CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest,
Description = "description2cf9da67",
Members =
{
new gagvr::CustomAudienceMember(),
},
};
mockGrpcClient.Setup(x => x.GetCustomAudienceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomAudience>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomAudience responseCallSettings = await client.GetCustomAudienceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomAudience responseCancellationToken = await client.GetCustomAudienceAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomAudience()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
GetCustomAudienceRequest request = new GetCustomAudienceRequest
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
};
gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Id = -6774108720365892680L,
Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled,
CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest,
Description = "description2cf9da67",
Members =
{
new gagvr::CustomAudienceMember(),
},
};
mockGrpcClient.Setup(x => x.GetCustomAudience(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomAudience response = client.GetCustomAudience(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomAudienceAsync()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
GetCustomAudienceRequest request = new GetCustomAudienceRequest
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
};
gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Id = -6774108720365892680L,
Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled,
CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest,
Description = "description2cf9da67",
Members =
{
new gagvr::CustomAudienceMember(),
},
};
mockGrpcClient.Setup(x => x.GetCustomAudienceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomAudience>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomAudience responseCallSettings = await client.GetCustomAudienceAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomAudience responseCancellationToken = await client.GetCustomAudienceAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomAudienceResourceNames()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
GetCustomAudienceRequest request = new GetCustomAudienceRequest
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
};
gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Id = -6774108720365892680L,
Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled,
CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest,
Description = "description2cf9da67",
Members =
{
new gagvr::CustomAudienceMember(),
},
};
mockGrpcClient.Setup(x => x.GetCustomAudience(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomAudience response = client.GetCustomAudience(request.ResourceNameAsCustomAudienceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomAudienceResourceNamesAsync()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
GetCustomAudienceRequest request = new GetCustomAudienceRequest
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
};
gagvr::CustomAudience expectedResponse = new gagvr::CustomAudience
{
ResourceNameAsCustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Id = -6774108720365892680L,
Status = gagve::CustomAudienceStatusEnum.Types.CustomAudienceStatus.Enabled,
CustomAudienceName = gagvr::CustomAudienceName.FromCustomerCustomAudience("[CUSTOMER_ID]", "[CUSTOM_AUDIENCE_ID]"),
Type = gagve::CustomAudienceTypeEnum.Types.CustomAudienceType.Interest,
Description = "description2cf9da67",
Members =
{
new gagvr::CustomAudienceMember(),
},
};
mockGrpcClient.Setup(x => x.GetCustomAudienceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomAudience>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomAudience responseCallSettings = await client.GetCustomAudienceAsync(request.ResourceNameAsCustomAudienceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomAudience responseCancellationToken = await client.GetCustomAudienceAsync(request.ResourceNameAsCustomAudienceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomAudiencesRequestObject()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomAudienceOperation(),
},
ValidateOnly = true,
};
MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse
{
Results =
{
new MutateCustomAudienceResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomAudiences(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomAudiencesResponse response = client.MutateCustomAudiences(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomAudiencesRequestObjectAsync()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomAudienceOperation(),
},
ValidateOnly = true,
};
MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse
{
Results =
{
new MutateCustomAudienceResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomAudiencesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomAudiencesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomAudiencesResponse responseCallSettings = await client.MutateCustomAudiencesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomAudiencesResponse responseCancellationToken = await client.MutateCustomAudiencesAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomAudiences()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomAudienceOperation(),
},
};
MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse
{
Results =
{
new MutateCustomAudienceResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomAudiences(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomAudiencesResponse response = client.MutateCustomAudiences(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomAudiencesAsync()
{
moq::Mock<CustomAudienceService.CustomAudienceServiceClient> mockGrpcClient = new moq::Mock<CustomAudienceService.CustomAudienceServiceClient>(moq::MockBehavior.Strict);
MutateCustomAudiencesRequest request = new MutateCustomAudiencesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomAudienceOperation(),
},
};
MutateCustomAudiencesResponse expectedResponse = new MutateCustomAudiencesResponse
{
Results =
{
new MutateCustomAudienceResult(),
},
};
mockGrpcClient.Setup(x => x.MutateCustomAudiencesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomAudiencesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomAudienceServiceClient client = new CustomAudienceServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomAudiencesResponse responseCallSettings = await client.MutateCustomAudiencesAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomAudiencesResponse responseCancellationToken = await client.MutateCustomAudiencesAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation runbook draft. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
internal partial class RunbookDraftOperations : IServiceOperations<AutomationManagementClient>, IRunbookDraftOperations
{
/// <summary>
/// Initializes a new instance of the RunbookDraftOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RunbookDraftOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the publish runbook operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> BeginPublishAsync(string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.PublishedBy == null)
{
throw new ArgumentNullException("parameters.PublishedBy");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginPublishAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(parameters.Name);
url = url + "/draft/publish";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LongRunningOperationResultResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ocp-location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> BeginUpdateAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Stream == null)
{
throw new ArgumentNullException("parameters.Stream");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(parameters.Name);
url = url + "/draft/content";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Stream;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/powershell");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
result = new LongRunningOperationResultResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ocp-location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> BeginUpdateGraphAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Stream == null)
{
throw new ArgumentNullException("parameters.Stream");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdateGraphAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(parameters.Name);
url = url + "/draft/content";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Stream;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/powershell");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
result = new LongRunningOperationResultResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ocp-location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the content of runbook draft identified by runbook name.
/// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the runbook content operation.
/// </returns>
public async Task<RunbookContentResponse> ContentAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "ContentAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/content";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
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
RunbookContentResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RunbookContentResponse();
result.Stream = responseContent;
}
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();
}
}
}
/// <summary>
/// Retrieve the runbook draft identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get runbook draft operation.
/// </returns>
public async Task<RunbookDraftGetResponse> GetAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
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
RunbookDraftGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RunbookDraftGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
RunbookDraft runbookDraftInstance = new RunbookDraft();
result.RunbookDraft = runbookDraftInstance;
JToken inEditValue = responseDoc["inEdit"];
if (inEditValue != null && inEditValue.Type != JTokenType.Null)
{
bool inEditInstance = ((bool)inEditValue);
runbookDraftInstance.InEdit = inEditInstance;
}
JToken draftContentLinkValue = responseDoc["draftContentLink"];
if (draftContentLinkValue != null && draftContentLinkValue.Type != JTokenType.Null)
{
ContentLink draftContentLinkInstance = new ContentLink();
runbookDraftInstance.DraftContentLink = draftContentLinkInstance;
JToken uriValue = draftContentLinkValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue));
draftContentLinkInstance.Uri = uriInstance;
}
JToken contentHashValue = draftContentLinkValue["contentHash"];
if (contentHashValue != null && contentHashValue.Type != JTokenType.Null)
{
ContentHash contentHashInstance = new ContentHash();
draftContentLinkInstance.ContentHash = contentHashInstance;
JToken algorithmValue = contentHashValue["algorithm"];
if (algorithmValue != null && algorithmValue.Type != JTokenType.Null)
{
string algorithmInstance = ((string)algorithmValue);
contentHashInstance.Algorithm = algorithmInstance;
}
JToken valueValue = contentHashValue["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue);
contentHashInstance.Value = valueInstance;
}
}
JToken versionValue = draftContentLinkValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
draftContentLinkInstance.Version = versionInstance;
}
}
JToken creationTimeValue = responseDoc["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
runbookDraftInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
runbookDraftInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]);
if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in parametersSequenceElement)
{
string parametersKey = ((string)property.Name);
JObject varToken = ((JObject)property.Value);
RunbookParameter runbookParameterInstance = new RunbookParameter();
runbookDraftInstance.Parameters.Add(parametersKey, runbookParameterInstance);
JToken typeValue = varToken["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
runbookParameterInstance.Type = typeInstance;
}
JToken isMandatoryValue = varToken["isMandatory"];
if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null)
{
bool isMandatoryInstance = ((bool)isMandatoryValue);
runbookParameterInstance.IsMandatory = isMandatoryInstance;
}
JToken positionValue = varToken["position"];
if (positionValue != null && positionValue.Type != JTokenType.Null)
{
int positionInstance = ((int)positionValue);
runbookParameterInstance.Position = positionInstance;
}
JToken defaultValueValue = varToken["defaultValue"];
if (defaultValueValue != null && defaultValueValue.Type != JTokenType.Null)
{
string defaultValueInstance = ((string)defaultValueValue);
runbookParameterInstance.DefaultValue = defaultValueInstance;
}
}
}
}
}
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();
}
}
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the publish runbook operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> PublishAsync(string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken)
{
AutomationManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PublishAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse response = await client.RunbookDraft.BeginPublishAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the undoedit runbook operation.
/// </returns>
public async Task<RunbookDraftUndoEditResponse> UndoEditAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "UndoEditAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/undoEdit";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
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
RunbookDraftUndoEditResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RunbookDraftUndoEditResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
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();
}
}
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> UpdateAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
AutomationManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse response = await client.RunbookDraft.BeginUpdateAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> UpdateGraphAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
AutomationManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateGraphAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse response = await client.RunbookDraft.BeginUpdateAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ArmorDemoWeb.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
namespace Sherlock {
partial class frmMain {
/// <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(frmMain));
this.mnuMain = new System.Windows.Forms.MenuStrip();
this.mnuFile = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileNew = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileOpen = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuFileSave = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileSaveAs = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuFileChangePassword = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.mnuFileExit = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFolder = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFolderAdd = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFolderRename = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFolderDelete = new System.Windows.Forms.ToolStripMenuItem();
this.mnuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mnuItemAdd = new System.Windows.Forms.ToolStripMenuItem();
this.mnuItemEdit = new System.Windows.Forms.ToolStripMenuItem();
this.mnuItemDelete = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuItemCopy = new System.Windows.Forms.ToolStripMenuItem();
this.mnuItemCopyStripped = new System.Windows.Forms.ToolStripMenuItem();
this.mnuItemCopyPart = new System.Windows.Forms.ToolStripMenuItem();
this.menuItemSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuItemOpen = new System.Windows.Forms.ToolStripMenuItem();
this.mnuTools = new System.Windows.Forms.ToolStripMenuItem();
this.mnuToolsRegisterShellExtensions = new System.Windows.Forms.ToolStripMenuItem();
this.mnuToolsRepairDatabase = new System.Windows.Forms.ToolStripMenuItem();
this.mnuHelp = new System.Windows.Forms.ToolStripMenuItem();
this.mnuHelpAbout = new System.Windows.Forms.ToolStripMenuItem();
this.tlbMain = new System.Windows.Forms.ToolStrip();
this.tbbOpen = new System.Windows.Forms.ToolStripButton();
this.tbbSave = new System.Windows.Forms.ToolStripButton();
this.tbbSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.tbbFolderAdd = new System.Windows.Forms.ToolStripButton();
this.tbbFolderRename = new System.Windows.Forms.ToolStripButton();
this.tbbFolderDelete = new System.Windows.Forms.ToolStripButton();
this.tbbSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.tbbItemAdd = new System.Windows.Forms.ToolStripButton();
this.tbbItemEdit = new System.Windows.Forms.ToolStripButton();
this.tbbItemDelete = new System.Windows.Forms.ToolStripButton();
this.tbbSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.tbbItemCopy = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.tbbItemOpen = new System.Windows.Forms.ToolStripButton();
this.staMain = new System.Windows.Forms.StatusStrip();
this.stpFolder = new System.Windows.Forms.ToolStripStatusLabel();
this.splMain = new System.Windows.Forms.SplitContainer();
this.tvwFolders = new System.Windows.Forms.TreeView();
this.cmsFolder = new System.Windows.Forms.ContextMenuStrip(this.components);
this.cmsFolderAdd = new System.Windows.Forms.ToolStripMenuItem();
this.cmsFolderRename = new System.Windows.Forms.ToolStripMenuItem();
this.cmsFolderDelete = new System.Windows.Forms.ToolStripMenuItem();
this.ilsMain = new System.Windows.Forms.ImageList(this.components);
this.lvwItems = new System.Windows.Forms.ListView();
this.chName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.chValue = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.cmsItem = new System.Windows.Forms.ContextMenuStrip(this.components);
this.cmsItemAdd = new System.Windows.Forms.ToolStripMenuItem();
this.cmsItemEdit = new System.Windows.Forms.ToolStripMenuItem();
this.cmsItemDelete = new System.Windows.Forms.ToolStripMenuItem();
this.cmsItemSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.cmsItemCopy = new System.Windows.Forms.ToolStripMenuItem();
this.cmsItemCopyStripped = new System.Windows.Forms.ToolStripMenuItem();
this.cmsItemCopyPart = new System.Windows.Forms.ToolStripMenuItem();
this.cmsItemSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.cmsItemOpen = new System.Windows.Forms.ToolStripMenuItem();
this.mnuMain.SuspendLayout();
this.tlbMain.SuspendLayout();
this.staMain.SuspendLayout();
this.splMain.Panel1.SuspendLayout();
this.splMain.Panel2.SuspendLayout();
this.splMain.SuspendLayout();
this.cmsFolder.SuspendLayout();
this.cmsItem.SuspendLayout();
this.SuspendLayout();
//
// mnuMain
//
this.mnuMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFile,
this.mnuFolder,
this.mnuItem,
this.mnuTools,
this.mnuHelp});
this.mnuMain.Location = new System.Drawing.Point(0, 0);
this.mnuMain.Name = "mnuMain";
this.mnuMain.Size = new System.Drawing.Size(682, 24);
this.mnuMain.TabIndex = 0;
this.mnuMain.Text = "Menu";
//
// mnuFile
//
this.mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFileNew,
this.mnuFileOpen,
this.mnuFileSeparator1,
this.mnuFileSave,
this.mnuFileSaveAs,
this.mnuFileSeparator2,
this.mnuFileChangePassword,
this.mnuFileSeparator3,
this.mnuFileExit});
this.mnuFile.Name = "mnuFile";
this.mnuFile.Size = new System.Drawing.Size(37, 20);
this.mnuFile.Text = "&File";
//
// mnuFileNew
//
this.mnuFileNew.Name = "mnuFileNew";
this.mnuFileNew.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.mnuFileNew.Size = new System.Drawing.Size(168, 22);
this.mnuFileNew.Text = "&New";
this.mnuFileNew.Click += new System.EventHandler(this.mnuFileNew_Click);
//
// mnuFileOpen
//
this.mnuFileOpen.Image = global::Sherlock.Properties.Resources.Open;
this.mnuFileOpen.Name = "mnuFileOpen";
this.mnuFileOpen.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.mnuFileOpen.Size = new System.Drawing.Size(168, 22);
this.mnuFileOpen.Text = "&Open";
this.mnuFileOpen.Click += new System.EventHandler(this.mnuFileOpen_Click);
//
// mnuFileSeparator1
//
this.mnuFileSeparator1.Name = "mnuFileSeparator1";
this.mnuFileSeparator1.Size = new System.Drawing.Size(165, 6);
//
// mnuFileSave
//
this.mnuFileSave.Image = global::Sherlock.Properties.Resources.Save;
this.mnuFileSave.Name = "mnuFileSave";
this.mnuFileSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.mnuFileSave.Size = new System.Drawing.Size(168, 22);
this.mnuFileSave.Text = "&Save";
this.mnuFileSave.Click += new System.EventHandler(this.mnuFileSave_Click);
//
// mnuFileSaveAs
//
this.mnuFileSaveAs.Name = "mnuFileSaveAs";
this.mnuFileSaveAs.Size = new System.Drawing.Size(168, 22);
this.mnuFileSaveAs.Text = "Save &As";
this.mnuFileSaveAs.Click += new System.EventHandler(this.mnuFileSaveAs_Click);
//
// mnuFileSeparator2
//
this.mnuFileSeparator2.Name = "mnuFileSeparator2";
this.mnuFileSeparator2.Size = new System.Drawing.Size(165, 6);
//
// mnuFileChangePassword
//
this.mnuFileChangePassword.Name = "mnuFileChangePassword";
this.mnuFileChangePassword.Size = new System.Drawing.Size(168, 22);
this.mnuFileChangePassword.Text = "Change Password";
this.mnuFileChangePassword.Click += new System.EventHandler(this.mnuFileChangePassword_Click);
//
// mnuFileSeparator3
//
this.mnuFileSeparator3.Name = "mnuFileSeparator3";
this.mnuFileSeparator3.Size = new System.Drawing.Size(165, 6);
//
// mnuFileExit
//
this.mnuFileExit.Name = "mnuFileExit";
this.mnuFileExit.Size = new System.Drawing.Size(168, 22);
this.mnuFileExit.Text = "E&xit";
this.mnuFileExit.Click += new System.EventHandler(this.mnuFileExit_Click);
//
// mnuFolder
//
this.mnuFolder.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFolderAdd,
this.mnuFolderRename,
this.mnuFolderDelete});
this.mnuFolder.Name = "mnuFolder";
this.mnuFolder.Size = new System.Drawing.Size(67, 20);
this.mnuFolder.Text = "Folder";
//
// mnuFolderAdd
//
this.mnuFolderAdd.Image = global::Sherlock.Properties.Resources.FolderAdd;
this.mnuFolderAdd.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnuFolderAdd.Name = "mnuFolderAdd";
this.mnuFolderAdd.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.A)));
this.mnuFolderAdd.Size = new System.Drawing.Size(170, 22);
this.mnuFolderAdd.Text = "&Add";
this.mnuFolderAdd.Click += new System.EventHandler(this.mnuFolderAdd_Click);
//
// mnuFolderRename
//
this.mnuFolderRename.Image = global::Sherlock.Properties.Resources.FolderRename;
this.mnuFolderRename.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnuFolderRename.Name = "mnuFolderRename";
this.mnuFolderRename.ShortcutKeyDisplayString = "F2";
this.mnuFolderRename.Size = new System.Drawing.Size(170, 22);
this.mnuFolderRename.Text = "&Rename";
this.mnuFolderRename.Click += new System.EventHandler(this.mnuFolderRename_Click);
//
// mnuFolderDelete
//
this.mnuFolderDelete.Image = global::Sherlock.Properties.Resources.FolderDelete;
this.mnuFolderDelete.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnuFolderDelete.Name = "mnuFolderDelete";
this.mnuFolderDelete.ShortcutKeyDisplayString = "Del";
this.mnuFolderDelete.Size = new System.Drawing.Size(170, 22);
this.mnuFolderDelete.Text = "&Delete";
this.mnuFolderDelete.Click += new System.EventHandler(this.mnuFolderDelete_Click);
//
// mnuItem
//
this.mnuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuItemAdd,
this.mnuItemEdit,
this.mnuItemDelete,
this.menuItemSeparator1,
this.mnuItemCopy,
this.mnuItemCopyStripped,
this.mnuItemCopyPart,
this.menuItemSeparator2,
this.mnuItemOpen});
this.mnuItem.Name = "mnuItem";
this.mnuItem.Size = new System.Drawing.Size(43, 20);
this.mnuItem.Text = "&Item";
//
// mnuItemAdd
//
this.mnuItemAdd.Image = global::Sherlock.Properties.Resources.ItemAdd;
this.mnuItemAdd.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnuItemAdd.Name = "mnuItemAdd";
this.mnuItemAdd.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
this.mnuItemAdd.Size = new System.Drawing.Size(149, 22);
this.mnuItemAdd.Text = "&Add";
this.mnuItemAdd.Click += new System.EventHandler(this.mnuItemAdd_Click);
//
// mnuItemEdit
//
this.mnuItemEdit.Image = global::Sherlock.Properties.Resources.ItemEdit;
this.mnuItemEdit.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnuItemEdit.Name = "mnuItemEdit";
this.mnuItemEdit.ShortcutKeyDisplayString = "Enter";
this.mnuItemEdit.Size = new System.Drawing.Size(149, 22);
this.mnuItemEdit.Text = "&Edit";
this.mnuItemEdit.Click += new System.EventHandler(this.mnuItemEdit_Click);
//
// mnuItemDelete
//
this.mnuItemDelete.Image = global::Sherlock.Properties.Resources.ItemDelete;
this.mnuItemDelete.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.mnuItemDelete.Name = "mnuItemDelete";
this.mnuItemDelete.ShortcutKeyDisplayString = "Del";
this.mnuItemDelete.Size = new System.Drawing.Size(149, 22);
this.mnuItemDelete.Text = "&Delete";
this.mnuItemDelete.Click += new System.EventHandler(this.mnuItemDelete_Click);
//
// menuItemSeparator1
//
this.menuItemSeparator1.Name = "menuItemSeparator1";
this.menuItemSeparator1.Size = new System.Drawing.Size(146, 6);
//
// mnuItemCopy
//
this.mnuItemCopy.Image = global::Sherlock.Properties.Resources.Copy;
this.mnuItemCopy.Name = "mnuItemCopy";
this.mnuItemCopy.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.mnuItemCopy.Size = new System.Drawing.Size(149, 22);
this.mnuItemCopy.Text = "&Copy";
this.mnuItemCopy.Click += new System.EventHandler(this.mnuItemCopy_Click);
//
// mnuItemCopyStripped
//
this.mnuItemCopyStripped.Name = "mnuItemCopyStripped";
this.mnuItemCopyStripped.Size = new System.Drawing.Size(149, 22);
this.mnuItemCopyStripped.Text = "Copy Stripped";
this.mnuItemCopyStripped.Click += new System.EventHandler(this.mnuItemCopyStripped_Click);
//
// mnuItemCopyPart
//
this.mnuItemCopyPart.Name = "mnuItemCopyPart";
this.mnuItemCopyPart.Size = new System.Drawing.Size(149, 22);
this.mnuItemCopyPart.Text = "Copy Part";
//
// menuItemSeparator2
//
this.menuItemSeparator2.Name = "menuItemSeparator2";
this.menuItemSeparator2.Size = new System.Drawing.Size(146, 6);
//
// mnuItemOpen
//
this.mnuItemOpen.Image = global::Sherlock.Properties.Resources.Link;
this.mnuItemOpen.Name = "mnuItemOpen";
this.mnuItemOpen.Size = new System.Drawing.Size(149, 22);
this.mnuItemOpen.Text = "Open";
this.mnuItemOpen.Click += new System.EventHandler(this.mnuItemOpen_Click);
//
// mnuTools
//
this.mnuTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuToolsRegisterShellExtensions,
this.mnuToolsRepairDatabase});
this.mnuTools.Name = "mnuTools";
this.mnuTools.Size = new System.Drawing.Size(48, 20);
this.mnuTools.Text = "&Tools";
//
// mnuToolsRegisterShellExtensions
//
this.mnuToolsRegisterShellExtensions.Name = "mnuToolsRegisterShellExtensions";
this.mnuToolsRegisterShellExtensions.Size = new System.Drawing.Size(202, 22);
this.mnuToolsRegisterShellExtensions.Text = "Register Shell Extensions";
this.mnuToolsRegisterShellExtensions.Click += new System.EventHandler(this.mnuToolsRegisterShellExtensions_Click);
//
// mnuToolsRepairDatabase
//
this.mnuToolsRepairDatabase.Name = "mnuToolsRepairDatabase";
this.mnuToolsRepairDatabase.Size = new System.Drawing.Size(202, 22);
this.mnuToolsRepairDatabase.Text = "Repair Database";
this.mnuToolsRepairDatabase.Click += new System.EventHandler(this.mnuToolsRepairDatabase_Click);
//
// mnuHelp
//
this.mnuHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuHelpAbout});
this.mnuHelp.Name = "mnuHelp";
this.mnuHelp.Size = new System.Drawing.Size(44, 20);
this.mnuHelp.Text = "&Help";
//
// mnuHelpAbout
//
this.mnuHelpAbout.Name = "mnuHelpAbout";
this.mnuHelpAbout.Size = new System.Drawing.Size(107, 22);
this.mnuHelpAbout.Text = "&About";
this.mnuHelpAbout.Click += new System.EventHandler(this.mnuHelpAbout_Click);
//
// tlbMain
//
this.tlbMain.AutoSize = false;
this.tlbMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tbbOpen,
this.tbbSave,
this.tbbSeparator1,
this.tbbFolderAdd,
this.tbbFolderRename,
this.tbbFolderDelete,
this.tbbSeparator2,
this.tbbItemAdd,
this.tbbItemEdit,
this.tbbItemDelete,
this.tbbSeparator3,
this.tbbItemCopy,
this.toolStripSeparator1,
this.tbbItemOpen});
this.tlbMain.Location = new System.Drawing.Point(0, 24);
this.tlbMain.Name = "tlbMain";
this.tlbMain.Size = new System.Drawing.Size(682, 40);
this.tlbMain.TabIndex = 1;
this.tlbMain.Text = "Standard";
//
// tbbOpen
//
this.tbbOpen.AutoSize = false;
this.tbbOpen.Image = global::Sherlock.Properties.Resources.Open;
this.tbbOpen.Name = "tbbOpen";
this.tbbOpen.Size = new System.Drawing.Size(40, 36);
this.tbbOpen.Text = "Open";
this.tbbOpen.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbOpen.Click += new System.EventHandler(this.mnuFileOpen_Click);
//
// tbbSave
//
this.tbbSave.AutoSize = false;
this.tbbSave.Image = global::Sherlock.Properties.Resources.Save;
this.tbbSave.Name = "tbbSave";
this.tbbSave.Size = new System.Drawing.Size(40, 36);
this.tbbSave.Text = "Save";
this.tbbSave.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbSave.Click += new System.EventHandler(this.mnuFileSave_Click);
//
// tbbSeparator1
//
this.tbbSeparator1.Name = "tbbSeparator1";
this.tbbSeparator1.Size = new System.Drawing.Size(6, 40);
//
// tbbFolderAdd
//
this.tbbFolderAdd.AutoSize = false;
this.tbbFolderAdd.Image = global::Sherlock.Properties.Resources.FolderAdd;
this.tbbFolderAdd.Name = "tbbFolderAdd";
this.tbbFolderAdd.Size = new System.Drawing.Size(40, 36);
this.tbbFolderAdd.Text = "Add";
this.tbbFolderAdd.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbFolderAdd.Click += new System.EventHandler(this.mnuFolderAdd_Click);
//
// tbbFolderRename
//
this.tbbFolderRename.Image = global::Sherlock.Properties.Resources.FolderRename;
this.tbbFolderRename.Name = "tbbFolderRename";
this.tbbFolderRename.Size = new System.Drawing.Size(54, 37);
this.tbbFolderRename.Text = "Rename";
this.tbbFolderRename.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbFolderRename.Click += new System.EventHandler(this.mnuFolderRename_Click);
//
// tbbFolderDelete
//
this.tbbFolderDelete.Image = global::Sherlock.Properties.Resources.FolderDelete;
this.tbbFolderDelete.Name = "tbbFolderDelete";
this.tbbFolderDelete.Size = new System.Drawing.Size(44, 37);
this.tbbFolderDelete.Text = "Delete";
this.tbbFolderDelete.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbFolderDelete.Click += new System.EventHandler(this.mnuFolderDelete_Click);
//
// tbbSeparator2
//
this.tbbSeparator2.Name = "tbbSeparator2";
this.tbbSeparator2.Size = new System.Drawing.Size(6, 40);
//
// tbbItemAdd
//
this.tbbItemAdd.AutoSize = false;
this.tbbItemAdd.Image = global::Sherlock.Properties.Resources.ItemAdd;
this.tbbItemAdd.Name = "tbbItemAdd";
this.tbbItemAdd.Size = new System.Drawing.Size(40, 36);
this.tbbItemAdd.Text = "Add";
this.tbbItemAdd.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbItemAdd.Click += new System.EventHandler(this.mnuItemAdd_Click);
//
// tbbItemEdit
//
this.tbbItemEdit.AutoSize = false;
this.tbbItemEdit.Image = global::Sherlock.Properties.Resources.ItemEdit;
this.tbbItemEdit.Name = "tbbItemEdit";
this.tbbItemEdit.Size = new System.Drawing.Size(40, 36);
this.tbbItemEdit.Text = "Edit";
this.tbbItemEdit.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbItemEdit.Click += new System.EventHandler(this.mnuItemEdit_Click);
//
// tbbItemDelete
//
this.tbbItemDelete.Image = global::Sherlock.Properties.Resources.ItemDelete;
this.tbbItemDelete.Name = "tbbItemDelete";
this.tbbItemDelete.Size = new System.Drawing.Size(44, 37);
this.tbbItemDelete.Text = "Delete";
this.tbbItemDelete.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbItemDelete.Click += new System.EventHandler(this.mnuItemDelete_Click);
//
// tbbSeparator3
//
this.tbbSeparator3.Name = "tbbSeparator3";
this.tbbSeparator3.Size = new System.Drawing.Size(6, 40);
//
// tbbItemCopy
//
this.tbbItemCopy.AutoSize = false;
this.tbbItemCopy.Image = global::Sherlock.Properties.Resources.Copy;
this.tbbItemCopy.Name = "tbbItemCopy";
this.tbbItemCopy.Size = new System.Drawing.Size(40, 36);
this.tbbItemCopy.Text = "Copy";
this.tbbItemCopy.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbItemCopy.Click += new System.EventHandler(this.mnuItemCopy_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 40);
//
// tbbItemOpen
//
this.tbbItemOpen.Image = global::Sherlock.Properties.Resources.Link;
this.tbbItemOpen.Name = "tbbItemOpen";
this.tbbItemOpen.Size = new System.Drawing.Size(40, 37);
this.tbbItemOpen.Text = "Open";
this.tbbItemOpen.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.tbbItemOpen.Click += new System.EventHandler(this.mnuItemOpen_Click);
//
// staMain
//
this.staMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.stpFolder});
this.staMain.Location = new System.Drawing.Point(0, 436);
this.staMain.Name = "staMain";
this.staMain.Size = new System.Drawing.Size(682, 22);
this.staMain.TabIndex = 2;
this.staMain.Text = "statusStrip1";
//
// stpFolder
//
this.stpFolder.Name = "stpFolder";
this.stpFolder.Size = new System.Drawing.Size(0, 17);
//
// splMain
//
this.splMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splMain.Location = new System.Drawing.Point(2, 68);
this.splMain.Name = "splMain";
//
// splMain.Panel1
//
this.splMain.Panel1.Controls.Add(this.tvwFolders);
//
// splMain.Panel2
//
this.splMain.Panel2.Controls.Add(this.lvwItems);
this.splMain.Size = new System.Drawing.Size(678, 363);
this.splMain.SplitterDistance = 207;
this.splMain.SplitterWidth = 3;
this.splMain.TabIndex = 3;
//
// tvwFolders
//
this.tvwFolders.AllowDrop = true;
this.tvwFolders.ContextMenuStrip = this.cmsFolder;
this.tvwFolders.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvwFolders.HideSelection = false;
this.tvwFolders.ImageIndex = 0;
this.tvwFolders.ImageList = this.ilsMain;
this.tvwFolders.LabelEdit = true;
this.tvwFolders.Location = new System.Drawing.Point(0, 0);
this.tvwFolders.Name = "tvwFolders";
this.tvwFolders.SelectedImageIndex = 1;
this.tvwFolders.Size = new System.Drawing.Size(207, 363);
this.tvwFolders.TabIndex = 0;
this.tvwFolders.BeforeLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.tvwCategories_BeforeLabelEdit);
this.tvwFolders.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.tvwCategories_AfterLabelEdit);
this.tvwFolders.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.tvwCategories_ItemDrag);
this.tvwFolders.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvwCategories_AfterSelect);
this.tvwFolders.DragDrop += new System.Windows.Forms.DragEventHandler(this.tvwCategories_DragDrop);
this.tvwFolders.DragOver += new System.Windows.Forms.DragEventHandler(this.tvwCategories_DragOver);
this.tvwFolders.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tvwCategories_KeyDown);
//
// cmsFolder
//
this.cmsFolder.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cmsFolderAdd,
this.cmsFolderRename,
this.cmsFolderDelete});
this.cmsFolder.Name = "cmsFolder";
this.cmsFolder.Size = new System.Drawing.Size(171, 70);
//
// cmsFolderAdd
//
this.cmsFolderAdd.Image = global::Sherlock.Properties.Resources.FolderAdd;
this.cmsFolderAdd.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.cmsFolderAdd.Name = "cmsFolderAdd";
this.cmsFolderAdd.ShortcutKeyDisplayString = "Ctrl+Shift+A";
this.cmsFolderAdd.Size = new System.Drawing.Size(170, 22);
this.cmsFolderAdd.Text = "Add";
this.cmsFolderAdd.Click += new System.EventHandler(this.mnuFolderAdd_Click);
//
// cmsFolderRename
//
this.cmsFolderRename.Image = global::Sherlock.Properties.Resources.FolderRename;
this.cmsFolderRename.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.cmsFolderRename.Name = "cmsFolderRename";
this.cmsFolderRename.ShortcutKeyDisplayString = "F2";
this.cmsFolderRename.Size = new System.Drawing.Size(170, 22);
this.cmsFolderRename.Text = "Rename";
this.cmsFolderRename.Click += new System.EventHandler(this.mnuFolderRename_Click);
//
// cmsFolderDelete
//
this.cmsFolderDelete.Image = global::Sherlock.Properties.Resources.FolderDelete;
this.cmsFolderDelete.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.cmsFolderDelete.Name = "cmsFolderDelete";
this.cmsFolderDelete.ShortcutKeyDisplayString = "Del";
this.cmsFolderDelete.Size = new System.Drawing.Size(170, 22);
this.cmsFolderDelete.Text = "Delete";
this.cmsFolderDelete.Click += new System.EventHandler(this.mnuFolderDelete_Click);
//
// ilsMain
//
this.ilsMain.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilsMain.ImageStream")));
this.ilsMain.TransparentColor = System.Drawing.Color.Empty;
this.ilsMain.Images.SetKeyName(0, "");
this.ilsMain.Images.SetKeyName(1, "");
this.ilsMain.Images.SetKeyName(2, "");
//
// lvwItems
//
this.lvwItems.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.chName,
this.chValue});
this.lvwItems.ContextMenuStrip = this.cmsItem;
this.lvwItems.Dock = System.Windows.Forms.DockStyle.Fill;
this.lvwItems.FullRowSelect = true;
this.lvwItems.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lvwItems.LabelEdit = true;
this.lvwItems.Location = new System.Drawing.Point(0, 0);
this.lvwItems.MultiSelect = false;
this.lvwItems.Name = "lvwItems";
this.lvwItems.Size = new System.Drawing.Size(468, 363);
this.lvwItems.SmallImageList = this.ilsMain;
this.lvwItems.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.lvwItems.TabIndex = 0;
this.lvwItems.UseCompatibleStateImageBehavior = false;
this.lvwItems.View = System.Windows.Forms.View.Details;
this.lvwItems.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.lvwItems_AfterLabelEdit);
this.lvwItems.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.lvwItems_ItemDrag);
this.lvwItems.SelectedIndexChanged += new System.EventHandler(this.lvwItems_SelectedIndexChanged);
this.lvwItems.DoubleClick += new System.EventHandler(this.mnuItemEdit_Click);
this.lvwItems.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lvwItems_KeyDown);
//
// chName
//
this.chName.Text = "Name";
this.chName.Width = 169;
//
// chValue
//
this.chValue.Text = "Value";
this.chValue.Width = 229;
//
// cmsItem
//
this.cmsItem.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cmsItemAdd,
this.cmsItemEdit,
this.cmsItemDelete,
this.cmsItemSeparator1,
this.cmsItemCopy,
this.cmsItemCopyStripped,
this.cmsItemCopyPart,
this.cmsItemSeparator2,
this.cmsItemOpen});
this.cmsItem.Name = "cmsItem";
this.cmsItem.Size = new System.Drawing.Size(143, 170);
//
// cmsItemAdd
//
this.cmsItemAdd.Image = global::Sherlock.Properties.Resources.ItemAdd;
this.cmsItemAdd.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.cmsItemAdd.Name = "cmsItemAdd";
this.cmsItemAdd.ShortcutKeyDisplayString = "Ctrl+A";
this.cmsItemAdd.Size = new System.Drawing.Size(142, 22);
this.cmsItemAdd.Text = "&Add";
this.cmsItemAdd.Click += new System.EventHandler(this.mnuItemAdd_Click);
//
// cmsItemEdit
//
this.cmsItemEdit.Image = global::Sherlock.Properties.Resources.ItemEdit;
this.cmsItemEdit.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.cmsItemEdit.Name = "cmsItemEdit";
this.cmsItemEdit.ShortcutKeyDisplayString = "Enter";
this.cmsItemEdit.Size = new System.Drawing.Size(142, 22);
this.cmsItemEdit.Text = "&Edit";
this.cmsItemEdit.Click += new System.EventHandler(this.mnuItemEdit_Click);
//
// cmsItemDelete
//
this.cmsItemDelete.Image = global::Sherlock.Properties.Resources.ItemDelete;
this.cmsItemDelete.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.cmsItemDelete.Name = "cmsItemDelete";
this.cmsItemDelete.ShortcutKeyDisplayString = "Del";
this.cmsItemDelete.Size = new System.Drawing.Size(142, 22);
this.cmsItemDelete.Text = "&Delete";
this.cmsItemDelete.Click += new System.EventHandler(this.mnuItemDelete_Click);
//
// cmsItemSeparator1
//
this.cmsItemSeparator1.Name = "cmsItemSeparator1";
this.cmsItemSeparator1.Size = new System.Drawing.Size(139, 6);
//
// cmsItemCopy
//
this.cmsItemCopy.Image = global::Sherlock.Properties.Resources.Copy;
this.cmsItemCopy.Name = "cmsItemCopy";
this.cmsItemCopy.ShortcutKeyDisplayString = "Ctrl+C";
this.cmsItemCopy.Size = new System.Drawing.Size(142, 22);
this.cmsItemCopy.Text = "&Copy";
this.cmsItemCopy.Click += new System.EventHandler(this.mnuItemCopy_Click);
//
// cmsItemCopyStripped
//
this.cmsItemCopyStripped.Name = "cmsItemCopyStripped";
this.cmsItemCopyStripped.Size = new System.Drawing.Size(142, 22);
this.cmsItemCopyStripped.Text = "Copy Stripped";
this.cmsItemCopyStripped.Click += new System.EventHandler(this.mnuItemCopyStripped_Click);
//
// cmsItemCopyPart
//
this.cmsItemCopyPart.Name = "cmsItemCopyPart";
this.cmsItemCopyPart.Size = new System.Drawing.Size(142, 22);
this.cmsItemCopyPart.Text = "Copy Part";
//
// cmsItemSeparator2
//
this.cmsItemSeparator2.Name = "cmsItemSeparator2";
this.cmsItemSeparator2.Size = new System.Drawing.Size(139, 6);
//
// cmsItemOpen
//
this.cmsItemOpen.Image = global::Sherlock.Properties.Resources.Link;
this.cmsItemOpen.Name = "cmsItemOpen";
this.cmsItemOpen.Size = new System.Drawing.Size(142, 22);
this.cmsItemOpen.Text = "&Open";
this.cmsItemOpen.Click += new System.EventHandler(this.mnuItemOpen_Click);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(682, 458);
this.Controls.Add(this.splMain);
this.Controls.Add(this.staMain);
this.Controls.Add(this.tlbMain);
this.Controls.Add(this.mnuMain);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.mnuMain;
this.Name = "frmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Sherlock";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing);
this.mnuMain.ResumeLayout(false);
this.mnuMain.PerformLayout();
this.tlbMain.ResumeLayout(false);
this.tlbMain.PerformLayout();
this.staMain.ResumeLayout(false);
this.staMain.PerformLayout();
this.splMain.Panel1.ResumeLayout(false);
this.splMain.Panel2.ResumeLayout(false);
this.splMain.ResumeLayout(false);
this.cmsFolder.ResumeLayout(false);
this.cmsItem.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip mnuMain;
private System.Windows.Forms.ToolStripMenuItem mnuFile;
private System.Windows.Forms.ToolStripMenuItem mnuFileNew;
private System.Windows.Forms.ToolStripMenuItem mnuFileOpen;
private System.Windows.Forms.ToolStripSeparator mnuFileSeparator1;
private System.Windows.Forms.ToolStripMenuItem mnuFileSave;
private System.Windows.Forms.ToolStripMenuItem mnuFileSaveAs;
private System.Windows.Forms.ToolStripSeparator mnuFileSeparator2;
private System.Windows.Forms.ToolStripMenuItem mnuFileExit;
private System.Windows.Forms.ToolStripMenuItem mnuHelp;
private System.Windows.Forms.ToolStripMenuItem mnuHelpAbout;
private System.Windows.Forms.ToolStrip tlbMain;
private System.Windows.Forms.ToolStripButton tbbOpen;
private System.Windows.Forms.ToolStripButton tbbSave;
private System.Windows.Forms.ToolStripSeparator tbbSeparator1;
private System.Windows.Forms.ToolStripButton tbbItemCopy;
private System.Windows.Forms.ToolStripButton tbbFolderAdd;
private System.Windows.Forms.StatusStrip staMain;
private System.Windows.Forms.SplitContainer splMain;
private System.Windows.Forms.TreeView tvwFolders;
private System.Windows.Forms.ListView lvwItems;
private System.Windows.Forms.ToolStripButton tbbFolderDelete;
private System.Windows.Forms.ToolStripButton tbbFolderRename;
private System.Windows.Forms.ToolStripMenuItem mnuFolder;
private System.Windows.Forms.ToolStripMenuItem mnuFolderAdd;
private System.Windows.Forms.ToolStripMenuItem mnuFolderRename;
private System.Windows.Forms.ToolStripMenuItem mnuFolderDelete;
private System.Windows.Forms.ToolStripMenuItem mnuItem;
private System.Windows.Forms.ToolStripMenuItem mnuItemAdd;
private System.Windows.Forms.ToolStripMenuItem mnuItemEdit;
private System.Windows.Forms.ToolStripMenuItem mnuItemDelete;
private System.Windows.Forms.ToolStripButton tbbItemAdd;
private System.Windows.Forms.ToolStripButton tbbItemEdit;
private System.Windows.Forms.ToolStripButton tbbItemDelete;
private System.Windows.Forms.ImageList ilsMain;
private System.Windows.Forms.ColumnHeader chName;
private System.Windows.Forms.ColumnHeader chValue;
private System.Windows.Forms.ToolStripSeparator menuItemSeparator1;
private System.Windows.Forms.ToolStripMenuItem mnuItemCopy;
private System.Windows.Forms.ToolStripSeparator tbbSeparator2;
private System.Windows.Forms.ToolStripSeparator tbbSeparator3;
private System.Windows.Forms.ToolStripStatusLabel stpFolder;
private System.Windows.Forms.ToolStripMenuItem mnuFileChangePassword;
private System.Windows.Forms.ToolStripSeparator mnuFileSeparator3;
private System.Windows.Forms.ToolStripMenuItem mnuItemCopyStripped;
private System.Windows.Forms.ContextMenuStrip cmsItem;
private System.Windows.Forms.ToolStripMenuItem cmsItemAdd;
private System.Windows.Forms.ToolStripMenuItem cmsItemEdit;
private System.Windows.Forms.ToolStripMenuItem cmsItemDelete;
private System.Windows.Forms.ToolStripSeparator cmsItemSeparator1;
private System.Windows.Forms.ToolStripMenuItem cmsItemCopy;
private System.Windows.Forms.ToolStripMenuItem cmsItemCopyStripped;
private System.Windows.Forms.ToolStripMenuItem mnuItemOpen;
private System.Windows.Forms.ToolStripButton tbbItemOpen;
private System.Windows.Forms.ToolStripMenuItem cmsItemOpen;
private System.Windows.Forms.ContextMenuStrip cmsFolder;
private System.Windows.Forms.ToolStripMenuItem cmsFolderAdd;
private System.Windows.Forms.ToolStripMenuItem cmsFolderRename;
private System.Windows.Forms.ToolStripMenuItem cmsFolderDelete;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSeparator menuItemSeparator2;
private System.Windows.Forms.ToolStripSeparator cmsItemSeparator2;
private System.Windows.Forms.ToolStripMenuItem mnuTools;
private System.Windows.Forms.ToolStripMenuItem mnuToolsRegisterShellExtensions;
private System.Windows.Forms.ToolStripMenuItem mnuToolsRepairDatabase;
private System.Windows.Forms.ToolStripMenuItem cmsItemCopyPart;
private System.Windows.Forms.ToolStripMenuItem mnuItemCopyPart;
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace UnrealBuildTool
{
/**
* Base class for platform-specific project generators
*/
public abstract class UEPlatformProjectGenerator
{
static Dictionary<UnrealTargetPlatform, UEPlatformProjectGenerator> ProjectGeneratorDictionary = new Dictionary<UnrealTargetPlatform, UEPlatformProjectGenerator>();
/**
* Register the given platforms UEPlatformProjectGenerator instance
*
* @param InPlatform The UnrealTargetPlatform to register with
* @param InProjectGenerator The UEPlatformProjectGenerator instance to use for the InPlatform
*/
public static void RegisterPlatformProjectGenerator(UnrealTargetPlatform InPlatform, UEPlatformProjectGenerator InProjectGenerator)
{
// Make sure the build platform is legal
var BuildPlatform = UEBuildPlatform.GetBuildPlatform(InPlatform, true);
if (BuildPlatform != null)
{
if (ProjectGeneratorDictionary.ContainsKey(InPlatform) == true)
{
Log.TraceInformation("RegisterPlatformProjectGenerator Warning: Registering project generator {0} for {1} when it is already set to {2}",
InProjectGenerator.ToString(), InPlatform.ToString(), ProjectGeneratorDictionary[InPlatform].ToString());
ProjectGeneratorDictionary[InPlatform] = InProjectGenerator;
}
else
{
ProjectGeneratorDictionary.Add(InPlatform, InProjectGenerator);
}
}
else
{
Log.TraceVerbose("Skipping project file generator registration for {0} due to no valid BuildPlatform.", InPlatform.ToString());
}
}
/**
* Retrieve the UEPlatformProjectGenerator instance for the given TargetPlatform
*
* @param InPlatform The UnrealTargetPlatform being built
* @param bInAllowFailure If true, do not throw an exception and return null
*
* @return UEPlatformProjectGenerator The instance of the project generator
*/
public static UEPlatformProjectGenerator GetPlatformProjectGenerator(UnrealTargetPlatform InPlatform, bool bInAllowFailure = false)
{
if (ProjectGeneratorDictionary.ContainsKey(InPlatform) == true)
{
return ProjectGeneratorDictionary[InPlatform];
}
if (bInAllowFailure == true)
{
return null;
}
throw new BuildException("GetPlatformProjectGenerator: No PlatformProjectGenerator found for {0}", InPlatform.ToString());
}
/// <summary>
/// Allow various platform project generators to generate stub projects if required
/// </summary>
/// <param name="InTargetName"></param>
/// <param name="InTargetFilepath"></param>
/// <returns></returns>
public static bool GenerateGameProjectStubs(ProjectFileGenerator InGenerator, string InTargetName, string InTargetFilepath, TargetRules InTargetRules,
List<UnrealTargetPlatform> InPlatforms, List<UnrealTargetConfiguration> InConfigurations)
{
foreach (KeyValuePair<UnrealTargetPlatform, UEPlatformProjectGenerator> Entry in ProjectGeneratorDictionary)
{
UEPlatformProjectGenerator ProjGen = Entry.Value;
ProjGen.GenerateGameProjectStub(InGenerator, InTargetName, InTargetFilepath, InTargetRules, InPlatforms, InConfigurations);
}
return true;
}
/// <summary>
/// Allow various platform project generators to generate any special project properties if required
/// </summary>
/// <param name="InPlatform"></param>
/// <returns></returns>
public static bool GenerateGamePlatformSpecificProperties(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration Configuration, TargetRules.TargetType TargetType, StringBuilder VCProjectFileContent, string RootDirectory, string TargetFilePath)
{
if (ProjectGeneratorDictionary.ContainsKey(InPlatform) == true)
{
ProjectGeneratorDictionary[InPlatform].GenerateGameProperties(Configuration, VCProjectFileContent, TargetType, RootDirectory, TargetFilePath); ;
}
return true;
}
public static bool PlatformRequiresVSUserFileGeneration(List<UnrealTargetPlatform> InPlatforms, List<UnrealTargetConfiguration> InConfigurations)
{
bool bRequiresVSUserFileGeneration = false;
foreach (KeyValuePair<UnrealTargetPlatform, UEPlatformProjectGenerator> Entry in ProjectGeneratorDictionary)
{
if (InPlatforms.Contains(Entry.Key))
{
UEPlatformProjectGenerator ProjGen = Entry.Value;
bRequiresVSUserFileGeneration |= ProjGen.RequiresVSUserFileGeneration();
}
}
return bRequiresVSUserFileGeneration;
}
/**
* Register the platform with the UEPlatformProjectGenerator class
*/
public abstract void RegisterPlatformProjectGenerator();
public virtual void GenerateGameProjectStub(ProjectFileGenerator InGenerator, string InTargetName, string InTargetFilepath, TargetRules InTargetRules,
List<UnrealTargetPlatform> InPlatforms, List<UnrealTargetConfiguration> InConfigurations)
{
// Do nothing
}
public virtual void GenerateGameProperties(UnrealTargetConfiguration Configuration, StringBuilder VCProjectFileContent, TargetRules.TargetType TargetType, string RootDirectory, string TargetFilePath)
{
// Do nothing
}
public virtual bool RequiresVSUserFileGeneration()
{
return false;
}
///
/// VisualStudio project generation functions
///
/**
* Whether this build platform has native support for VisualStudio
*
* @param InPlatform The UnrealTargetPlatform being built
* @param InConfiguration The UnrealTargetConfiguration being built
*
* @return bool true if native VisualStudio support (or custom VSI) is available
*/
public virtual bool HasVisualStudioSupport(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
// By default, we assume this is true
return true;
}
/**
* Return the VisualStudio platform name for this build platform
*
* @param InPlatform The UnrealTargetPlatform being built
* @param InConfiguration The UnrealTargetConfiguration being built
*
* @return string The name of the platform that VisualStudio recognizes
*/
public virtual string GetVisualStudioPlatformName(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
// By default, return the platform string
return InPlatform.ToString();
}
/**
* Return the platform toolset string to write into the project configuration
*
* @param InPlatform The UnrealTargetPlatform being built
* @param InConfiguration The UnrealTargetConfiguration being built
*
* @return string The custom configuration section for the project file; Empty string if it doesn't require one
*/
public virtual string GetVisualStudioPlatformToolsetString(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration, VCProjectFile InProjectFile)
{
return "";
}
/**
* Return any custom property group lines
*
* @param InPlatform The UnrealTargetPlatform being built
*
* @return string The custom property import lines for the project file; Empty string if it doesn't require one
*/
public virtual string GetAdditionalVisualStudioPropertyGroups(UnrealTargetPlatform InPlatform)
{
return "";
}
/**
* Return any custom property group lines
*
* @param InPlatform The UnrealTargetPlatform being built
*
* @return string The platform configuration type. Defaults to "Makefile" unless overridden
*/
public virtual string GetVisualStudioPlatformConfigurationType(UnrealTargetPlatform InPlatform)
{
return "Makefile";
}
/**
* Return any custom paths for VisualStudio this platform requires
* This include ReferencePath, LibraryPath, LibraryWPath, IncludePath and ExecutablePath.
*
* @param InPlatform The UnrealTargetPlatform being built
* @param TargetType The type of target (game or program)
*
* @return string The custom path lines for the project file; Empty string if it doesn't require one
*/
public virtual string GetVisualStudioPathsEntries(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration, TargetRules.TargetType TargetType, string TargetRulesPath, string ProjectFilePath, string NMakeOutputPath)
{
// NOTE: We are intentionally overriding defaults for these paths with empty strings. We never want Visual Studio's
// defaults for these fields to be propagated, since they are version-sensitive paths that may not reflect
// the environment that UBT is building in. We'll set these environment variables ourselves!
// NOTE: We don't touch 'ExecutablePath' because that would result in Visual Studio clobbering the system "Path"
// environment variable
string PathsLines =
" <IncludePath />\n" +
" <ReferencePath />\n" +
" <LibraryPath />\n" +
" <LibraryWPath />\n" +
" <SourcePath />\n" +
" <ExcludePath />\n";
return PathsLines;
}
/**
* Return any custom property import lines
*
* @param InPlatform The UnrealTargetPlatform being built
*
* @return string The custom property import lines for the project file; Empty string if it doesn't require one
*/
public virtual string GetAdditionalVisualStudioImportSettings(UnrealTargetPlatform InPlatform)
{
return "";
}
/**
* Return any custom layout directory sections
*
* @param InPlatform The UnrealTargetPlatform being built
* @param TargetType The type of target (game or program)
*
* @return string The custom property import lines for the project file; Empty string if it doesn't require one
*/
public virtual string GetVisualStudioLayoutDirSection(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration, string InConditionString, TargetRules.TargetType TargetType, string TargetRulesPath, string ProjectFilePath, string NMakeOutputPath)
{
return "";
}
/**
* Get the output manifest section, if required
*
* @param InPlatform The UnrealTargetPlatform being built
*
* @return string The output manifest section for the project file; Empty string if it doesn't require one
*/
public virtual string GetVisualStudioOutputManifestSection(UnrealTargetPlatform InPlatform, TargetRules.TargetType TargetType, string TargetRulesPath, string ProjectFilePath)
{
return "";
}
/**
* Get whether this platform deploys
*
* @return bool true if the 'Deploy' option should be enabled
*/
public virtual bool GetVisualStudioDeploymentEnabled(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration)
{
return false;
}
/// <summary>
/// Get the text to insert into the user file for the given platform/configuration/target
/// </summary>
/// <param name="InPlatform">The platform being added</param>
/// <param name="InConfiguration">The configuration being added</param>
/// <param name="InConditionString">The condition string </param>
/// <param name="InTargetRules">The target rules </param>
/// <param name="TargetRulesPath">The target rules path</param>
/// <param name="ProjectFilePath">The project file path</param>
/// <returns>The string to append to the user file</returns>
public virtual string GetVisualStudioUserFileStrings(UnrealTargetPlatform InPlatform, UnrealTargetConfiguration InConfiguration,
string InConditionString, TargetRules InTargetRules, string TargetRulesPath, string ProjectFilePath)
{
return "";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace BatchClientIntegrationTests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using BatchTestCommon;
using Fixtures;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Common;
using Microsoft.Azure.Batch.Integration.Tests.Infrastructure;
using IntegrationTestUtilities;
using Xunit;
using Xunit.Abstractions;
[Collection("SharedPoolCollection")]
public class NodeFileIntegrationTests
{
private readonly ITestOutputHelper testOutputHelper;
private readonly PoolFixture poolFixture;
private static readonly TimeSpan TestTimeout = TimeSpan.FromMinutes(2);
public NodeFileIntegrationTests(ITestOutputHelper testOutputHelper, PaasWindowsPoolFixture poolFixture)
{
this.testOutputHelper = testOutputHelper;
this.poolFixture = poolFixture;
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void Bug1480489NodeFileMissingIsDirectory()
{
void test()
{
using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
string jobId = "Bug1480489Job-" + TestUtilities.GetMyName();
try
{
// here we show how to use an unbound Job + Commit() to run millions of Tasks
CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation() { PoolId = poolFixture.PoolId });
unboundJob.Commit();
// Open the new Job as bound.
CloudJob boundJob = batchCli.JobOperations.GetJob(jobId);
CloudTask myTask = new CloudTask(id: "Bug1480489Task", commandline: @"md Bug1480489Directory");
// add the task to the job
boundJob.AddTask(myTask);
// wait for the task to complete
Utilities utilities = batchCli.Utilities;
TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
boundJob.ListTasks(),
Microsoft.Azure.Batch.Common.TaskState.Completed,
TimeSpan.FromMinutes(3));
CloudTask myCompletedTask = new List<CloudTask>(boundJob.ListTasks(null))[0];
string stdOut = myCompletedTask.GetNodeFile(Constants.StandardOutFileName).ReadAsString();
string stdErr = myCompletedTask.GetNodeFile(Constants.StandardErrorFileName).ReadAsString();
testOutputHelper.WriteLine("TaskId: " + myCompletedTask.Id);
testOutputHelper.WriteLine("StdOut: ");
testOutputHelper.WriteLine(stdOut);
testOutputHelper.WriteLine("StdErr: ");
testOutputHelper.WriteLine(stdErr);
testOutputHelper.WriteLine("Task Files:");
bool foundAtLeastOneDir = false;
foreach (NodeFile curFile in myCompletedTask.ListNodeFiles())
{
testOutputHelper.WriteLine(" Filepath: " + curFile.Path);
testOutputHelper.WriteLine(" IsDirectory: " + curFile.IsDirectory.ToString());
// turns out wd is created for each task so use it as sentinal
if (curFile.Path.Equals("wd") && curFile.IsDirectory.HasValue && curFile.IsDirectory.Value)
{
foundAtLeastOneDir = true;
}
}
Assert.True(foundAtLeastOneDir);
}
finally
{
TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
}
}
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void Bug230385SupportDeleteNodeFileByTask()
{
void test()
{
using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
string jobId = "Bug230285Job-" + TestUtilities.GetMyName();
try
{
const string taskId = "hiWorld";
const string directoryCreationTaskId1 = "dirTask1";
const string directoryCreationTaskId2 = "dirTask2";
const string directoryNameOne = "Foo";
const string directoryNameTwo = "Bar";
const string directory2PathOnNode = "wd/" + directoryNameTwo;
//
// Create the job
//
CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation());
unboundJob.PoolInformation.PoolId = poolFixture.PoolId;
unboundJob.Commit();
CloudJob boundJob = batchCli.JobOperations.GetJob(jobId);
CloudTask myTask = new CloudTask(taskId, "cmd /c echo hello world");
CloudTask directoryCreationTask1 = new CloudTask(directoryCreationTaskId1, string.Format("cmd /c mkdir {0} && echo test > {0}/testfile.txt", directoryNameOne));
CloudTask directoryCreationTask2 = new CloudTask(directoryCreationTaskId2, string.Format("cmd /c mkdir {0} && echo test > {0}/testfile.txt", directoryNameTwo));
boundJob.AddTask(myTask);
boundJob.AddTask(directoryCreationTask1);
boundJob.AddTask(directoryCreationTask2);
testOutputHelper.WriteLine("Initial job commit()");
//
// Wait for task to go to completion
//
Utilities utilities = batchCli.Utilities;
TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
boundJob.ListTasks(),
Microsoft.Azure.Batch.Common.TaskState.Completed,
TimeSpan.FromMinutes(3));
//
// NodeFile delete
//
//Delete single file
NodeFile file = batchCli.JobOperations.GetNodeFile(jobId, taskId, Constants.StandardOutFileName);
file.Delete();
//Ensure delete succeeded
TestUtilities.AssertThrows<BatchException>(() => batchCli.JobOperations.GetNodeFile(jobId, taskId, Constants.StandardOutFileName));
//Delete directory
NodeFile directory = batchCli.JobOperations.ListNodeFiles(jobId, directoryCreationTaskId1, recursive: true).First(item => item.Path.Contains(directoryNameOne));
Assert.True(directory.IsDirectory);
TestUtilities.AssertThrows<BatchException>(() => directory.Delete(recursive: false));
directory.Delete(recursive: true);
Assert.Null(batchCli.JobOperations.ListNodeFiles(jobId, directoryCreationTaskId1, recursive: true).FirstOrDefault(item => item.Path.Contains(directoryNameOne)));
//
// JobScheduleOperations delete task file
//
batchCli.JobOperations.GetNodeFile(jobId, taskId, Constants.StandardErrorFileName);
batchCli.JobOperations.DeleteNodeFile(jobId, taskId, Constants.StandardErrorFileName);
//Ensure delete succeeded
TestUtilities.AssertThrows<BatchException>(() => batchCli.JobOperations.GetNodeFile(jobId, taskId, Constants.StandardErrorFileName));
//Delete directory
directory = batchCli.JobOperations.ListNodeFiles(jobId, directoryCreationTaskId2, recursive: true).First(item => item.Path.Contains(directoryNameTwo));
Assert.True(directory.IsDirectory);
TestUtilities.AssertThrows<BatchException>(() => batchCli.JobOperations.DeleteNodeFile(jobId, directoryCreationTaskId2, directory2PathOnNode, recursive: false));
batchCli.JobOperations.DeleteNodeFile(jobId, directoryCreationTaskId2, directory2PathOnNode, recursive: true);
Assert.Null(batchCli.JobOperations.ListNodeFiles(jobId, directoryCreationTaskId2, recursive: true).FirstOrDefault(item => item.Path.Contains(directoryNameTwo)));
}
finally
{
TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
}
}
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void TestNode_GetListDeleteFiles()
{
void test()
{
using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
string jobId = "TestNodeGetListDeleteFiles-" + TestUtilities.GetMyName();
try
{
const string taskId = "hiWorld";
const string directoryCreationTaskId1 = "dirTask1";
const string directoryCreationTaskId2 = "dirTask2";
const string directoryNameOne = "Foo";
const string directoryNameTwo = "Bar";
//
// Create the job
//
CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation());
unboundJob.PoolInformation.PoolId = poolFixture.PoolId;
unboundJob.Commit();
CloudJob boundJob = batchCli.JobOperations.GetJob(jobId);
CloudTask myTask = new CloudTask(taskId, "cmd /c echo hello world");
CloudTask directoryCreationTask1 = new CloudTask(directoryCreationTaskId1, string.Format("cmd /c mkdir {0} && echo test > {0}/testfile.txt", directoryNameOne));
CloudTask directoryCreationTask2 = new CloudTask(directoryCreationTaskId2, string.Format("cmd /c mkdir {0} && echo test > {0}/testfile.txt", directoryNameTwo));
boundJob.AddTask(myTask);
boundJob.AddTask(directoryCreationTask1);
boundJob.AddTask(directoryCreationTask2);
testOutputHelper.WriteLine("Initial job commit()");
//
// Wait for task to go to completion
//
Utilities utilities = batchCli.Utilities;
TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
boundJob.ListTasks(),
Microsoft.Azure.Batch.Common.TaskState.Completed,
TimeSpan.FromMinutes(3));
CloudTask boundTask = boundJob.GetTask(taskId);
//Since the compute node name comes back as "Node:<computeNodeId>" we need to split on : to get the actual compute node name
string computeNodeId = boundTask.ComputeNodeInformation.AffinityId.Split(':')[1];
ComputeNode computeNode = batchCli.PoolOperations.GetComputeNode(poolFixture.PoolId, computeNodeId);
testOutputHelper.WriteLine("Task ran on compute node: {0}", computeNodeId);
//Ensure that ListFiles done without a recursive option, or with recursive false return the same values
{
List<NodeFile> filesByComputeNodeRecursiveOmitted = batchCli.PoolOperations.ListNodeFiles(
poolFixture.PoolId,
computeNodeId).ToList();
List<NodeFile> filesByComputeNodeRecursiveFalse = batchCli.PoolOperations.ListNodeFiles(
poolFixture.PoolId,
computeNodeId,
recursive: false).ToList();
AssertFileListsMatch(filesByComputeNodeRecursiveOmitted, filesByComputeNodeRecursiveFalse);
}
{
List<NodeFile> filesByTaskRecursiveOmitted = batchCli.JobOperations.ListNodeFiles(
jobId,
taskId).ToList();
List<NodeFile> filesByTaskRecursiveFalse = batchCli.JobOperations.ListNodeFiles(
jobId,
taskId,
recursive: false).ToList();
AssertFileListsMatch(filesByTaskRecursiveOmitted, filesByTaskRecursiveFalse);
}
//
// List all node files from operations -- recursive true
//
//TODO: Detail level?
List<NodeFile> fileListFromComputeNodeOperations = batchCli.PoolOperations.ListNodeFiles(poolFixture.PoolId, computeNodeId, recursive: true).ToList();
foreach (NodeFile f in fileListFromComputeNodeOperations)
{
testOutputHelper.WriteLine("Found file: {0}", f.Path);
}
//Check to make sure the expected folder named "Shared" exists
Assert.Contains("shared", fileListFromComputeNodeOperations.Select(f => f.Path));
//
// List all node files from the compute node -- recursive true
//
List<NodeFile> fileListFromComputeNode = computeNode.ListNodeFiles(recursive: true).ToList();
foreach (NodeFile f in fileListFromComputeNodeOperations)
{
testOutputHelper.WriteLine("Found file: {0}", f.Path);
}
//Check to make sure the expected folder named "Shared" exists
Assert.Contains("shared", fileListFromComputeNode.Select(f => f.Path));
//
// Get file from operations
//
string filePathToGet = fileListFromComputeNode.First(f => !f.IsDirectory.Value && f.Properties.ContentLength > 0).Path;
testOutputHelper.WriteLine("Getting file: {0}", filePathToGet);
NodeFile computeNodeFileFromManager = batchCli.PoolOperations.GetNodeFile(poolFixture.PoolId, computeNodeId, filePathToGet);
testOutputHelper.WriteLine("Successfully retrieved file: {0}", filePathToGet);
testOutputHelper.WriteLine("---- File data: ----");
var computeNodeFileContentFromManager = computeNodeFileFromManager.ReadAsString();
testOutputHelper.WriteLine(computeNodeFileContentFromManager);
Assert.NotEmpty(computeNodeFileContentFromManager);
//
// Get file directly from operations (bypassing the properties call)
//
var computeNodeFileContentDirect = batchCli.PoolOperations.CopyNodeFileContentToString(poolFixture.PoolId, computeNodeId, filePathToGet);
testOutputHelper.WriteLine("---- File data: ----");
testOutputHelper.WriteLine(computeNodeFileContentDirect);
Assert.NotEmpty(computeNodeFileContentDirect);
//
// Get file from compute node
//
testOutputHelper.WriteLine("Getting file: {0}", filePathToGet);
NodeFile fileFromComputeNode = computeNode.GetNodeFile(filePathToGet);
testOutputHelper.WriteLine("Successfully retrieved file: {0}", filePathToGet);
testOutputHelper.WriteLine("---- File data: ----");
var computeNodeFileContentFromNode = fileFromComputeNode.ReadAsString();
testOutputHelper.WriteLine(computeNodeFileContentFromNode);
Assert.NotEmpty(computeNodeFileContentFromNode);
//
// Get file from compute node (bypassing the properties call)
//
computeNodeFileContentDirect = computeNode.CopyNodeFileContentToString(filePathToGet);
testOutputHelper.WriteLine("---- File data: ----");
testOutputHelper.WriteLine(computeNodeFileContentDirect);
Assert.NotEmpty(computeNodeFileContentDirect);
//
// NodeFile delete
//
string filePath = Path.Combine(@"workitems", jobId, "job-1", taskId, Constants.StandardOutFileName);
NodeFile nodeFile = batchCli.PoolOperations.GetNodeFile(poolFixture.PoolId, computeNodeId, filePath);
nodeFile.Delete();
//Ensure delete succeeded
TestUtilities.AssertThrows<BatchException>(() => nodeFile.Refresh());
//Delete directory
NodeFile directory = batchCli.PoolOperations.ListNodeFiles(poolFixture.PoolId, computeNodeId, recursive: true).First(item => item.Path.Contains(directoryNameOne));
Assert.True(directory.IsDirectory);
TestUtilities.AssertThrows<BatchException>(() => directory.Delete(recursive: false));
directory.Delete(recursive: true);
Assert.Null(batchCli.PoolOperations.ListNodeFiles(poolFixture.PoolId, computeNodeId, recursive: true).FirstOrDefault(item => item.Path.Contains(directoryNameOne)));
//
// PoolManager delete node file
//
filePath = Path.Combine(@"workitems", jobId, "job-1", taskId, Constants.StandardErrorFileName);
NodeFile file = batchCli.JobOperations.GetNodeFile(jobId, taskId, Constants.StandardErrorFileName);
batchCli.PoolOperations.DeleteNodeFile(poolFixture.PoolId, computeNodeId, filePath);
//Ensure delete succeeded
TestUtilities.AssertThrows<BatchException>(() => batchCli.JobOperations.GetNodeFile(jobId, taskId, Constants.StandardErrorFileName));
//Delete directory
directory = batchCli.PoolOperations.ListNodeFiles(poolFixture.PoolId, computeNodeId, recursive: true).First(item => item.Path.Contains(directoryNameTwo));
Assert.True(directory.IsDirectory);
TestUtilities.AssertThrows<BatchException>(() => batchCli.PoolOperations.DeleteNodeFile(poolFixture.PoolId, computeNodeId, directory.Path, recursive: false));
batchCli.PoolOperations.DeleteNodeFile(poolFixture.PoolId, computeNodeId, directory.Path, recursive: true);
Assert.Null(batchCli.PoolOperations.ListNodeFiles(poolFixture.PoolId, computeNodeId, recursive: true).FirstOrDefault(item => item.Path.Contains(directoryNameTwo)));
}
finally
{
batchCli.JobOperations.DeleteJob(jobId);
}
}
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void Bug2338301_CheckStreamPositionAfterFileRead()
{
void test()
{
using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
JobOperations jobOperations = batchCli.JobOperations;
{
string jobId = "Bug2338301Job-" + TestUtilities.GetMyName();
try
{
const string taskId = "hiWorld";
//
// Create the job
//
CloudJob unboundJob = jobOperations.CreateJob(jobId, new PoolInformation() { PoolId = poolFixture.PoolId });
unboundJob.Commit();
CloudJob boundJob = jobOperations.GetJob(jobId);
CloudTask myTask = new CloudTask(taskId, "cmd /c echo hello world");
boundJob.AddTask(myTask);
testOutputHelper.WriteLine("Initial job commit()");
//
// Wait for task to go to completion
//
Utilities utilities = batchCli.Utilities;
TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
boundJob.ListTasks(),
Microsoft.Azure.Batch.Common.TaskState.Completed,
TimeSpan.FromMinutes(3));
CloudTask boundTask = boundJob.GetTask(taskId);
//Get the task file
const string fileToGet = "stdout.txt";
NodeFile file = boundTask.GetNodeFile(fileToGet);
//Download the file data
string result = file.ReadAsString();
Assert.True(result.Length > 0);
}
finally
{
jobOperations.DeleteJob(jobId);
}
}
}
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void Bug1480491NodeFileFileProperties()
{
void test()
{
using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
string jobId = "Bug1480491Job-" + TestUtilities.GetMyName();
try
{
const string taskId = "hiWorld";
//
// Create the job
//
CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation());
unboundJob.PoolInformation.PoolId = poolFixture.PoolId;
unboundJob.Commit();
CloudJob boundJob = batchCli.JobOperations.GetJob(jobId);
CloudTask myTask = new CloudTask(taskId, "cmd /c echo hello world");
boundJob.AddTask(myTask);
testOutputHelper.WriteLine("Initial job commit()");
//
// Wait for task to go to completion
//
Utilities utilities = batchCli.Utilities;
TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
taskStateMonitor.WaitAll(
boundJob.ListTasks(),
Microsoft.Azure.Batch.Common.TaskState.Completed,
TimeSpan.FromMinutes(3));
const int expectedFileSize = 13; //Magic number based on output generated by the task
//
// NodeFile by task
//
NodeFile file = batchCli.JobOperations.GetNodeFile(jobId, taskId, Constants.StandardOutFileName);
testOutputHelper.WriteLine("File {0} has content length: {1}", Constants.StandardOutFileName, file.Properties.ContentLength);
testOutputHelper.WriteLine("File {0} has content type: {1}", Constants.StandardOutFileName, file.Properties.ContentType);
testOutputHelper.WriteLine("File {0} has creation time: {1}", Constants.StandardOutFileName, file.Properties.CreationTime);
testOutputHelper.WriteLine("File {0} has last modified time: {1}", Constants.StandardOutFileName, file.Properties.LastModified);
Assert.Equal(expectedFileSize, file.Properties.ContentLength);
Assert.Equal("text/plain", file.Properties.ContentType);
//
// NodeFile by node
//
CloudTask boundTask = boundJob.GetTask(taskId);
string computeNodeId = boundTask.ComputeNodeInformation.AffinityId.Split(':')[1];
ComputeNode computeNode = batchCli.PoolOperations.GetComputeNode(poolFixture.PoolId, computeNodeId);
testOutputHelper.WriteLine("Task ran on compute node: {0}", computeNodeId);
List<NodeFile> files = computeNode.ListNodeFiles(recursive: true).ToList();
foreach (NodeFile nodeFile in files)
{
testOutputHelper.WriteLine("Found file: {0}", nodeFile.Path);
}
string filePathToGet = string.Format("workitems/{0}/{1}/{2}/{3}", jobId, "job-1", taskId, Constants.StandardOutFileName);
file = computeNode.GetNodeFile(filePathToGet);
testOutputHelper.WriteLine("File {0} has content length: {1}", filePathToGet, file.Properties.ContentLength);
testOutputHelper.WriteLine("File {0} has content type: {1}", filePathToGet, file.Properties.ContentType);
testOutputHelper.WriteLine("File {0} has creation time: {1}", filePathToGet, file.Properties.CreationTime);
testOutputHelper.WriteLine("File {0} has last modified time: {1}", filePathToGet, file.Properties.LastModified);
Assert.Equal(expectedFileSize, file.Properties.ContentLength);
Assert.Equal("text/plain", file.Properties.ContentType);
}
finally
{
batchCli.JobOperations.DeleteJob(jobId);
}
}
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)]
public void TestGetNodeFileByTask()
{
void test()
{
using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
JobOperations jobOperations = batchCli.JobOperations;
string jobId = Constants.DefaultConveniencePrefix + TestUtilities.GetMyName() + "-" + nameof(TestGetNodeFileByTask);
try
{
//
// Create the job
//
CloudJob job = jobOperations.CreateJob(jobId, new PoolInformation());
job.PoolInformation = new PoolInformation()
{
PoolId = poolFixture.PoolId
};
testOutputHelper.WriteLine("Initial job schedule commit()");
job.Commit();
//
// Wait for the job
//
testOutputHelper.WriteLine("Waiting for job");
CloudJob boundJob = jobOperations.GetJob(jobId);
//
// Add task to the job
//
const string taskId = "T1";
const string taskMessage = "This is a test";
testOutputHelper.WriteLine("Adding task: {0}", taskId);
CloudTask task = new CloudTask(taskId, string.Format("cmd /c echo {0}", taskMessage));
boundJob.AddTask(task);
//
// Wait for the task to complete
//
testOutputHelper.WriteLine("Waiting for the task to complete");
Utilities utilities = batchCli.Utilities;
TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
//Wait for the task state to be running
taskStateMonitor.WaitAll(
jobOperations.ListTasks(jobId),
TaskState.Completed,
TimeSpan.FromSeconds(30));
//Download the data
testOutputHelper.WriteLine("Downloading the stdout for the file");
NodeFile file = jobOperations.GetNodeFile(jobId, taskId, Constants.StandardOutFileName);
string data = file.ReadAsString();
testOutputHelper.WriteLine("Data: {0}", data);
Assert.Contains(taskMessage, data);
// Download the data again using the JobOperations read file content helper
data = batchCli.JobOperations.CopyNodeFileContentToString(jobId, taskId, Constants.StandardOutFileName);
testOutputHelper.WriteLine("Data: {0}", data);
Assert.Contains(taskMessage, data);
}
finally
{
jobOperations.DeleteJob(jobId);
}
}
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
private static void AssertFileListsMatch(List<NodeFile> listOne, List<NodeFile> listTwo)
{
Assert.Equal(listOne.Count, listTwo.Count);
Assert.NotEmpty(listOne);
Assert.NotEmpty(listTwo);
foreach (NodeFile file in listOne)
{
//Find the corresponding file in the other list and ensure they are the same
NodeFile matchedFile = listTwo.FirstOrDefault(f => f.Path == file.Path);
Assert.NotNull(matchedFile);
//Ensure the files match
Assert.Equal(file.IsDirectory, matchedFile.IsDirectory);
if (file.Properties == null)
{
Assert.Null(file.Properties);
Assert.Null(matchedFile.Properties);
}
else
{
Assert.Equal(file.Properties.ContentLength, matchedFile.Properties.ContentLength);
Assert.Equal(file.Properties.ContentType, matchedFile.Properties.ContentType);
Assert.Equal(file.Properties.CreationTime, matchedFile.Properties.CreationTime);
Assert.Equal(file.Properties.LastModified, matchedFile.Properties.LastModified);
}
}
}
}
[Collection("SharedLinuxPoolCollection")]
public class IntegrationNodeFileLinuxTests
{
private readonly ITestOutputHelper testOutputHelper;
private readonly PoolFixture poolFixture;
private static readonly TimeSpan TestTimeout = TimeSpan.FromMinutes(2);
public IntegrationNodeFileLinuxTests(ITestOutputHelper testOutputHelper, IaasLinuxPoolFixture poolFixture)
{
this.testOutputHelper = testOutputHelper;
this.poolFixture = poolFixture;
}
[Fact]
[LiveTest]
[Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)]
public void TestFilePropertiesFileMode()
{
void test()
{
using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
string jobId = null;
try
{
// create some files on the node
TestUtilities.HelloWorld(
batchCli,
testOutputHelper,
poolFixture.Pool,
out jobId,
out string taskId,
deleteJob: false,
isLinux: true);
var nodes = poolFixture.Pool.ListComputeNodes().ToList();
ComputeNode cn = nodes[0]; // get the node that has files on it
List<NodeFile> files = cn.ListNodeFiles(recursive: true).ToList();
Assert.True(files.Count > 0);
bool foundOne = false;
// look through all the files for a filemode
foreach (NodeFile curNF in files)
{
if ((null != curNF.Properties) && !string.IsNullOrWhiteSpace(curNF.Properties.FileMode))
{
foundOne = true;
break;
}
}
Assert.True(foundOne);
}
finally
{
TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
}
}
SynchronizationContextHelper.RunTest(test, TestTimeout);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: MutexSecurity
**
**
** Purpose: Managed ACL wrapper for Win32 mutexes.
**
**
===========================================================*/
using System;
using System.Collections;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace System.Security.AccessControl
{
// Derive this list of values from winnt.h and MSDN docs:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization_object_security_and_access_rights.asp
// In order to call ReleaseMutex, you must have an ACL granting you
// MUTEX_MODIFY_STATE rights (0x0001). The other interesting value
// in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001).
// You need SYNCHRONIZE to be able to open a handle to a mutex.
[Flags]
public enum MutexRights
{
Modify = 0x000001,
Delete = 0x010000,
ReadPermissions = 0x020000,
ChangePermissions = 0x040000,
TakeOwnership = 0x080000,
Synchronize = 0x100000, // SYNCHRONIZE
FullControl = 0x1F0001
}
public sealed class MutexAccessRule : AccessRule
{
// Constructor for creating access rules for registry objects
public MutexAccessRule(IdentityReference identity, MutexRights eventRights, AccessControlType type)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
public MutexAccessRule(String identity, MutexRights eventRights, AccessControlType type)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of {File|Folder}Security
//
internal MutexAccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type )
{
}
public MutexRights MutexRights {
get { return (MutexRights) base.AccessMask; }
}
}
public sealed class MutexAuditRule : AuditRule
{
public MutexAuditRule(IdentityReference identity, MutexRights eventRights, AuditFlags flags)
: this(identity, (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
/* // Not in the spec
public MutexAuditRule(string identity, MutexRights eventRights, AuditFlags flags)
: this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags)
{
}
*/
internal MutexAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags)
{
}
public MutexRights MutexRights {
get { return (MutexRights) base.AccessMask; }
}
}
public sealed class MutexSecurity : NativeObjectSecurity
{
public MutexSecurity()
: base(true, ResourceType.KernelObject)
{
}
[System.Security.SecuritySafeCritical] // auto-generated
public MutexSecurity(String name, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, name, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
internal MutexSecurity(SafeWaitHandle handle, AccessControlSections includeSections)
: base(true, ResourceType.KernelObject, handle, includeSections, _HandleErrorCode, null)
{
// Let the underlying ACL API's demand unmanaged code permission.
}
[System.Security.SecurityCritical] // auto-generated
private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
{
System.Exception exception = null;
switch (errorCode) {
case Win32Native.ERROR_INVALID_NAME:
case Win32Native.ERROR_INVALID_HANDLE:
case Win32Native.ERROR_FILE_NOT_FOUND:
if ((name != null) && (name.Length != 0))
exception = new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
else
exception = new WaitHandleCannotBeOpenedException();
break;
default:
break;
}
return exception;
}
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
{
return new MutexAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
}
public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
{
return new MutexAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
}
internal AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified)
persistRules = AccessControlSections.Access;
if (AuditRulesModified)
persistRules |= AccessControlSections.Audit;
if (OwnerModified)
persistRules |= AccessControlSections.Owner;
if (GroupModified)
persistRules |= AccessControlSections.Group;
return persistRules;
}
[System.Security.SecurityCritical] // auto-generated
internal void Persist(SafeWaitHandle handle)
{
// Let the underlying ACL API's demand unmanaged code.
WriteLock();
try
{
AccessControlSections persistSections = GetAccessControlSectionsFromChanges();
if (persistSections == AccessControlSections.None)
return; // Don't need to persist anything.
base.Persist(handle, persistSections);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
public void AddAccessRule(MutexAccessRule rule)
{
base.AddAccessRule(rule);
}
public void SetAccessRule(MutexAccessRule rule)
{
base.SetAccessRule(rule);
}
public void ResetAccessRule(MutexAccessRule rule)
{
base.ResetAccessRule(rule);
}
public bool RemoveAccessRule(MutexAccessRule rule)
{
return base.RemoveAccessRule(rule);
}
public void RemoveAccessRuleAll(MutexAccessRule rule)
{
base.RemoveAccessRuleAll(rule);
}
public void RemoveAccessRuleSpecific(MutexAccessRule rule)
{
base.RemoveAccessRuleSpecific(rule);
}
public void AddAuditRule(MutexAuditRule rule)
{
base.AddAuditRule(rule);
}
public void SetAuditRule(MutexAuditRule rule)
{
base.SetAuditRule(rule);
}
public bool RemoveAuditRule(MutexAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
public void RemoveAuditRuleAll(MutexAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
public void RemoveAuditRuleSpecific(MutexAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
public override Type AccessRightType
{
get { return typeof(MutexRights); }
}
public override Type AccessRuleType
{
get { return typeof(MutexAccessRule); }
}
public override Type AuditRuleType
{
get { return typeof(MutexAuditRule); }
}
}
}
| |
// 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.Xml; //Required for Content Type File manipulation
using System.Diagnostics;
using System.IO.Compression;
namespace System.IO.Packaging
{
/// <summary>
/// ZipPackage is a specific implementation for the abstract Package
/// class, corresponding to the Zip file format.
/// This is a part of the Packaging Layer APIs.
/// </summary>
public sealed class ZipPackage : Package
{
#region Public Methods
#region PackagePart Methods
/// <summary>
/// This method is for custom implementation for the underlying file format
/// Adds a new item to the zip archive corresponding to the PackagePart in the package.
/// </summary>
/// <param name="partUri">PartName</param>
/// <param name="contentType">Content type of the part</param>
/// <param name="compressionOption">Compression option for this part</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentNullException">If contentType parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception>
protected override PackagePart CreatePartCore(Uri partUri,
string contentType,
CompressionOption compressionOption)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
if (contentType == null)
throw new ArgumentNullException(nameof(contentType));
Package.ThrowIfCompressionOptionInvalid(compressionOption);
// Convert Metro CompressionOption to Zip CompressionMethodEnum.
CompressionLevel level;
GetZipCompressionMethodFromOpcCompressionOption(compressionOption,
out level);
// Create new Zip item.
// We need to remove the leading "/" character at the beginning of the part name.
// The partUri object must be a ValidatedPartUri
string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1);
ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level);
//Store the content type of this part in the content types stream.
_contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level);
return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Returns the part after reading the actual physical bits. The method
/// returns a null to indicate that the part corresponding to the specified
/// Uri was not found in the container.
/// This method does not throw an exception if a part does not exist.
/// </summary>
/// <param name="partUri"></param>
/// <returns></returns>
protected override PackagePart GetPartCore(Uri partUri)
{
//Currently the design has two aspects which makes it possible to return
//a null from this method -
// 1. All the parts are loaded at Package.Open time and as such, this
// method would not be invoked, unless the user is asking for -
// i. a part that does not exist - we can safely return null
// ii.a part(interleaved/non-interleaved) that was added to the
// underlying package by some other means, and the user wants to
// access the updated part. This is currently not possible as the
// underlying zip i/o layer does not allow for FileShare.ReadWrite.
// 2. Also, its not a straightforward task to determine if a new part was
// added as we need to look for atomic as well as interleaved parts and
// this has to be done in a case sensitive manner. So, effectively
// we will have to go through the entire list of zip items to determine
// if there are any updates.
// If ever the design changes, then this method must be updated accordingly
return null;
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Deletes the part corresponding to the uri specified. Deleting a part that does not
/// exists is not an error and so we do not throw an exception in that case.
/// </summary>
/// <param name="partUri"></param>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
protected override void DeletePartCore(Uri partUri)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri));
ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName);
if (zipArchiveEntry != null)
{
// Case of an atomic part.
zipArchiveEntry.Delete();
}
//Delete the content type for this part if it was specified as an override
_contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// This is the method that knows how to get the actual parts from the underlying
/// zip archive.
/// </summary>
/// <remarks>
/// <para>
/// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates
/// the Uri of the proper part name and the ZipFileInfo of the initial piece.
/// This function does not go through the extra work of checking piece naming validity
/// throughout the package.
/// </para>
/// <para>
/// This means that interleaved parts without an initial piece will be silently ignored.
/// Other naming anomalies get caught at the Stream level when an I/O operation involves
/// an anomalous or missing piece.
/// </para>
/// <para>
/// This function reads directly from the underlying IO layer and is supposed to be called
/// just once in the lifetime of a package (at init time).
/// </para>
/// </remarks>
/// <returns>An array of ZipPackagePart.</returns>
protected override PackagePart[] GetPartsCore()
{
List<PackagePart> parts = new List<PackagePart>(InitialPartListSize);
// The list of files has to be searched linearly (1) to identify the content type
// stream, and (2) to identify parts.
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries;
// We have already identified the [ContentTypes].xml pieces if any are present during
// the initialization of ZipPackage object
// Record parts and ignored items.
foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries)
{
//Returns false if -
// a. its a content type item
// b. items that have either a leading or trailing slash.
if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName))
{
Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative);
PackUriHelper.ValidatedPartUri validatedPartUri;
if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri))
{
ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri);
if (contentType != null)
{
// In case there was some redundancy between pieces and/or the atomic
// part, it will be detected at this point because the part's Uri (which
// is independent of interleaving) will already be in the dictionary.
parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry,
_zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry)));
}
}
//If not valid part uri we can completely ignore this zip file item. Even if later someone adds
//a new part, the corresponding zip item can never map to one of these items
}
// If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item
// starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later
// a new part gets added, its corresponding zip item cannot map to one of these items.
}
return parts.ToArray();
}
#endregion PackagePart Methods
#region Other Methods
/// <summary>
/// This method is for custom implementation corresponding to the underlying zip file format.
/// </summary>
protected override void FlushCore()
{
//Save the content type file to the archive.
_contentTypeHelper.SaveToFile();
}
/// <summary>
/// Closes the underlying ZipArchive object for this container
/// </summary>
/// <param name="disposing">True if called during Dispose, false if called during Finalize</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_contentTypeHelper != null)
{
_contentTypeHelper.SaveToFile();
}
if (_zipStreamManager != null)
{
_zipStreamManager.Dispose();
}
if (_zipArchive != null)
{
_zipArchive.Dispose();
}
// _containerStream may be opened given a file name, in which case it should be closed here.
// _containerStream may be passed into the constructor, in which case, it should not be closed here.
if (_shouldCloseContainerStream)
{
_containerStream.Dispose();
}
else
{
}
_containerStream = null;
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Other Methods
#endregion Public Methods
#region Internal Constructors
/// <summary>
/// Internal constructor that is called by the OpenOnFile static method.
/// </summary>
/// <param name="path">File path to the container.</param>
/// <param name="packageFileMode">Container is opened in the specified mode if possible</param>
/// <param name="packageFileAccess">Container is opened with the specified access if possible</param>
/// <param name="share">Container is opened with the specified share if possible</param>
internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
_containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share);
_shouldCloseContainerStream = true;
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager);
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
/// <summary>
/// Internal constructor that is called by the Open(Stream) static methods.
/// </summary>
/// <param name="s"></param>
/// <param name="packageFileMode"></param>
/// <param name="packageFileAccess"></param>
internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
if (s.CanSeek)
{
switch (packageFileMode)
{
case FileMode.Open:
if (s.Length == 0)
{
throw new FileFormatException(SR.ZipZeroSizeFileIsNotValidArchive);
}
break;
case FileMode.CreateNew:
if (s.Length != 0)
{
throw new IOException(SR.CreateNewOnNonEmptyStream);
}
break;
case FileMode.Create:
if (s.Length != 0)
{
s.SetLength(0); // Discard existing data
}
break;
}
}
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager);
}
catch (InvalidDataException)
{
throw new FileFormatException("File contains corrupted data.");
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_containerStream = s;
_shouldCloseContainerStream = false;
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
#endregion Internal Constructors
#region Internal Methods
// More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names.
internal static string GetZipItemNameFromOpcName(string opcName)
{
Debug.Assert(opcName != null && opcName.Length > 0);
return opcName.Substring(1);
}
// More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names.
internal static string GetOpcNameFromZipItemName(string zipItemName)
{
return String.Concat(ForwardSlashString, zipItemName);
}
// Convert from Metro CompressionOption to ZipFileInfo compression properties.
internal static void GetZipCompressionMethodFromOpcCompressionOption(
CompressionOption compressionOption,
out CompressionLevel compressionLevel)
{
switch (compressionOption)
{
case CompressionOption.NotCompressed:
{
compressionLevel = CompressionLevel.NoCompression;
}
break;
case CompressionOption.Normal:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Maximum:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Fast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
case CompressionOption.SuperFast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
// fall-through is not allowed
default:
{
Debug.Assert(false, "Encountered an invalid CompressionOption enum value");
goto case CompressionOption.NotCompressed;
}
}
}
#endregion Internal Methods
internal FileMode PackageFileMode
{
get
{
return _packageFileMode;
}
}
#region Private Methods
//returns a boolean indicating if the underlying zip item is a valid metro part or piece
// This mainly excludes the content type item, as well as entries with leading or trailing
// slashes.
private bool IsZipItemValidOpcPartOrPiece(string zipItemName)
{
Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null");
//check if the zip item is the Content type item -case sensitive comparison
// The following test will filter out an atomic content type file, with name
// "[Content_Types].xml", as well as an interleaved one, with piece names such as
// "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece".
if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase))
return false;
else
{
//Could be an empty zip folder
//We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive
//Some of the tools support this and some don't. There is no way ensure that the zip item never have
//a leading "/", although this is a requirement we impose on items created through our API
//Therefore we ignore them at the packaging api level.
if (zipItemName.StartsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
//This will ignore the folder entries found in the zip package created by some zip tool
//PartNames ending with a "/" slash is also invalid so we are skipping these entries,
//this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a
// partname ending with a "/"
if (zipItemName.EndsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
else
return true;
}
}
// convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption
private static CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo)
{
// Note: we can't determine compression method / level from the ZipArchiveEntry.
CompressionOption result = CompressionOption.Normal;
return result;
}
#endregion Private Methods
#region Private Members
private const int InitialPartListSize = 50;
private const int InitialPieceNameListSize = 50;
private ZipArchive _zipArchive;
private Stream _containerStream; // stream we are opened in if Open(Stream) was called
private bool _shouldCloseContainerStream;
private ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container
private ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times
private FileAccess _packageFileAccess;
private FileMode _packageFileMode;
private const string ForwardSlashString = "/"; //Required for creating a part name from a zip item name
//IEqualityComparer for extensions
private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer();
#endregion Private Members
/// <summary>
/// ExtensionComparer
/// The Extensions are stored in the Default Dictionary in their original form,
/// however they are compared in a normalized manner.
/// Equivalence for extensions in the content type stream, should follow
/// the same rules as extensions of partnames. Also, by the time this code is invoked,
/// we have already validated, that the extension is in the correct format as per the
/// part name rules.So we are simplifying the logic here to just convert the extensions
/// to Upper invariant form and then compare them.
/// </summary>
private sealed class ExtensionEqualityComparer : IEqualityComparer<string>
{
bool IEqualityComparer<string>.Equals(string extensionA, string extensionB)
{
Debug.Assert(extensionA != null, "extension should not be null");
Debug.Assert(extensionB != null, "extension should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return (String.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0);
}
int IEqualityComparer<string>.GetHashCode(string extension)
{
Debug.Assert(extension != null, "extension should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return extension.ToUpperInvariant().GetHashCode();
}
}
/// <summary>
/// This is a helper class that maintains the Content Types File related to
/// this ZipPackage.
/// </summary>
private class ContentTypeHelper
{
/// <summary>
/// Initialize the object without uploading any information from the package.
/// Complete initialization in read mode also involves calling ParseContentTypesFile
/// to deserialize content type information.
/// </summary>
internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager)
{
_zipArchive = zipArchive; //initialized in the ZipPackage constructor
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
_zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor
// The extensions are stored in the default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary = new Dictionary<string, ContentType>(s_defaultDictionaryInitialSize, s_extensionEqualityComparer);
// Identify the content type file or files before identifying parts and piece sequences.
// This is necessary because the name of the content type stream is not a part name and
// the information it contains is needed to recognize valid parts.
if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update)
ParseContentTypesFile(_zipArchive.Entries);
//No contents to persist to the disk -
_dirty = false; //by default
//Lazy initialize these members as required
//_overrideDictionary - Overrides should be rare
//_contentTypeFileInfo - We will either find an atomin part, or
//_contentTypeStreamPieces - an interleaved part
//_contentTypeStreamExists - defaults to false - not yet found
}
internal static string ContentTypeFileName
{
get
{
return s_contentTypesFile;
}
}
//Adds the Default entry if it is the first time we come across
//the extension for the partUri, does nothing if the content type
//corresponding to the default entry for the extension matches or
//adds a override corresponding to this part and content type.
//This call is made when a new part is being added to the package.
// This method assumes the partUri is valid.
internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType,
CompressionLevel compressionLevel)
{
//save the compressionOption and deflateOption that should be used
//to create the content type item later
if (!_contentTypeStreamExists)
{
_cachedCompressionLevel = compressionLevel;
}
// Figure out whether the mapping matches a default entry, can be made into a new
// default entry, or has to be entered as an override entry.
bool foundMatchingDefault = false;
string extension = partUri.PartUriExtension;
// Need to create an override entry?
if (extension.Length == 0
|| (_defaultDictionary.ContainsKey(extension)
&& !(foundMatchingDefault =
_defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType))))
{
AddOverrideElement(partUri, contentType);
}
// Else, either there is already a mapping from extension to contentType,
// or one needs to be created.
else if (!foundMatchingDefault)
{
AddDefaultElement(extension, contentType);
}
}
//Returns the content type for the part, if present, else returns null.
internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri)
{
//Step 1: Check if there is an override entry present corresponding to the
//partUri provided. Override takes precedence over the default entries
if (_overrideDictionary != null)
{
if (_overrideDictionary.ContainsKey(partUri))
return _overrideDictionary[partUri];
}
//Step 2: Check if there is a default entry corresponding to the
//extension of the partUri provided.
string extension = partUri.PartUriExtension;
if (_defaultDictionary.ContainsKey(extension))
return _defaultDictionary[extension];
//Step 3: If we did not find an entry in the override and the default
//dictionaries, this is an error condition
return null;
}
//Deletes the override entry corresponding to the partUri, if it exists
internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri)
{
if (_overrideDictionary != null)
{
if (_overrideDictionary.Remove(partUri))
_dirty = true;
}
}
internal void SaveToFile()
{
if (_dirty)
{
//Lazy init: Initialize when the first part is added.
if (!_contentTypeStreamExists)
{
_contentTypeZipArchiveEntry = _zipArchive.CreateEntry(s_contentTypesFile, _cachedCompressionLevel);
_contentTypeStreamExists = true;
}
// delete and re-create entry for content part. When writing this, the stream will not truncate the content
// if the XML is shorter than the existing content part.
var contentTypefullName = _contentTypeZipArchiveEntry.FullName;
var thisArchive = _contentTypeZipArchiveEntry.Archive;
_zipStreamManager.Close(_contentTypeZipArchiveEntry);
_contentTypeZipArchiveEntry.Delete();
_contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName);
using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite))
{
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// write root element tag - Types
writer.WriteStartElement(s_typesTagName, s_typesNamespaceUri);
// for each default entry
foreach (string key in _defaultDictionary.Keys)
{
WriteDefaultElement(writer, key, _defaultDictionary[key]);
}
if (_overrideDictionary != null)
{
// for each override entry
foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys)
{
WriteOverrideElement(writer, key, _overrideDictionary[key]);
}
}
// end of Types tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
_dirty = false;
}
}
}
}
private void EnsureOverrideDictionary()
{
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using the PartUriComparer
if (_overrideDictionary == null)
_overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(s_overrideDictionaryInitialSize);
}
private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
// Find the content type stream, allowing for interleaving. Naming collisions
// (as between an atomic and an interleaved part) will result in an exception being thrown.
Stream s = OpenContentTypeStream(zipFiles);
// Allow non-existent content type stream.
if (s == null)
return;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.IgnoreWhitespace = true;
using (s)
using (XmlReader reader = XmlReader.Create(s, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our root tag and namespace pair - ignore others in case of version changes
// Make sure that the current node read is an Element
if ((reader.NodeType == XmlNodeType.Element)
&& (reader.Depth == 0)
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_typesTagName) == 0))
{
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
{
throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// start tag encountered
// now parse individual Default and Override tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
// Make sure that the current node read is an element
// Currently we expect the Default and Override Tag at Depth 1
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_defaultTagName) == 0))
{
ProcessDefaultTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (String.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (String.CompareOrdinal(reader.Name, s_overrideTagName) == 0))
{
ProcessOverrideTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && String.CompareOrdinal(reader.Name, s_typesTagName) == 0)
continue;
else
{
throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
else
{
throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
/// <summary>
/// Find the content type stream, allowing for interleaving. Naming collisions
/// (as between an atomic and an interleaved part) will result in an exception being thrown.
/// Return null if no content type stream has been found.
/// </summary>
/// <remarks>
/// The input array is lexicographically sorted
/// </remarks>
private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
foreach (ZipArchiveEntry zipFileInfo in zipFiles)
{
if (zipFileInfo.Name.ToUpperInvariant().StartsWith(s_contentTypesFileUpperInvariant, StringComparison.Ordinal))
{
// Atomic name.
if (zipFileInfo.Name.Length == ContentTypeFileName.Length)
{
// Record the file info.
_contentTypeZipArchiveEntry = zipFileInfo;
}
}
}
// If an atomic file was found, open a stream on it.
if (_contentTypeZipArchiveEntry != null)
{
_contentTypeStreamExists = true;
return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite);
}
// No content type stream was found.
return null;
}
// Process the attributes for the Default tag
private void ProcessDefaultTagAttributes(XmlReader reader)
{
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string extensionAttributeValue = reader.GetAttribute(s_extensionAttributeName);
ValidateXmlAttribute(s_extensionAttributeName, extensionAttributeValue, s_defaultTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_defaultTagName, reader);
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri(
new Uri(s_temporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative));
_defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Default Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_defaultTagName);
}
// Process the attributes for the Default tag
private void ProcessOverrideTagAttributes(XmlReader reader)
{
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string partNameAttributeValue = reader.GetAttribute(s_partNameAttributeName);
ValidateXmlAttribute(s_partNameAttributeName, partNameAttributeValue, s_overrideTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_overrideTagName, reader);
PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative));
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Override Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_overrideTagName);
}
//If End element is present for Relationship then we process it
private void ProcessEndElement(XmlReader reader, string elementName)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && String.CompareOrdinal(elementName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
//Delete any entry corresponding in the Override dictionary
//corresponding to the PartUri for which the contentType is being added.
//This is to compensate for dead override entries in the content types file.
DeleteContentType(partUri);
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, contentType);
_dirty = true;
}
private void AddDefaultElement(string extension, ContentType contentType)
{
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary.Add(extension, contentType);
_dirty = true;
}
private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
xmlWriter.WriteStartElement(s_overrideTagName);
xmlWriter.WriteAttributeString(s_partNameAttributeName,
partUri.PartUriString);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType)
{
xmlWriter.WriteStartElement(s_defaultTagName);
xmlWriter.WriteAttributeString(s_extensionAttributeName, extension);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
//Validate if the required XML attribute is present and not an empty string
private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader);
//Checking for empty attribute
if (attributeValue == String.Empty)
throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
//Validate if the required Content type XML attribute is present
//Content type of a part can be empty
private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
if (attributeValue == null)
throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary;
private Dictionary<string, ContentType> _defaultDictionary;
private ZipArchive _zipArchive;
private FileMode _packageFileMode;
private FileAccess _packageFileAccess;
private ZipStreamManager _zipStreamManager;
private ZipArchiveEntry _contentTypeZipArchiveEntry;
private bool _contentTypeStreamExists;
private bool _dirty;
private CompressionLevel _cachedCompressionLevel;
private static readonly string s_contentTypesFile = "[Content_Types].xml";
private static readonly string s_contentTypesFileUpperInvariant = "[CONTENT_TYPES].XML";
private static readonly int s_defaultDictionaryInitialSize = 16;
private static readonly int s_overrideDictionaryInitialSize = 8;
//Xml tag specific strings for the Content Type file
private static readonly string s_typesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types";
private static readonly string s_typesTagName = "Types";
private static readonly string s_defaultTagName = "Default";
private static readonly string s_extensionAttributeName = "Extension";
private static readonly string s_contentTypeAttributeName = "ContentType";
private static readonly string s_overrideTagName = "Override";
private static readonly string s_partNameAttributeName = "PartName";
private static readonly string s_temporaryPartNameWithoutExtension = "/tempfiles/sample.";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis
{
partial class ConnectionMultiplexer
{
private readonly Dictionary<RedisChannel, Subscription> subscriptions = new Dictionary<RedisChannel, Subscription>();
internal static bool TryCompleteHandler<T>(EventHandler<T> handler, object sender, T args, bool isAsync) where T : EventArgs
{
if (handler == null) return true;
if (isAsync)
{
foreach (EventHandler<T> sub in handler.GetInvocationList())
{
try
{ sub.Invoke(sender, args); }
catch
{ }
}
return true;
}
return false;
}
internal Task AddSubscription(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags, object asyncState)
{
if (handler != null)
{
lock (subscriptions)
{
Subscription sub;
if (subscriptions.TryGetValue(channel, out sub))
{
sub.Add(handler);
}
else
{
sub = new Subscription(handler);
subscriptions.Add(channel, sub);
var task = sub.SubscribeToServer(this, channel, flags, asyncState, false);
if (task != null) return task;
}
}
}
return CompletedTask<bool>.Default(asyncState);
}
internal ServerEndPoint GetSubscribedServer(RedisChannel channel)
{
if (!channel.IsNullOrEmpty)
{
lock (subscriptions)
{
Subscription sub;
if (subscriptions.TryGetValue(channel, out sub))
{
return sub.GetOwner();
}
}
}
return null;
}
internal void OnMessage(RedisChannel subscription, RedisChannel channel, RedisValue payload)
{
ICompletable completable = null;
lock (subscriptions)
{
Subscription sub;
if (subscriptions.TryGetValue(subscription, out sub))
{
completable = sub.ForInvoke(channel, payload);
}
}
if (completable != null) unprocessableCompletionManager.CompleteSyncOrAsync(completable);
}
internal Task RemoveAllSubscriptions(CommandFlags flags, object asyncState)
{
Task last = CompletedTask<bool>.Default(asyncState);
lock (subscriptions)
{
foreach (var pair in subscriptions)
{
pair.Value.Remove(null); // always wipes
var task = pair.Value.UnsubscribeFromServer(pair.Key, flags, asyncState, false);
if (task != null) last = task;
}
subscriptions.Clear();
}
return last;
}
internal Task RemoveSubscription(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags, object asyncState)
{
lock (subscriptions)
{
Subscription sub;
if (subscriptions.TryGetValue(channel, out sub))
{
if (sub.Remove(handler))
{
subscriptions.Remove(channel);
var task = sub.UnsubscribeFromServer(channel, flags, asyncState, false);
if (task != null) return task;
}
}
}
return CompletedTask<bool>.Default(asyncState);
}
internal void ResendSubscriptions(ServerEndPoint server)
{
if (server == null) return;
lock (subscriptions)
{
foreach (var pair in subscriptions)
{
pair.Value.Resubscribe(pair.Key, server);
}
}
}
internal bool SubscriberConnected(RedisChannel channel = default(RedisChannel))
{
var server = GetSubscribedServer(channel);
if (server != null) return server.IsConnected;
server = SelectServer(-1, RedisCommand.SUBSCRIBE, CommandFlags.DemandMaster, default(RedisKey));
return server != null && server.IsConnected;
}
internal long ValidateSubscriptions()
{
lock (subscriptions)
{
long count = 0;
foreach (var pair in subscriptions)
{
if (pair.Value.Validate(this, pair.Key)) count++;
}
return count;
}
}
private sealed class Subscription
{
private Action<RedisChannel, RedisValue> handler;
private ServerEndPoint owner;
public Subscription(Action<RedisChannel, RedisValue> value)
{
handler = value;
}
public void Add(Action<RedisChannel, RedisValue> value)
{
handler += value;
}
public ICompletable ForInvoke(RedisChannel channel, RedisValue message)
{
var tmp = handler;
return tmp == null ? null : new MessageCompletable(channel, message, tmp);
}
public bool Remove(Action<RedisChannel, RedisValue> value)
{
if (value == null)
{ // treat as blanket wipe
handler = null;
return true;
}
else
{
return (handler -= value) == null;
}
}
public Task SubscribeToServer(ConnectionMultiplexer multiplexer, RedisChannel channel, CommandFlags flags, object asyncState, bool internalCall)
{
var cmd = channel.IsPatternBased ? RedisCommand.PSUBSCRIBE : RedisCommand.SUBSCRIBE;
var selected = multiplexer.SelectServer(-1, cmd, CommandFlags.DemandMaster, default(RedisKey));
if (selected == null || Interlocked.CompareExchange(ref owner, selected, null) != null) return null;
var msg = Message.Create(-1, flags, cmd, channel);
return selected.QueueDirectAsync(msg, ResultProcessor.TrackSubscriptions, asyncState);
}
public Task UnsubscribeFromServer(RedisChannel channel, CommandFlags flags, object asyncState, bool internalCall)
{
var oldOwner = Interlocked.Exchange(ref owner, null);
if (oldOwner == null) return null;
var cmd = channel.IsPatternBased ? RedisCommand.PUNSUBSCRIBE : RedisCommand.UNSUBSCRIBE;
var msg = Message.Create(-1, flags, cmd, channel);
if (internalCall) msg.SetInternalCall();
return oldOwner.QueueDirectAsync(msg, ResultProcessor.TrackSubscriptions, asyncState);
}
internal ServerEndPoint GetOwner()
{
return Interlocked.CompareExchange(ref owner, null, null);
}
internal void Resubscribe(RedisChannel channel, ServerEndPoint server)
{
if (server != null && Interlocked.CompareExchange(ref owner, server, server) == server)
{
var cmd = channel.IsPatternBased ? RedisCommand.PSUBSCRIBE : RedisCommand.SUBSCRIBE;
var msg = Message.Create(-1, CommandFlags.FireAndForget, cmd, channel);
msg.SetInternalCall();
server.QueueDirectFireAndForget(msg, ResultProcessor.TrackSubscriptions);
}
}
internal bool Validate(ConnectionMultiplexer multiplexer, RedisChannel channel)
{
bool changed = false;
var oldOwner = Interlocked.CompareExchange(ref owner, null, null);
if (oldOwner != null && !oldOwner.IsSelectable(RedisCommand.PSUBSCRIBE))
{
if (UnsubscribeFromServer(channel, CommandFlags.FireAndForget, null, true) != null)
{
changed = true;
}
oldOwner = null;
}
if (oldOwner == null)
{
if (SubscribeToServer(multiplexer, channel, CommandFlags.FireAndForget, null, true) != null)
{
changed = true;
}
}
return changed;
}
}
}
internal sealed class RedisSubscriber : RedisBase, ISubscriber
{
internal RedisSubscriber(ConnectionMultiplexer multiplexer, object asyncState) : base(multiplexer, asyncState)
{
}
public EndPoint IdentifyEndpoint(RedisChannel channel, CommandFlags flags = CommandFlags.None)
{
var msg = Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.NUMSUB, channel);
msg.SetInternalCall();
return ExecuteSync(msg, ResultProcessor.ConnectionIdentity);
}
public Task<EndPoint> IdentifyEndpointAsync(RedisChannel channel, CommandFlags flags = CommandFlags.None)
{
var msg = Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.NUMSUB, channel);
msg.SetInternalCall();
return ExecuteAsync(msg, ResultProcessor.ConnectionIdentity);
}
public bool IsConnected(RedisChannel channel = default(RedisChannel))
{
return multiplexer.SubscriberConnected(channel);
}
public override TimeSpan Ping(CommandFlags flags = CommandFlags.None)
{
// can't use regular PING, but we can unsubscribe from something random that we weren't even subscribed to...
RedisValue channel = Guid.NewGuid().ToByteArray();
var msg = ResultProcessor.TimingProcessor.CreateMessage(-1, flags, RedisCommand.UNSUBSCRIBE, channel);
return ExecuteSync(msg, ResultProcessor.ResponseTimer);
}
public override Task<TimeSpan> PingAsync(CommandFlags flags = CommandFlags.None)
{
// can't use regular PING, but we can unsubscribe from something random that we weren't even subscribed to...
RedisValue channel = Guid.NewGuid().ToByteArray();
var msg = ResultProcessor.TimingProcessor.CreateMessage(-1, flags, RedisCommand.UNSUBSCRIBE, channel);
return ExecuteAsync(msg, ResultProcessor.ResponseTimer);
}
public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{
if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
var msg = Message.Create(-1, flags, RedisCommand.PUBLISH, channel, message);
return ExecuteSync(msg, ResultProcessor.Int64);
}
public Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None)
{
if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
var msg = Message.Create(-1, flags, RedisCommand.PUBLISH, channel, message);
return ExecuteAsync(msg, ResultProcessor.Int64);
}
public void Subscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags = CommandFlags.None)
{
var task = SubscribeAsync(channel, handler, flags);
if ((flags & CommandFlags.FireAndForget) == 0) Wait(task);
}
public Task SubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler, CommandFlags flags = CommandFlags.None)
{
if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
return multiplexer.AddSubscription(channel, handler, flags, asyncState);
}
public EndPoint SubscribedEndpoint(RedisChannel channel)
{
var server = multiplexer.GetSubscribedServer(channel);
return server?.EndPoint;
}
public void Unsubscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None)
{
var task = UnsubscribeAsync(channel, handler, flags);
if ((flags & CommandFlags.FireAndForget) == 0) Wait(task);
}
public void UnsubscribeAll(CommandFlags flags = CommandFlags.None)
{
var task = UnsubscribeAllAsync(flags);
if ((flags & CommandFlags.FireAndForget) == 0) Wait(task);
}
public Task UnsubscribeAllAsync(CommandFlags flags = CommandFlags.None)
{
return multiplexer.RemoveAllSubscriptions(flags, asyncState);
}
public Task UnsubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handler = null, CommandFlags flags = CommandFlags.None)
{
if (channel.IsNullOrEmpty) throw new ArgumentNullException(nameof(channel));
return multiplexer.RemoveSubscription(channel, handler, flags, asyncState);
}
}
}
| |
// 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 Microsoft.Win32;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Diagnostics
{
internal sealed class PerformanceCounterLib
{
private static volatile string s_computerName;
private PerformanceMonitor _performanceMonitor;
private string _machineName;
private string _perfLcid;
private static volatile Dictionary<String, PerformanceCounterLib> s_libraryTable;
private Dictionary<int, string> _nameTable;
private readonly object _nameTableLock = new Object();
private static Object s_internalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_internalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange(ref s_internalSyncObject, o, null);
}
return s_internalSyncObject;
}
}
internal PerformanceCounterLib(string machineName, string lcid)
{
_machineName = machineName;
_perfLcid = lcid;
}
/// <internalonly/>
internal static string ComputerName
{
get
{
if (s_computerName == null)
{
lock (InternalSyncObject)
{
if (s_computerName == null)
{
s_computerName = Interop.mincore.GetComputerName();
}
}
}
return s_computerName;
}
}
internal Dictionary<int, string> NameTable
{
get
{
if (_nameTable == null)
{
lock (_nameTableLock)
{
if (_nameTable == null)
_nameTable = GetStringTable(false);
}
}
return _nameTable;
}
}
internal string GetCounterName(int index)
{
string result;
return NameTable.TryGetValue(index, out result) ? result : "";
}
internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
{
string lcidString = culture.Name.ToLowerInvariant();
if (machineName.CompareTo(".") == 0)
machineName = ComputerName.ToLowerInvariant();
else
machineName = machineName.ToLowerInvariant();
if (PerformanceCounterLib.s_libraryTable == null)
{
lock (InternalSyncObject)
{
if (PerformanceCounterLib.s_libraryTable == null)
PerformanceCounterLib.s_libraryTable = new Dictionary<string, PerformanceCounterLib>();
}
}
string libraryKey = machineName + ":" + lcidString;
PerformanceCounterLib library;
if (!PerformanceCounterLib.s_libraryTable.TryGetValue(libraryKey, out library))
{
library = new PerformanceCounterLib(machineName, lcidString);
PerformanceCounterLib.s_libraryTable[libraryKey] = library;
}
return library;
}
internal byte[] GetPerformanceData(string item)
{
if (_performanceMonitor == null)
{
lock (InternalSyncObject)
{
if (_performanceMonitor == null)
_performanceMonitor = new PerformanceMonitor(_machineName);
}
}
return _performanceMonitor.GetData(item);
}
private Dictionary<int, string> GetStringTable(bool isHelp)
{
Dictionary<int, string> stringTable;
RegistryKey libraryKey;
libraryKey = Registry.PerformanceData;
try
{
string[] names = null;
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// In some stress situations, querying counter values from
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009
// often returns null/empty data back. We should build fault-tolerance logic to
// make it more reliable because getting null back once doesn't necessarily mean
// that the data is corrupted, most of the time we would get the data just fine
// in subsequent tries.
while (waitRetries > 0)
{
try
{
if (!isHelp)
names = (string[])libraryKey.GetValue("Counter " + _perfLcid);
else
names = (string[])libraryKey.GetValue("Explain " + _perfLcid);
if ((names == null) || (names.Length == 0))
{
--waitRetries;
if (waitSleep == 0)
waitSleep = 10;
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
else
break;
}
catch (IOException)
{
// RegistryKey throws if it can't find the value. We want to return an empty table
// and throw a different exception higher up the stack.
names = null;
break;
}
catch (InvalidCastException)
{
// Unable to cast object of type 'System.Byte[]' to type 'System.String[]'.
// this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ
names = null;
break;
}
}
if (names == null)
stringTable = new Dictionary<int, string>();
else
{
stringTable = new Dictionary<int, string>(names.Length / 2);
for (int index = 0; index < (names.Length / 2); ++index)
{
string nameString = names[(index * 2) + 1];
if (nameString == null)
nameString = String.Empty;
int key;
if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key))
{
if (isHelp)
{
// Category Help Table
throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2]));
}
else
{
// Counter Name Table
throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2]));
}
}
stringTable[key] = nameString;
}
}
}
finally
{
libraryKey.Dispose();
}
return stringTable;
}
internal class PerformanceMonitor
{
private RegistryKey _perfDataKey = null;
private string _machineName;
internal PerformanceMonitor(string machineName)
{
_machineName = machineName;
Init();
}
private void Init()
{
_perfDataKey = Registry.PerformanceData;
}
// Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some
// scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY,
// ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the
// wait loop and switch case below). We want to wait most certainly more than a 2min window.
// The current wait time of up to 10mins takes care of the known stress deadlock issues. In most
// cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time
// we wait may not be sufficient if the Win32 code keeps running into this deadlock again
// and again. A condition very rare but possible in theory. We would get back to the user
// in this case with InvalidOperationException after the wait time expires.
internal byte[] GetData(string item)
{
int waitRetries = 17; //2^16*10ms == approximately 10mins
int waitSleep = 0;
byte[] data = null;
int error = 0;
while (waitRetries > 0)
{
try
{
data = (byte[])_perfDataKey.GetValue(item);
return data;
}
catch (IOException e)
{
error = Marshal.GetHRForException(e);
switch (error)
{
case Interop.mincore.RPCStatus.RPC_S_CALL_FAILED:
case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
case Interop.mincore.RPCStatus.RPC_S_SERVER_UNAVAILABLE:
Init();
goto case Interop.mincore.WaitOptions.WAIT_TIMEOUT;
case Interop.mincore.WaitOptions.WAIT_TIMEOUT:
case Interop.mincore.Errors.ERROR_NOT_READY:
case Interop.mincore.Errors.ERROR_LOCK_FAILED:
case Interop.mincore.Errors.ERROR_BUSY:
--waitRetries;
if (waitSleep == 0)
{
waitSleep = 10;
}
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
break;
default:
throw new Win32Exception(error);
}
}
catch (InvalidCastException e)
{
throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, _perfDataKey.ToString()), e);
}
}
throw new Win32Exception(error);
}
}
}
}
| |
using System;
using Xunit;
namespace VulkanCore.Tests
{
public unsafe class InteropTest
{
[Fact]
public void AllocZeroBytes()
{
IntPtr handle = Interop.Alloc(0);
Assert.Equal(IntPtr.Zero, handle);
}
[Fact]
public void AllocStringToPtr()
{
const string value = "hi"; // 0x68 + 0x69
IntPtr handle = IntPtr.Zero;
try
{
handle = Interop.String.AllocToPointer(value);
var ptr = (byte*)handle;
Assert.Equal(0x68, ptr[0]); // 'h'
Assert.Equal(0x69, ptr[1]); // 'i'
Assert.Equal(0x00, ptr[2]); // '\0' - null-terminator
}
finally
{
Interop.Free(handle);
}
}
[Fact]
public void AllocEmptyStringToPtr()
{
const string value = "";
IntPtr handle = IntPtr.Zero;
try
{
handle = Interop.String.AllocToPointer(value);
var ptr = (byte*)handle;
Assert.Equal(0x00, ptr[0]); // '\0' - null-terminator
}
finally
{
Interop.Free(handle);
}
}
[Fact]
public void AllocNullStringToPtr()
{
IntPtr handle = Interop.String.AllocToPointer(null);
Assert.Equal(IntPtr.Zero, handle);
}
[Fact]
public void StringToPtr()
{
const string str = "hi"; // 0x68 + 0x69
int count = Interop.String.GetMaxByteCount(str);
var bytes = stackalloc byte[count];
Interop.String.ToPointer(str, bytes, count);
Assert.Equal(0x68, bytes[0]);
Assert.Equal(0x69, bytes[1]);
Assert.Equal(0, bytes[2]);
}
[Fact]
public void EmptyStringToPtr()
{
const string str = "";
int count = Interop.String.GetMaxByteCount(str);
var bytes = stackalloc byte[count];
Interop.String.ToPointer(str, bytes, count);
Assert.Equal(0, bytes[0]);
}
[Fact]
public void NullStringToPtr()
{
const string str = null;
int count = Interop.String.GetMaxByteCount(str);
var bytes = stackalloc byte[count];
Interop.String.ToPointer(str, bytes, count);
Assert.Equal(0, count);
}
[Fact]
public void NullPtrToString()
{
string value = Interop.String.FromPointer(null);
Assert.Null(value);
}
[Fact]
public void PtrToEmptyString()
{
const string value = "";
IntPtr handle = IntPtr.Zero;
try
{
handle = Interop.String.AllocToPointer(value);
string unmarshalledValue = Interop.String.FromPointer(handle);
Assert.Equal(value, unmarshalledValue);
}
finally
{
Interop.Free(handle);
}
}
[Fact]
public void PtrToString()
{
const string value = "hi";
IntPtr handle = IntPtr.Zero;
try
{
handle = Interop.String.AllocToPointer(value);
string unmarshalledValue = Interop.String.FromPointer(handle);
Assert.Equal(value, unmarshalledValue);
}
finally
{
Interop.Free(handle);
}
}
[Fact]
public void AllocNullStringsToPtrs()
{
IntPtr* ptr = Interop.String.AllocToPointers(null);
Assert.Equal(IntPtr.Zero, (IntPtr)ptr);
}
[Fact]
public void AllocEmptyStringsToPtrs()
{
IntPtr* ptr = Interop.String.AllocToPointers(new string[0]);
Assert.Equal(IntPtr.Zero, (IntPtr)ptr);
}
[Fact]
public void AllocStringsToPtrs()
{
string[] values = { "hi", "hello" };
IntPtr* ptr = null;
try
{
ptr = Interop.String.AllocToPointers(values);
IntPtr firstHandle = ptr[0];
IntPtr secondHandle = ptr[1];
Assert.Equal(values[0], Interop.String.FromPointer(firstHandle));
Assert.Equal(values[1], Interop.String.FromPointer(secondHandle));
}
finally
{
Interop.Free(ptr, values.Length);
}
}
[Fact]
public void AllocNullStructToPtr()
{
int? value = null;
IntPtr ptr = Interop.Struct.AllocToPointer(ref value);
Assert.Equal(IntPtr.Zero, ptr);
}
[Fact]
public void AllocStructToPtr()
{
IntPtr ptr = IntPtr.Zero;
try
{
int value = 1;
ptr = Interop.Struct.AllocToPointer(ref value);
Assert.Equal(1, *(int*)ptr);
}
finally
{
Interop.Free(ptr);
}
}
[Fact]
public void AllocNullableStructToPtr()
{
IntPtr ptr = IntPtr.Zero;
try
{
int? value = 1;
ptr = Interop.Struct.AllocToPointer(ref value);
Assert.Equal(1, *(int*)ptr);
}
finally
{
Interop.Free(ptr);
}
}
[Fact]
public void AllocNullStructsToPtr()
{
IntPtr ptr = Interop.Struct.AllocToPointer<int>(null);
Assert.Equal(IntPtr.Zero, ptr);
}
[Fact]
public void AllocEmptyStructsToPtr()
{
IntPtr ptr = Interop.Struct.AllocToPointer(new int[0]);
Assert.Equal(IntPtr.Zero, ptr);
}
[Fact]
public void Alloc32BitStructsToPtr()
{
int[] structs = { 1, 2, 3, 4 };
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Interop.Struct.AllocToPointer(structs);
var intPtr = (int*)ptr;
for (int i = 0; i < structs.Length; i++)
Assert.Equal(structs[i], intPtr[i]);
}
finally
{
Interop.Free(ptr);
}
}
[Fact]
public void Alloc64BitStructsToPtr()
{
long[] structs = { 1, 2, 3, 4 };
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Interop.Struct.AllocToPointer(structs);
var intPtr = (long*)ptr;
for (int i = 0; i < structs.Length; i++)
Assert.Equal(structs[i], intPtr[i]);
}
finally
{
Interop.Free(ptr);
}
}
[Fact]
public void ReAlloc()
{
IntPtr ptr = IntPtr.Zero;
try
{
ptr = Interop.Alloc(32);
ptr = Interop.ReAlloc(ptr, 64);
Assert.NotEqual(IntPtr.Zero, ptr);
}
finally
{
Interop.Free(ptr);
}
}
[Fact]
public void ReadValue()
{
long src = 0L;
long dst = 1L;
Interop.Read(new IntPtr(&dst), ref src);
Assert.Equal(1L, src);
}
[Fact]
public void WriteValue()
{
long src = 1L;
long dst = 0L;
Interop.Write(new IntPtr(&dst), ref src);
Assert.Equal(1L, dst);
}
[Fact]
public void ReadArray()
{
var dst = new long[2];
long[] src = { 1L, 2L };
fixed (long* srcPtr = src)
Interop.Read(new IntPtr(srcPtr), dst);
Assert.Equal(1L, dst[0]);
Assert.Equal(2L, dst[1]);
}
[Fact]
public void WriteArray()
{
long[] src = { 1L, 2L };
var dst = new long[2];
fixed (long* dstPtr = dst)
Interop.Write(new IntPtr(dstPtr), src);
Assert.Equal(1L, dst[0]);
Assert.Equal(2L, dst[1]);
}
[Fact]
public void ReadEmptyArray()
{
var dst = new long[0];
var src = new long[0];
fixed (long* srcPointer = src)
Interop.Read(new IntPtr(srcPointer), dst);
}
[Fact]
public void WriteEmptyArray()
{
var src = new long[0];
var dst = new long[0];
fixed (long* dstPtr = dst)
Interop.Write(new IntPtr(dstPtr), src);
}
}
}
| |
using System;
using System.Security;
using System.Runtime.InteropServices;
using SFML.Window;
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// This class defines a sprite : texture, transformations,
/// color, and draw on screen
/// </summary>
////////////////////////////////////////////////////////////
public class Sprite : Transformable, Drawable
{
////////////////////////////////////////////////////////////
/// <summary>
/// Default constructor
/// </summary>
////////////////////////////////////////////////////////////
public Sprite() :
base(sfSprite_create())
{
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the sprite from a source texture
/// </summary>
/// <param name="texture">Source texture to assign to the sprite</param>
////////////////////////////////////////////////////////////
public Sprite(Texture texture) :
base(sfSprite_create())
{
Texture = texture;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the sprite from a source texture
/// </summary>
/// <param name="texture">Source texture to assign to the sprite</param>
/// <param name="rectangle">Sub-rectangle of the texture to assign to the sprite</param>
////////////////////////////////////////////////////////////
public Sprite(Texture texture, IntRect rectangle) :
base(sfSprite_create())
{
Texture = texture;
TextureRect = rectangle;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the sprite from another sprite
/// </summary>
/// <param name="copy">Sprite to copy</param>
////////////////////////////////////////////////////////////
public Sprite(Sprite copy) :
base(sfSprite_copy(copy.CPointer))
{
Origin = copy.Origin;
Position = copy.Position;
Rotation = copy.Rotation;
Scale = copy.Scale;
Texture = copy.Texture;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Global color of the object
/// </summary>
////////////////////////////////////////////////////////////
public Color Color
{
get { return sfSprite_getColor(CPointer); }
set { sfSprite_setColor(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Source texture displayed by the sprite
/// </summary>
////////////////////////////////////////////////////////////
public Texture Texture
{
get { return myTexture; }
set { myTexture = value; sfSprite_setTexture(CPointer, value != null ? value.CPointer : IntPtr.Zero, false); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Sub-rectangle of the source image displayed by the sprite
/// </summary>
////////////////////////////////////////////////////////////
public IntRect TextureRect
{
get { return sfSprite_getTextureRect(CPointer); }
set { sfSprite_setTextureRect(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the local bounding rectangle of the entity.
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
/// </summary>
/// <returns>Local bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetLocalBounds()
{
return sfSprite_getLocalBounds(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the global bounding rectangle of the entity.
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
/// </summary>
/// <returns>Global bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetGlobalBounds()
{
// we don't use the native getGlobalBounds function,
// because we override the object's transform
return Transform.TransformRect(GetLocalBounds());
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[Sprite]" +
" Color(" + Color + ")" +
" Texture(" + Texture + ")" +
" TextureRect(" + TextureRect + ")";
}
////////////////////////////////////////////////////////////
/// <summmary>
/// Draw the object to a render target
///
/// This is a pure virtual function that has to be implemented
/// by the derived class to define how the drawable should be
/// drawn.
/// </summmary>
/// <param name="target">Render target to draw to</param>
/// <param name="states">Current render states</param>
////////////////////////////////////////////////////////////
public void Draw(RenderTarget target, RenderStates states)
{
//states.Transform *= Transform; // NetGore custom line
RenderStates.MarshalData marshaledStates = states.Marshal(Transform); // NetGore custom line
if (target is RenderWindow)
{
sfRenderWindow_drawSprite(((RenderWindow)target).CPointer, CPointer, ref marshaledStates);
}
else if (target is RenderTexture)
{
sfRenderTexture_drawSprite(((RenderTexture)target).CPointer, CPointer, ref marshaledStates);
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
sfSprite_destroy(CPointer);
}
private Texture myTexture = null;
#region Imports
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfSprite_create();
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfSprite_copy(IntPtr Sprite);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSprite_destroy(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSprite_setColor(IntPtr CPointer, Color Color);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Color sfSprite_getColor(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_drawSprite(IntPtr CPointer, IntPtr Sprite, ref RenderStates.MarshalData states);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_drawSprite(IntPtr CPointer, IntPtr Sprite, ref RenderStates.MarshalData states);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSprite_setTexture(IntPtr CPointer, IntPtr Texture, bool AdjustToNewSize);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSprite_setTextureRect(IntPtr CPointer, IntRect Rect);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntRect sfSprite_getTextureRect(IntPtr CPointer);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern FloatRect sfSprite_getLocalBounds(IntPtr CPointer);
#endregion
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Dematt.Airy.ApplicationInsights.Sample.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2016 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if !PORTABLE && !NETSTANDARD1_6
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Win32;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Enumeration identifying a common language
/// runtime implementation.
/// </summary>
public enum RuntimeType
{
/// <summary>Any supported runtime framework</summary>
Any,
/// <summary>Microsoft .NET Framework</summary>
Net,
/// <summary>Microsoft Shared Source CLI</summary>
SSCLI,
/// <summary>Mono</summary>
Mono,
/// <summary>MonoTouch</summary>
MonoTouch
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework
{
// NOTE: This version of RuntimeFramework is for use
// within the NUnit framework assembly. It is simpler
// than the version in the test engine because it does
// not need to know what frameworks are available,
// only what framework is currently running.
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0,0);
private static readonly Lazy<RuntimeFramework> currentFramework = new Lazy<RuntimeFramework>(() =>
{
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate,monotouch");
bool isMonoTouch = monoTouchType != null;
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMonoTouch
? RuntimeType.MonoTouch
: isMono
? RuntimeType.Mono
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
else /* It's windows */
if (major == 2)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework"))
{
if (key != null)
{
string installRoot = key.GetValue("InstallRoot") as string;
if (installRoot != null)
{
if (Directory.Exists(Path.Combine(installRoot, "v3.5")))
{
major = 3;
minor = 5;
}
else if (Directory.Exists(Path.Combine(installRoot, "v3.0")))
{
major = 3;
minor = 0;
}
}
}
}
}
else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null)
{
minor = 5;
}
var currentFramework = new RuntimeFramework( runtime, new Version (major, minor) )
{
ClrVersion = Environment.Version
};
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
return currentFramework;
});
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework( RuntimeType runtime, Version version)
{
Runtime = runtime;
if (version.Build < 0)
InitFromFrameworkVersion(version);
else
InitFromClrVersion(version);
DisplayName = GetDefaultDisplayName(runtime, version);
}
private void InitFromFrameworkVersion(Version version)
{
FrameworkVersion = ClrVersion = version;
if (version.Major > 0) // 0 means any version
switch (Runtime)
{
case RuntimeType.Net:
case RuntimeType.Mono:
case RuntimeType.Any:
switch (version.Major)
{
case 1:
switch (version.Minor)
{
case 0:
ClrVersion = Runtime == RuntimeType.Mono
? new Version(1, 1, 4322)
: new Version(1, 0, 3705);
break;
case 1:
if (Runtime == RuntimeType.Mono)
FrameworkVersion = new Version(1, 0);
ClrVersion = new Version(1, 1, 4322);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
case 2:
case 3:
ClrVersion = new Version(2, 0, 50727);
break;
case 4:
ClrVersion = new Version(4, 0, 30319);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
}
}
private static void ThrowInvalidFrameworkVersion(Version version)
{
throw new ArgumentException("Unknown framework version " + version, "version");
}
private void InitFromClrVersion(Version version)
{
FrameworkVersion = new Version(version.Major, version.Minor);
ClrVersion = version;
if (Runtime == RuntimeType.Mono && version.Major == 1)
FrameworkVersion = new Version(1, 0);
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
return currentFramework.Value;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime { get; private set; }
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion { get; private set; }
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion { get; private set; }
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return ClrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName { get; private set; }
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphenated RuntimeType-Version or
/// a Version prefixed by 'versionString'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split('-');
if (parts.Length == 2)
{
runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (AllowAnyVersion)
{
return Runtime.ToString().ToLower();
}
else
{
string vstring = FrameworkVersion.ToString();
if (Runtime == RuntimeType.Any)
return "v" + vstring;
else
return Runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="target">The RuntimeFramework to be matched.</param>
/// <returns>True on match, otherwise false</returns>
public bool Supports(RuntimeFramework target)
{
if (Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& Runtime != target.Runtime)
return false;
if (AllowAnyVersion || target.AllowAnyVersion)
return true;
if (!VersionsMatch(ClrVersion, target.ClrVersion))
return false;
return FrameworkVersion.Major >= target.FrameworkVersion.Major && FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
return TypeHelper.GetEnumNames( typeof(RuntimeType)).Any( item => item.ToLower() == name.ToLower() );
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version)
{
if (version == DefaultVersion)
return runtime.ToString();
else if (runtime == RuntimeType.Any)
return "v" + version;
else
return runtime + " " + version;
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
#endregion
}
}
#endif
| |
// 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 Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Threading;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using YetiCommon;
using YetiVSI.DebugEngine;
using YetiVSI.DebugEngine.NatvisEngine;
using YetiVSI.Util;
namespace YetiVSI
{
public enum LLDBVisualizerFeatureFlag
{
[Description("Default - Enabled")] [EnumValueAlias(ENABLED)]
DEFAULT = 0,
[Description("Enabled")] ENABLED = 1,
[Description("Built-in only (Used for Stadia specific visualizations, e.g. SSE registers)")]
BUILT_IN_ONLY = 2,
[Description("Disabled")] DISABLED = 3,
}
public enum SymbolServerFeatureFlag
{
[Description("Default - Disabled")] [EnumValueAlias(DISABLED)]
DEFAULT = 0,
[Description("Enabled")] ENABLED = 1,
[Description("Disabled")] DISABLED = 2,
}
public enum ShowOption
{
[Description("Default - Ask for each dialog")]
AskForEachDialog,
[Description("Never show")] NeverShow,
[Description("Always show")] AlwaysShow,
}
public class SdkPairIdentifier
{
public string GameletVersion { get; set; }
public string LocalVersion { get; set; }
public string GameletName { get; set; }
public override bool Equals(object obj)
{
if (!(obj is SdkPairIdentifier))
{
return false;
}
var sdkPair = (SdkPairIdentifier) obj;
return Equals(sdkPair);
}
public override int GetHashCode() =>
HashCode.Combine(GameletVersion, LocalVersion, GameletName);
protected bool Equals(SdkPairIdentifier other)
{
if (other == null)
{
return false;
}
return string.Equals(GameletVersion, other.GameletVersion) &&
string.Equals(LocalVersion, other.LocalVersion) &&
string.Equals(GameletName, other.GameletName);
}
}
public class SdkIncompatibilityWarning
{
ShowOption _showOption = ShowOption.AskForEachDialog;
public List<SdkPairIdentifier> SdkVersionPairsToHide { get; set; } =
new List<SdkPairIdentifier>();
public ShowOption ShowOption
{
get => _showOption;
set
{
if (_showOption == value)
{
return;
}
_showOption = value;
SdkVersionPairsToHide.Clear();
}
}
public override string ToString() => new JsonUtil().Serialize(this);
public static SdkIncompatibilityWarning FromString(string serialized) =>
new JsonUtil().Deserialize<SdkIncompatibilityWarning>(serialized);
public override bool Equals(object obj)
{
if (!(obj is SdkIncompatibilityWarning))
{
return false;
}
var sdkCompWarn = (SdkIncompatibilityWarning) obj;
return Equals(sdkCompWarn);
}
protected bool Equals(SdkIncompatibilityWarning other)
{
if (other == null)
{
return false;
}
if (!other.ShowOption.Equals(ShowOption) ||
other.SdkVersionPairsToHide.Count != SdkVersionPairsToHide.Count)
{
return false;
}
return other.SdkVersionPairsToHide.All(v => SdkVersionPairsToHide.Contains(v));
}
public override int GetHashCode() =>
HashCode.Combine((int) _showOption, SdkVersionPairsToHide);
}
public enum NatvisLoggingLevelFeatureFlag
{
[Description("Default - Disabled")] [EnumValueAlias(OFF)]
DEFAULT = 0,
[Description("Disabled")] OFF = 1,
[Description("Error")] ERROR = 2,
[Description("Warning")] WARNING = 3,
[Description("Verbose")] VERBOSE = 4,
}
public enum FastExpressionEvaluationFlag
{
[Description("Default - Disabled")] [EnumValueAlias(DISABLED)]
DEFAULT = 0,
[Description("Enabled")] ENABLED = 1,
[Description("Disabled")] DISABLED = 2,
}
public enum ExpressionEvaluationEngineFlag
{
[Description("Default - lldb-eval with fallback to LLDB")]
[EnumValueAlias(LLDB_EVAL_WITH_FALLBACK)]
DEFAULT = 0,
[Description("LLDB")] LLDB = 1,
[Description("lldb-eval with fallback to LLDB")]
LLDB_EVAL_WITH_FALLBACK = 2,
[Description("lldb-eval")] LLDB_EVAL = 3,
}
public struct GenericOption
{
public string Category;
public string Name;
public Type Type;
public object Value;
public bool IsDefaultValue;
}
public interface IExtensionOptions
{
event PropertyChangedEventHandler PropertyChanged;
bool CaptureGameOutput { get; }
string SelectedAccount { get; }
LLDBVisualizerSupport LLDBVisualizerSupport { get; }
SymbolServerSupport SymbolServerSupport { get; }
ShowOption ShowSuggestionToEnableSymbolsServer { get; }
NatvisLoggingLevel NatvisLoggingLevel { get; }
FastExpressionEvaluation FastExpressionEvaluation { get; }
ExpressionEvaluationStrategy ExpressionEvaluationStrategy { get; }
ShowOption SdkCompatibilityWarningOption { get; }
void AddSdkVersionsToHide(string gameletVersion, string localVersion, string gameletName);
bool SdkVersionsAreHidden(string gameletVersion, string localVersion, string gameletName);
void HideSuggestionToEnableSymbolsServer();
IEnumerable<GenericOption> Options { get; }
}
/// <summary>
/// Extension-wide options accessible via Tools->Options->Stadia SDK.
/// </summary>
/// <remarks>
/// The name of this class is used as a key in the Windows Registry. Do not change it.
///
/// The names, types, and values of these properties are stored in the registry.
/// The names and values of some properties are also recorded in metrics.
/// In general, do not rename or delete properties. Only add new ones.
///
/// To change the default value of an enum option, modify the EnumValueAttribute on its
/// DEFAULT value. For enum options, DefaultValue should point at the DEFAULT value.
///
/// If you add a new option, be sure to add it to the unit tests.
/// </remarks>
public class OptionPageGrid : DialogPage, IExtensionOptions, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
NatvisLoggingLevelFeatureFlag _natvisLoggingLevel;
FastExpressionEvaluationFlag _fastExpressionEvaluation;
ExpressionEvaluationEngineFlag _expressionEvaluationEngine;
public const string LldbDebugger = "LLDB Debugger";
public const string SuggestToEnableSymbolStore = "Suggest to enable symbol store";
[Category("Runtime")]
[DisplayName("Display game output in Output window")]
[Description("If enabled, captures the game's standard error and standard output and " +
"displays it in the Visual Studio Output window.")]
[DefaultValue(true)]
public bool CaptureGameOutput { get; set; }
[Category("Runtime")]
[DisplayName("Account used to run game")]
[Description("The account used to launch the game. If empty, the default account is " +
"used.")]
[DefaultValue("")]
public string SelectedAccount { get; set; }
[Category(LldbDebugger)]
[DisplayName("Enable variable visualizer support")]
[Description("Enables Natvis visualizer support for inspecting variables.")]
[TypeConverter(typeof(FeatureFlagConverter))]
[DefaultValue(LLDBVisualizerFeatureFlag.DEFAULT)]
public LLDBVisualizerFeatureFlag LLDBVisualizerSupport1 { get; set; }
[Category(LldbDebugger)]
[DisplayName("Enable symbol server support")]
[Description("If enabled, searches for symbol files in the locations specified in " +
"'Tools -> Options... -> Debugging -> Symbols'.")]
[TypeConverter(typeof(FeatureFlagConverter))]
[DefaultValue(SymbolServerFeatureFlag.DEFAULT)]
public SymbolServerFeatureFlag SymbolServerSupport { get; set; }
[Category(LldbDebugger)]
[DisplayName(SuggestToEnableSymbolStore)]
[Description("Sets whether the symbol store suggestion is shown during" +
" crash dump load or not.")]
[TypeConverter(typeof(FeatureFlagConverter))]
[DefaultValue(ShowOption.AskForEachDialog)]
public ShowOption ShowSuggestionToEnableSymbolsServer { get; set; }
[Category("Game launch")]
[DisplayName("SDK incompatibility warning")]
[Description("Sets whether the SDK incompatibility warning" +
" is shown during a game launch or not.")]
[TypeConverter(typeof(SdkWarningFlagConverter))]
public SdkIncompatibilityWarning SdkIncompatibilityWarning { get; set; }
[Category(LldbDebugger)]
[DisplayName("Natvis diagnostic messages")]
[Description("Sets the level of diagnostic output involving visualization of C++" +
" objects using natvis files. Takes effect immediately. Performance may be impacted" +
" when enabled.")]
[TypeConverter(typeof(FeatureFlagConverter))]
[DefaultValue(NatvisLoggingLevelFeatureFlag.DEFAULT)]
public NatvisLoggingLevelFeatureFlag NatvisLoggingLevel
{
get => _natvisLoggingLevel;
set
{
if (value != _natvisLoggingLevel)
{
_natvisLoggingLevel = value;
OnPropertyChanged(nameof(NatvisLoggingLevel));
}
}
}
[Category("LLDB Debugger")]
[DisplayName("Fast expression evaluation")]
[Description("Significantly faster expression evaluation, at the cost of incorrect " +
"symbol resolution when there are name collisions between ivars and local " +
"variables.")]
[TypeConverter(typeof(FeatureFlagConverter))]
[DefaultValue(FastExpressionEvaluationFlag.DEFAULT)]
public FastExpressionEvaluationFlag FastExpressionEvaluation
{
get => _fastExpressionEvaluation;
set
{
if (value != _fastExpressionEvaluation)
{
_fastExpressionEvaluation = value;
OnPropertyChanged(nameof(FastExpressionEvaluation));
}
}
}
[Category("LLDB Debugger")]
[DisplayName("Expression evaluation engine")]
[Description("Sets the expression evaluation engine used by Visual Studio in the " +
"Immediate Window and to display variables in various contexts (watches, autos, " +
"NatVis). LLDB is the default, mostly feature complete, but slow; lldb-eval is a " +
"faster experimental engine, more info: http://github.com/google/lldb-eval.")]
[TypeConverter(typeof(FeatureFlagConverter))]
[DefaultValue(ExpressionEvaluationEngineFlag.DEFAULT)]
public ExpressionEvaluationEngineFlag ExpressionEvaluationEngine
{
get => _expressionEvaluationEngine;
set
{
if (value != _expressionEvaluationEngine)
{
_expressionEvaluationEngine = value;
OnPropertyChanged(nameof(ExpressionEvaluationEngine));
}
}
}
public OptionPageGrid()
{
ResetSettings();
}
/// <summary>
/// Creates an OptionPageGrid for use in tests. The constructor of OptionPageGrid calls
/// ThreadHelper.JoinableTaskContext, but that's not set in tests. This method works
/// around that.
/// </summary>
public static OptionPageGrid CreateForTesting()
{
var taskContextField = typeof(ThreadHelper).GetField(
"_joinableTaskContextCache", BindingFlags.Static | BindingFlags.NonPublic);
// TODO: Use https://aka.ms/vssdktestfx for tests.
if (taskContextField.GetValue(null) == null)
{
// Disable "Use the ThreadHelper.JoinableTaskContext singleton rather than
// instantiating your own to avoid deadlocks".
#pragma warning disable VSSDK005
taskContextField.SetValue(null, new JoinableTaskContext());
#pragma warning restore VSSDK005
}
return new OptionPageGrid();
}
public override void ResetSettings()
{
// Initialize options to default values, if specified.
var optionsWithCategory = GetType().GetProperties()
.Where(p => GetPropertyCategory(p) != null);
foreach (var option in optionsWithCategory)
{
option.SetValue(this, GetPropertyDefaultValue(option));
}
}
#region IOptionPageGrid
LLDBVisualizerSupport IExtensionOptions.LLDBVisualizerSupport =>
EnumValueAliasAttribute.GetAliasOrValue(LLDBVisualizerSupport1)
.ConvertTo<LLDBVisualizerSupport>();
SymbolServerSupport IExtensionOptions.SymbolServerSupport =>
EnumValueAliasAttribute.GetAliasOrValue(SymbolServerSupport)
.ConvertTo<SymbolServerSupport>();
ShowOption IExtensionOptions.ShowSuggestionToEnableSymbolsServer =>
EnumValueAliasAttribute.GetAliasOrValue(ShowSuggestionToEnableSymbolsServer)
.ConvertTo<ShowOption>();
NatvisLoggingLevel IExtensionOptions.NatvisLoggingLevel =>
EnumValueAliasAttribute.GetAliasOrValue(NatvisLoggingLevel)
.ConvertTo<NatvisLoggingLevel>();
FastExpressionEvaluation IExtensionOptions.FastExpressionEvaluation =>
EnumValueAliasAttribute.GetAliasOrValue(FastExpressionEvaluation)
.ConvertTo<FastExpressionEvaluation>();
ExpressionEvaluationStrategy IExtensionOptions.ExpressionEvaluationStrategy =>
EnumValueAliasAttribute.GetAliasOrValue(ExpressionEvaluationEngine)
.ConvertTo<ExpressionEvaluationStrategy>();
ShowOption IExtensionOptions.SdkCompatibilityWarningOption =>
SdkIncompatibilityWarning.ShowOption;
void IExtensionOptions.AddSdkVersionsToHide(string gameletVersion, string localVersion,
string gameletName)
{
var sdkPair = new SdkPairIdentifier
{
GameletVersion = gameletVersion,
LocalVersion = localVersion,
GameletName = gameletName
};
if (SdkIncompatibilityWarning.SdkVersionPairsToHide.Contains(sdkPair))
{
return;
}
SdkIncompatibilityWarning.ShowOption = ShowOption.AskForEachDialog;
SdkIncompatibilityWarning.SdkVersionPairsToHide.Add(sdkPair);
SaveSettingsToStorage();
}
bool IExtensionOptions.SdkVersionsAreHidden(string gameletVersion, string localVersion,
string gameletName)
{
var sdkPair = new SdkPairIdentifier
{
GameletVersion = gameletVersion,
LocalVersion = localVersion,
GameletName = gameletName
};
return SdkIncompatibilityWarning.SdkVersionPairsToHide.Contains(sdkPair);
}
void IExtensionOptions.HideSuggestionToEnableSymbolsServer()
{
ShowSuggestionToEnableSymbolsServer = ShowOption.NeverShow;
SaveSettingsToStorage();
}
IEnumerable<GenericOption> IExtensionOptions.Options
{
get
{
// Find all properties that are options with a category.
var optionsWithCategory = GetType().GetProperties()
.Where(p => GetPropertyCategory(p) != null);
// Fill in GenericOption for each option on this option page.
return optionsWithCategory.Select(p =>
{
var value = p.GetValue(this);
var realValue = value;
if (p.PropertyType.IsEnum)
{
// Map enum value aliases.
realValue = EnumValueAliasAttribute.GetAliasOrValue(p.PropertyType, value);
}
return new GenericOption
{
Category = GetPropertyCategory(p),
Name = p.Name,
Type = p.PropertyType,
Value = realValue,
IsDefaultValue = Equals(GetPropertyDefaultValue(p), value),
};
});
}
}
#endregion
void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
static string GetPropertyCategory(PropertyInfo p)
{
var categoryAttribute =
Attribute.GetCustomAttribute(p, typeof(CategoryAttribute)) as CategoryAttribute;
return categoryAttribute?.Category;
}
static object GetPropertyDefaultValue(PropertyInfo p)
{
if (p.Name == nameof(SdkIncompatibilityWarning))
{
return new SdkIncompatibilityWarning();
}
var defaultValueAttribute =
Attribute.GetCustomAttribute(p, typeof(DefaultValueAttribute)) as
DefaultValueAttribute;
return defaultValueAttribute?.Value;
}
protected override void LoadSettingFromStorage(PropertyDescriptor prop)
{
// Sometimes it can happen that extension settings are saved in the wrong format or
// some default values changed. The new extension will fail to load because it can't
// convert the old settings. This shouldn't happen under normal conditions, but ignore
// the load errors and fallback to using default values.
try
{
base.LoadSettingFromStorage(prop);
}
catch (Exception e)
{
Trace.WriteLine($"Failed to load a setting for {prop.Name}: {e.Demystify()}");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography.EcDsa.Tests;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.EcDsa.OpenSsl.Tests
{
public class EcDsaOpenSslTests : ECDsaTestsBase
{
[Fact]
public void DefaultCtor()
{
using (ECDsaOpenSsl e = new ECDsaOpenSsl())
{
int keySize = e.KeySize;
Assert.Equal(521, keySize);
e.Exercise();
}
}
[Fact]
public void Ctor256()
{
int expectedKeySize = 256;
using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize))
{
int keySize = e.KeySize;
Assert.Equal(expectedKeySize, keySize);
e.Exercise();
}
}
[Fact]
public void Ctor384()
{
int expectedKeySize = 384;
using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize))
{
int keySize = e.KeySize;
Assert.Equal(expectedKeySize, keySize);
e.Exercise();
}
}
[Fact]
public void Ctor521()
{
int expectedKeySize = 521;
using (ECDsaOpenSsl e = new ECDsaOpenSsl(expectedKeySize))
{
int keySize = e.KeySize;
Assert.Equal(expectedKeySize, keySize);
e.Exercise();
}
}
[ConditionalFact(nameof(ECDsa224Available))]
public void CtorHandle224()
{
IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P224_OID_VALUE);
Assert.NotEqual(IntPtr.Zero, ecKey);
int success = Interop.Crypto.EcKeyGenerateKey(ecKey);
Assert.NotEqual(0, success);
using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey))
{
int keySize = e.KeySize;
Assert.Equal(224, keySize);
e.Exercise();
}
Interop.Crypto.EcKeyDestroy(ecKey);
}
[Fact]
public void CtorHandle384()
{
IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P384_OID_VALUE);
Assert.NotEqual(IntPtr.Zero, ecKey);
int success = Interop.Crypto.EcKeyGenerateKey(ecKey);
Assert.NotEqual(0, success);
using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey))
{
int keySize = e.KeySize;
Assert.Equal(384, keySize);
e.Exercise();
}
Interop.Crypto.EcKeyDestroy(ecKey);
}
[Fact]
public void CtorHandle521()
{
IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE);
Assert.NotEqual(IntPtr.Zero, ecKey);
int success = Interop.Crypto.EcKeyGenerateKey(ecKey);
Assert.NotEqual(0, success);
using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey))
{
int keySize = e.KeySize;
Assert.Equal(521, keySize);
e.Exercise();
}
Interop.Crypto.EcKeyDestroy(ecKey);
}
[Fact]
public void CtorHandleDuplicate()
{
IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE);
Assert.NotEqual(IntPtr.Zero, ecKey);
int success = Interop.Crypto.EcKeyGenerateKey(ecKey);
Assert.NotEqual(0, success);
using (ECDsaOpenSsl e = new ECDsaOpenSsl(ecKey))
{
// Make sure ECDsaOpenSsl did his own ref-count bump.
Interop.Crypto.EcKeyDestroy(ecKey);
int keySize = e.KeySize;
Assert.Equal(521, keySize);
e.Exercise();
}
}
[Fact]
public void KeySizePropWithExercise()
{
using (ECDsaOpenSsl e = new ECDsaOpenSsl())
{
e.KeySize = 384;
Assert.Equal(384, e.KeySize);
e.Exercise();
ECParameters p384 = e.ExportParameters(false);
Assert.Equal(ECCurve.ECCurveType.Named, p384.Curve.CurveType);
e.KeySize = 521;
Assert.Equal(521, e.KeySize);
e.Exercise();
ECParameters p521 = e.ExportParameters(false);
Assert.Equal(ECCurve.ECCurveType.Named, p521.Curve.CurveType);
// ensure the key was regenerated
Assert.NotEqual(p384.Curve.Oid.Value, p521.Curve.Oid.Value);
}
}
[Fact]
public void VerifyDuplicateKey_ValidHandle()
{
byte[] data = ByteUtils.RepeatByte(0x71, 11);
using (ECDsaOpenSsl first = new ECDsaOpenSsl())
using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
{
using (ECDsa second = new ECDsaOpenSsl(firstHandle))
{
byte[] signed = second.SignData(data, HashAlgorithmName.SHA512);
Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512));
}
}
}
[Fact]
public void VerifyDuplicateKey_DistinctHandles()
{
using (ECDsaOpenSsl first = new ECDsaOpenSsl())
using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle())
{
Assert.NotSame(firstHandle, firstHandle2);
}
}
[Fact]
public void VerifyDuplicateKey_RefCounts()
{
byte[] data = ByteUtils.RepeatByte(0x74, 11);
byte[] signature;
ECDsa second;
using (ECDsaOpenSsl first = new ECDsaOpenSsl())
using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
{
signature = first.SignData(data, HashAlgorithmName.SHA384);
second = new ECDsaOpenSsl(firstHandle);
}
// Now show that second still works, despite first and firstHandle being Disposed.
using (second)
{
Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384));
}
}
[Fact]
public void VerifyDuplicateKey_NullHandle()
{
SafeEvpPKeyHandle pkey = null;
Assert.Throws<ArgumentNullException>(() => new RSAOpenSsl(pkey));
}
[Fact]
public void VerifyDuplicateKey_InvalidHandle()
{
using (ECDsaOpenSsl ecdsa = new ECDsaOpenSsl())
{
SafeEvpPKeyHandle pkey = ecdsa.DuplicateKeyHandle();
using (pkey)
{
}
Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey));
}
}
[Fact]
public void VerifyDuplicateKey_NeverValidHandle()
{
using (SafeEvpPKeyHandle pkey = new SafeEvpPKeyHandle(IntPtr.Zero, false))
{
Assert.Throws<ArgumentException>(() => new ECDsaOpenSsl(pkey));
}
}
[Fact]
public void VerifyDuplicateKey_RsaHandle()
{
using (RSAOpenSsl rsa = new RSAOpenSsl())
using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle())
{
Assert.ThrowsAny<CryptographicException>(() => new ECDsaOpenSsl(pkey));
}
}
[Fact]
public void LookupCurveByOidValue()
{
ECDsaOpenSsl ec = null;
ec = new ECDsaOpenSsl(ECCurve.CreateFromValue(ECDSA_P256_OID_VALUE)); // Same as nistP256
ECParameters param = ec.ExportParameters(false);
param.Validate();
Assert.Equal(256, ec.KeySize);
Assert.True(param.Curve.IsNamed);
Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName);
Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value);
}
[Fact]
public void LookupCurveByOidFriendlyName()
{
ECDsaOpenSsl ec = null;
// prime256v1 is alias for nistP256 for OpenSsl
ec = new ECDsaOpenSsl(ECCurve.CreateFromFriendlyName("prime256v1"));
ECParameters param = ec.ExportParameters(false);
param.Validate();
Assert.Equal(256, ec.KeySize);
Assert.True(param.Curve.IsNamed);
Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName); // OpenSsl maps prime256v1 to ECDSA_P256
Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value);
// secp521r1 is same as nistP521; note Windows uses secP521r1 (uppercase P)
ec = new ECDsaOpenSsl(ECCurve.CreateFromFriendlyName("secp521r1"));
param = ec.ExportParameters(false);
param.Validate();
Assert.Equal(521, ec.KeySize);
Assert.True(param.Curve.IsNamed);
Assert.Equal("ECDSA_P521", param.Curve.Oid.FriendlyName); // OpenSsl maps secp521r1 to ECDSA_P521
Assert.Equal(ECDSA_P521_OID_VALUE, param.Curve.Oid.Value);
}
}
}
internal static partial class Interop
{
internal static class Crypto
{
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByOid")]
internal static extern IntPtr EcKeyCreateByOid(string oid);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyGenerateKey")]
internal static extern int EcKeyGenerateKey(IntPtr ecKey);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyDestroy")]
internal static extern void EcKeyDestroy(IntPtr r);
}
}
| |
// 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.Globalization;
using System.Linq;
namespace Microsoft.Tools.ServiceModel.Svcutil
{
internal enum SwitchType
{
Flag,
SingletonValue,
ValueList,
FlagOrSingletonValue
}
internal class CommandSwitch
{
public const string AbbreviationSwitchIndicator = "-";
public const string FullSwitchIndicator = "--";
public const OperationalContext DefaultSwitchLevel = OperationalContext.Project;
private static List<CommandSwitch> s_allSwitches = new List<CommandSwitch>();
public static IEnumerable<CommandSwitch> All { get { return s_allSwitches; } }
public string Name { get; private set; }
public string Abbreviation { get; private set; }
public SwitchType SwitchType { get; private set; }
public OperationalContext SwitchLevel { get; private set; }
internal CommandSwitch(string name, string abbreviation, SwitchType switchType, OperationalContext switchLevel = DefaultSwitchLevel)
{
// ensure that name doesn't start with the switch indicators.
// also convert to lower-case
if (name.StartsWith(FullSwitchIndicator))
{
this.Name = name.Substring(FullSwitchIndicator.Length);
}
else
{
this.Name = name;
}
if (abbreviation.StartsWith(AbbreviationSwitchIndicator))
{
this.Abbreviation = abbreviation.Substring(AbbreviationSwitchIndicator.Length);
}
else
{
this.Abbreviation = abbreviation;
}
this.SwitchType = switchType;
this.SwitchLevel = switchLevel;
System.Diagnostics.Debug.Assert(!s_allSwitches.Any(s => s.Equals(this)), $"A switch with name or abbreviation '{name}+{abbreviation}' has already been crated!");
s_allSwitches.Add(this);
}
internal static CommandSwitch FindSwitch(string name)
{
return CommandSwitch.All.FirstOrDefault(s => s.Equals(name));
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0} {{{1}, {2}, Type={3}}}", this.GetType().Name, Name, Abbreviation, SwitchType);
}
internal bool Equals(string other)
{
string otherName;
bool isAbbreviation = true;
if (string.IsNullOrWhiteSpace(other))
{
return false;
}
// If other starts with a switch indicator, we want to enforce the correct indicator (e.g. "-directory" and "--d" will return false, but "--directory" and "directory" will return true).
bool enforceSwitchType = other.StartsWith(FullSwitchIndicator) || other.StartsWith(AbbreviationSwitchIndicator);
// Take off the switch indicators and figure out if this is an abbreviation or not.
// also convert to lower-case
if (other.StartsWith(FullSwitchIndicator))
{
isAbbreviation = false;
otherName = other.Substring(FullSwitchIndicator.Length).ToLowerInvariant();
}
else if (other.StartsWith(AbbreviationSwitchIndicator))
{
isAbbreviation = true;
otherName = other.Substring(AbbreviationSwitchIndicator.Length).ToLowerInvariant();
}
else
{
otherName = other.ToLowerInvariant();
}
var thisAbbr = Abbreviation.ToLowerInvariant();
var thisName = Name.ToLowerInvariant();
if (enforceSwitchType)
{
return isAbbreviation ? thisAbbr == otherName : thisName == otherName;
}
else
{
return thisAbbr == otherName || thisName == otherName;
}
}
}
internal static class CommandParser
{
// Instead of throwing exceptions we pass the first exception that happens as an out parameter. This lets us parse as many
// arguments as we can correctly so we can respect options like noLogo and verbosity when showing errors.
internal static CommandProcessorOptions ParseCommand(string[] cmd)
{
var options = new CommandProcessorOptions();
// work around https://github.com/dotnet/core-setup/issues/619 to ignore additionalprobingpath
cmd = cmd.Where(c => !c.ToLowerInvariant().Contains("additionalprobingpath")).ToArray();
for (int i = 0; i < cmd.Length; i++)
{
string arg = cmd[i]?.Trim('\"').Trim();
if (string.IsNullOrWhiteSpace(arg))
{
continue;
}
// if argument does not start with switch indicator, place into "default" arguments
if (IsArgumentValue(arg))
{
SetValue(options, CommandProcessorOptions.InputsKey, Environment.ExpandEnvironmentVariables(arg));
continue;
}
// check if this switch exists in the list of possible switches
var argSwitch = CommandSwitch.FindSwitch(arg);
var argValue = cmd.Length > i + 1 ? cmd[i + 1] : null;
if (argSwitch == null)
{
options.AddError(string.Format(SR.ErrUnknownSwitchFormat, arg));
continue;
}
// we have a valid switch, now validate value.
// make sure there's a value for the parameter.
switch (argSwitch.SwitchType)
{
case SwitchType.Flag:
argValue = "true";
break;
case SwitchType.FlagOrSingletonValue:
argValue = (argValue == null || !IsArgumentValue(argValue)) ? string.Empty : argValue;
break;
case SwitchType.SingletonValue:
case SwitchType.ValueList:
if (string.IsNullOrWhiteSpace(argValue) || !IsArgumentValue(argValue))
{
options.AddError(string.Format(SR.ErrArgumentWithoutValue, argSwitch.Name));
continue;
}
break;
}
// check if switch is allowed to be specified multiple times
// if not and it has already been specified and a new value has been parsed.
if (argSwitch.SwitchType != SwitchType.ValueList && options.GetValue<object>(argSwitch.Name) != null)
{
options.AddError(string.Format(SR.ErrSingleUseSwitchFormat, argSwitch.Name));
continue;
}
SetValue(options, argSwitch.Name, argValue.Trim('\"').Trim());
if (argSwitch.SwitchType != SwitchType.Flag && argValue != string.Empty && IsArgumentValue(argValue))
{
i++; // move to next input.
}
}
return options;
}
private static void SetValue(CommandProcessorOptions options, string optionName, object value)
{
try
{
options.SetValue(optionName, value);
}
catch (Exception ex)
{
if (Utils.IsFatalOrUnexpected(ex)) throw;
options.AddError(ex);
}
}
private static bool IsArgumentValue(string arg)
{
return !(arg.StartsWith(CommandSwitch.FullSwitchIndicator) || arg.StartsWith(CommandSwitch.AbbreviationSwitchIndicator));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/// <summary>
/// A simple append only random-access <see cref="BytesRef"/> array that stores full
/// copies of the appended bytes in a <see cref="ByteBlockPool"/>.
/// <para/>
/// <b>Note: this class is not Thread-Safe!</b>
/// <para/>
/// @lucene.internal
/// @lucene.experimental
/// </summary>
public sealed class BytesRefArray
{
private readonly ByteBlockPool pool;
private int[] offsets = new int[1];
private int lastElement = 0;
private int currentOffset = 0;
private readonly Counter bytesUsed;
/// <summary>
/// Creates a new <see cref="BytesRefArray"/> with a counter to track allocated bytes
/// </summary>
public BytesRefArray(Counter bytesUsed)
{
this.pool = new ByteBlockPool(new ByteBlockPool.DirectTrackingAllocator(bytesUsed));
pool.NextBuffer();
bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + RamUsageEstimator.NUM_BYTES_INT32);
this.bytesUsed = bytesUsed;
}
/// <summary>
/// Clears this <see cref="BytesRefArray"/>
/// </summary>
public void Clear()
{
lastElement = 0;
currentOffset = 0;
Array.Clear(offsets, 0, offsets.Length);
pool.Reset(false, true); // no need to 0 fill the buffers we control the allocator
}
/// <summary>
/// Appends a copy of the given <see cref="BytesRef"/> to this <see cref="BytesRefArray"/>. </summary>
/// <param name="bytes"> The bytes to append </param>
/// <returns> The index of the appended bytes </returns>
public int Append(BytesRef bytes)
{
if (lastElement >= offsets.Length)
{
int oldLen = offsets.Length;
offsets = ArrayUtil.Grow(offsets, offsets.Length + 1);
bytesUsed.AddAndGet((offsets.Length - oldLen) * RamUsageEstimator.NUM_BYTES_INT32);
}
pool.Append(bytes);
offsets[lastElement++] = currentOffset;
currentOffset += bytes.Length;
return lastElement - 1;
}
/// <summary>
/// Returns the current size of this <see cref="BytesRefArray"/>.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
/// <returns> The current size of this <see cref="BytesRefArray"/> </returns>
public int Length
{
get { return lastElement; }
}
/// <summary>
/// Returns the <i>n'th</i> element of this <see cref="BytesRefArray"/> </summary>
/// <param name="spare"> A spare <see cref="BytesRef"/> instance </param>
/// <param name="index"> The elements index to retrieve </param>
/// <returns> The <i>n'th</i> element of this <see cref="BytesRefArray"/> </returns>
public BytesRef Get(BytesRef spare, int index)
{
if (lastElement > index)
{
int offset = offsets[index];
int length = index == lastElement - 1 ? currentOffset - offset : offsets[index + 1] - offset;
Debug.Assert(spare.Offset == 0);
spare.Grow(length);
spare.Length = length;
pool.ReadBytes(offset, spare.Bytes, spare.Offset, spare.Length);
return spare;
}
throw new System.IndexOutOfRangeException("index " + index + " must be less than the size: " + lastElement);
}
private int[] Sort(IComparer<BytesRef> comp)
{
int[] orderedEntries = new int[Length];
for (int i = 0; i < orderedEntries.Length; i++)
{
orderedEntries[i] = i;
}
new IntroSorterAnonymousInnerClassHelper(this, comp, orderedEntries).Sort(0, Length);
return orderedEntries;
}
private class IntroSorterAnonymousInnerClassHelper : IntroSorter
{
private readonly BytesRefArray outerInstance;
private IComparer<BytesRef> comp;
private int[] orderedEntries;
public IntroSorterAnonymousInnerClassHelper(BytesRefArray outerInstance, IComparer<BytesRef> comp, int[] orderedEntries)
{
this.outerInstance = outerInstance;
this.comp = comp;
this.orderedEntries = orderedEntries;
pivot = new BytesRef();
scratch1 = new BytesRef();
scratch2 = new BytesRef();
}
protected override void Swap(int i, int j)
{
int o = orderedEntries[i];
orderedEntries[i] = orderedEntries[j];
orderedEntries[j] = o;
}
protected override int Compare(int i, int j)
{
int idx1 = orderedEntries[i], idx2 = orderedEntries[j];
return comp.Compare(outerInstance.Get(scratch1, idx1), outerInstance.Get(scratch2, idx2));
}
protected override void SetPivot(int i)
{
int index = orderedEntries[i];
outerInstance.Get(pivot, index);
}
protected override int ComparePivot(int j)
{
int index = orderedEntries[j];
return comp.Compare(pivot, outerInstance.Get(scratch2, index));
}
private readonly BytesRef pivot;
private readonly BytesRef scratch1;
private readonly BytesRef scratch2;
}
/// <summary>
/// Sugar for <see cref="GetIterator(IComparer{BytesRef})"/> with a <c>null</c> comparer
/// </summary>
public IBytesRefIterator GetIterator()
{
return GetIterator(null);
}
/// <summary>
/// <para>
/// Returns a <see cref="IBytesRefIterator"/> with point in time semantics. The
/// iterator provides access to all so far appended <see cref="BytesRef"/> instances.
/// </para>
/// <para>
/// If a non <c>null</c> <see cref="T:IComparer{BytesRef}"/> is provided the iterator will
/// iterate the byte values in the order specified by the comparer. Otherwise
/// the order is the same as the values were appended.
/// </para>
/// <para>
/// This is a non-destructive operation.
/// </para>
/// </summary>
public IBytesRefIterator GetIterator(IComparer<BytesRef> comp)
{
BytesRef spare = new BytesRef();
int size = Length;
int[] indices = comp == null ? null : Sort(comp);
return new BytesRefIteratorAnonymousInnerClassHelper(this, comp, spare, size, indices);
}
private class BytesRefIteratorAnonymousInnerClassHelper : IBytesRefIterator
{
private readonly BytesRefArray outerInstance;
private IComparer<BytesRef> comp;
private BytesRef spare;
private int size;
private int[] indices;
public BytesRefIteratorAnonymousInnerClassHelper(BytesRefArray outerInstance, IComparer<BytesRef> comp, BytesRef spare, int size, int[] indices)
{
this.outerInstance = outerInstance;
this.comp = comp;
this.spare = spare;
this.size = size;
this.indices = indices;
pos = 0;
}
internal int pos;
public virtual BytesRef Next()
{
if (pos < size)
{
return outerInstance.Get(spare, indices == null ? pos++ : indices[pos++]);
}
return null;
}
public virtual IComparer<BytesRef> Comparer
{
get
{
return comp;
}
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes ([email protected]), Dan Moorehead ([email protected])
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
#region CVS Information
/*
* $Source$
* $Author: mccollum $
* $Date: 2006-09-08 17:12:07 -0700 (Fri, 08 Sep 2006) $
* $Revision: 6434 $
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using DNPreBuild.Core.Attributes;
using DNPreBuild.Core.Interfaces;
using DNPreBuild.Core.Nodes;
using DNPreBuild.Core.Util;
namespace DNPreBuild.Core.Targets
{
public enum VSVersion
{
VS70,
VS71,
VS80
}
[Target("vs2003")]
public class VS2003Target : ITarget
{
#region Inner Classes
protected struct ToolInfo
{
public string Name;
public string Guid;
public string FileExtension;
public string XMLTag;
public ToolInfo(string name, string guid, string fileExt, string xml)
{
Name = name;
Guid = guid;
FileExtension = fileExt;
XMLTag = xml;
}
}
#endregion
#region Fields
protected string m_SolutionVersion = "8.00";
protected string m_ProductVersion = "7.10.3077";
protected string m_SchemaVersion = "2.0";
protected string m_VersionName = "2003";
protected VSVersion m_Version = VSVersion.VS71;
protected Hashtable m_Tools = null;
protected Kernel m_Kernel = null;
#endregion
#region Constructors
public VS2003Target()
{
m_Tools = new Hashtable();
m_Tools["C#"] = new ToolInfo("C#", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "csproj", "CSHARP");
m_Tools["VB.NET"] = new ToolInfo("VB.NET", "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}", "vbproj", "VisualBasic");
}
#endregion
#region Private Methods
protected string MakeRefPath(ProjectNode project)
{
string ret = "";
foreach(ReferencePathNode node in project.ReferencePaths)
{
try
{
string fullPath = Helper.ResolvePath(node.Path);
if(ret.Length < 1)
ret = fullPath;
else
ret += ";" + fullPath;
}
catch(ArgumentException)
{
m_Kernel.Log.Write(LogType.Warning, "Could not resolve reference path: {0}", node.Path);
}
}
return ret;
}
protected virtual void WriteProject(SolutionNode solution, ProjectNode project)
{
if(!m_Tools.ContainsKey(project.Language))
throw new Exception("Unknown .NET language: " + project.Language);
ToolInfo toolInfo = (ToolInfo)m_Tools[project.Language];
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, toolInfo.FileExtension);
StreamWriter ps = new StreamWriter(projectFile);
m_Kernel.CWDStack.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projectFile));
using(ps)
{
ps.WriteLine("<VisualStudioProject>");
ps.WriteLine("\t<{0}", toolInfo.XMLTag);
ps.WriteLine("\t\tProjectType = \"Local\"");
ps.WriteLine("\t\tProductVersion = \"{0}\"", m_ProductVersion);
ps.WriteLine("\t\tSchemaVersion = \"{0}\"", m_SchemaVersion);
ps.WriteLine("\t\tProjectGuid = \"{{{0}}}\"", project.Guid.ToString().ToUpper());
ps.WriteLine("\t>");
ps.WriteLine("\t\t<Build>");
ps.WriteLine("\t\t\t<Settings");
ps.WriteLine("\t\t\t\tApplicationIcon = \"{0}\"",project.AppIcon);
ps.WriteLine("\t\t\t\tAssemblyKeyContainerName = \"\"");
ps.WriteLine("\t\t\t\tAssemblyName = \"{0}\"", project.AssemblyName);
ps.WriteLine("\t\t\t\tAssemblyOriginatorKeyFile = \"\"");
ps.WriteLine("\t\t\t\tDefaultClientScript = \"JScript\"");
ps.WriteLine("\t\t\t\tDefaultHTMLPageLayout = \"Grid\"");
ps.WriteLine("\t\t\t\tDefaultTargetSchema = \"IE50\"");
ps.WriteLine("\t\t\t\tDelaySign = \"false\"");
if(m_Version == VSVersion.VS70)
ps.WriteLine("\t\t\t\tNoStandardLibraries = \"false\"");
ps.WriteLine("\t\t\t\tOutputType = \"{0}\"", project.Type.ToString());
ps.WriteLine("\t\t\t\tRootNamespace = \"{0}\"", project.RootNamespace);
ps.WriteLine("\t\t\t\tStartupObject = \"{0}\"", project.StartupObject);
ps.WriteLine("\t\t\t>");
foreach(ConfigurationNode conf in project.Configurations)
{
ps.WriteLine("\t\t\t\t<Config");
ps.WriteLine("\t\t\t\t\tName = \"{0}\"", conf.Name);
ps.WriteLine("\t\t\t\t\tAllowUnsafeBlocks = \"{0}\"", conf.Options["AllowUnsafe"]);
ps.WriteLine("\t\t\t\t\tBaseAddress = \"{0}\"", conf.Options["BaseAddress"]);
ps.WriteLine("\t\t\t\t\tCheckForOverflowUnderflow = \"{0}\"", conf.Options["CheckUnderflowOverflow"]);
ps.WriteLine("\t\t\t\t\tConfigurationOverrideFile = \"\"");
ps.WriteLine("\t\t\t\t\tDefineConstants = \"{0}\"", conf.Options["CompilerDefines"]);
ps.WriteLine("\t\t\t\t\tDocumentationFile = \"{0}\"", conf.Options["XmlDocFile"]);
ps.WriteLine("\t\t\t\t\tDebugSymbols = \"{0}\"", conf.Options["DebugInformation"]);
ps.WriteLine("\t\t\t\t\tFileAlignment = \"{0}\"", conf.Options["FileAlignment"]);
ps.WriteLine("\t\t\t\t\tIncrementalBuild = \"{0}\"", conf.Options["IncrementalBuild"]);
if(m_Version == VSVersion.VS71)
{
ps.WriteLine("\t\t\t\t\tNoStdLib = \"{0}\"", conf.Options["NoStdLib"]);
ps.WriteLine("\t\t\t\t\tNoWarn = \"{0}\"", conf.Options["SupressWarnings"]);
}
ps.WriteLine("\t\t\t\t\tOptimize = \"{0}\"", conf.Options["OptimizeCode"]);
ps.WriteLine("\t\t\t\t\tOutputPath = \"{0}\"",
Helper.EndPath(Helper.NormalizePath(conf.Options["OutputPath"].ToString())));
ps.WriteLine("\t\t\t\t\tRegisterForComInterop = \"{0}\"", conf.Options["RegisterCOMInterop"]);
ps.WriteLine("\t\t\t\t\tRemoveIntegerChecks = \"{0}\"", conf.Options["RemoveIntegerChecks"]);
ps.WriteLine("\t\t\t\t\tTreatWarningsAsErrors = \"{0}\"", conf.Options["WarningsAsErrors"]);
ps.WriteLine("\t\t\t\t\tWarningLevel = \"{0}\"", conf.Options["WarningLevel"]);
ps.WriteLine("\t\t\t\t/>");
}
ps.WriteLine("\t\t\t</Settings>");
ps.WriteLine("\t\t\t<References>");
foreach(ReferenceNode refr in project.References)
{
ps.WriteLine("\t\t\t\t<Reference");
ps.WriteLine("\t\t\t\t\tName = \"{0}\"", refr.Name);
if(solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode refProject = (ProjectNode)solution.ProjectsTable[refr.Name];
ps.WriteLine("\t\t\t\t\tProject = \"{{{0}}}\"", refProject.Guid.ToString().ToUpper());
ps.WriteLine("\t\t\t\t\tPackage = \"{0}\"", toolInfo.Guid.ToString().ToUpper());
}
else
{
if(refr.Path != null)
ps.WriteLine("\t\t\t\t\tHintPath = \"{0}\"", Helper.MakeFilePath(refr.Path, refr.Name, "dll"));
}
if(refr.LocalCopySpecified)
ps.WriteLine("\t\t\t\t\tPrivate = \"{0}\"",refr.LocalCopy);
ps.WriteLine("\t\t\t\t/>");
}
ps.WriteLine("\t\t\t</References>");
ps.WriteLine("\t\t</Build>");
ps.WriteLine("\t\t<Files>");
ps.WriteLine("\t\t\t<Include>");
foreach(string file in project.Files)
{
ps.WriteLine("\t\t\t\t<File");
ps.WriteLine("\t\t\t\t\tRelPath = \"{0}\"", file.Replace(".\\", ""));
ps.WriteLine("\t\t\t\t\tSubType = \"Code\"");
ps.WriteLine("\t\t\t\t\tBuildAction = \"{0}\"", project.Files.GetBuildAction(file));
ps.WriteLine("\t\t\t\t/>");
}
ps.WriteLine("\t\t\t</Include>");
ps.WriteLine("\t\t</Files>");
ps.WriteLine("\t</{0}>", toolInfo.XMLTag);
ps.WriteLine("</VisualStudioProject>");
}
ps = new StreamWriter(projectFile + ".user");
using(ps)
{
ps.WriteLine("<VisualStudioProject>");
ps.WriteLine("\t<{0}>", toolInfo.XMLTag);
ps.WriteLine("\t\t<Build>");
ps.WriteLine("\t\t\t<Settings ReferencePath=\"{0}\">", MakeRefPath(project));
foreach(ConfigurationNode conf in project.Configurations)
{
ps.WriteLine("\t\t\t\t<Config");
ps.WriteLine("\t\t\t\t\tName = \"{0}\"", conf.Name);
ps.WriteLine("\t\t\t\t/>");
}
ps.WriteLine("\t\t\t</Settings>");
ps.WriteLine("\t\t</Build>");
ps.WriteLine("\t</{0}>", toolInfo.XMLTag);
ps.WriteLine("</VisualStudioProject>");
}
m_Kernel.CWDStack.Pop();
}
protected virtual void WriteSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Creating Visual Studio {0} solution and project files", m_VersionName);
foreach(ProjectNode project in solution.Projects)
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
m_Kernel.Log.Write("");
string solutionFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "sln");
StreamWriter ss = new StreamWriter(solutionFile);
m_Kernel.CWDStack.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(solutionFile));
using(ss)
{
ss.WriteLine("Microsoft Visual Studio Solution File, Format Version {0}", m_SolutionVersion);
foreach(ProjectNode project in solution.Projects)
{
if(!m_Tools.ContainsKey(project.Language))
throw new Exception("Unknown .NET language: " + project.Language);
ToolInfo toolInfo = (ToolInfo)m_Tools[project.Language];
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.WriteLine("Project(\"{0}\") = \"{1}\", \"{2}\", \"{{{3}}}\"",
toolInfo.Guid, project.Name, Helper.MakeFilePath(path, project.Name,
toolInfo.FileExtension), project.Guid.ToString().ToUpper());
ss.WriteLine("\tProjectSection(ProjectDependencies) = postProject");
ss.WriteLine("\tEndProjectSection");
ss.WriteLine("EndProject");
}
ss.WriteLine("Global");
ss.WriteLine("\tGlobalSection(SolutionConfiguration) = preSolution");
foreach(ConfigurationNode conf in solution.Configurations)
ss.WriteLine("\t\t{0} = {0}", conf.Name);
ss.WriteLine("\tEndGlobalSection");
ss.WriteLine("\tGlobalSection(ProjectDependencies) = postSolution");
foreach(ProjectNode project in solution.Projects)
{
for(int i = 0; i < project.References.Count; i++)
{
ReferenceNode refr = (ReferenceNode)project.References[i];
if(solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode refProject = (ProjectNode)solution.ProjectsTable[refr.Name];
ss.WriteLine("\t\t({{{0}}}).{1} = ({{{2}}})",
project.Guid.ToString().ToUpper()
, i,
refProject.Guid.ToString().ToUpper()
);
}
}
}
ss.WriteLine("\tEndGlobalSection");
ss.WriteLine("\tGlobalSection(ProjectConfiguration) = postSolution");
foreach(ProjectNode project in solution.Projects)
{
foreach(ConfigurationNode conf in solution.Configurations)
{
ss.WriteLine("\t\t{{{0}}}.{1}.ActiveCfg = {1}|.NET",
project.Guid.ToString().ToUpper(),
conf.Name);
ss.WriteLine("\t\t{{{0}}}.{1}.Build.0 = {1}|.NET",
project.Guid.ToString().ToUpper(),
conf.Name);
}
}
ss.WriteLine("\tEndGlobalSection");
if(solution.Files != null)
{
ss.WriteLine("\tGlobalSection(SolutionItems) = postSolution");
foreach(string file in solution.Files)
ss.WriteLine("\t\t{0} = {0}", file);
ss.WriteLine("\tEndGlobalSection");
}
ss.WriteLine("EndGlobal");
}
m_Kernel.CWDStack.Pop();
}
protected void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
ToolInfo toolInfo = (ToolInfo)m_Tools[project.Language];
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, toolInfo.FileExtension);
string userFile = projectFile + ".user";
Helper.DeleteIfExists(projectFile);
Helper.DeleteIfExists(userFile);
}
protected void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning Visual Studio {0} solution and project files", m_VersionName, solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "sln");
string suoFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "suo");
Helper.DeleteIfExists(slnFile);
Helper.DeleteIfExists(suoFile);
foreach(ProjectNode project in solution.Projects)
CleanProject(project);
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
public virtual void Write(Kernel kern)
{
m_Kernel = kern;
foreach(SolutionNode sol in m_Kernel.Solutions)
WriteSolution(sol);
m_Kernel = null;
}
public virtual void Clean(Kernel kern)
{
m_Kernel = kern;
foreach(SolutionNode sol in m_Kernel.Solutions)
CleanSolution(sol);
m_Kernel = null;
}
public virtual string Name
{
get
{
return "vs2003";
}
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Threading;
using NUnit.Framework;
using RestFiles.ServiceModel.Operations;
using ServiceStack.Common.Web;
using ServiceStack.Service;
using ServiceStack.ServiceClient.Web;
/* For syntax highlighting and better readability of this file, view it on GitHub:
* https://github.com/ServiceStack/ServiceStack.Examples/blob/master/src/RestFiles/RestFiles.Tests/AsyncRestClientTests.cs
*/
namespace RestFiles.Tests
{
/// <summary>
/// These test show how you can call ServiceStack REST web services asynchronously using an IRestClientAsync.
///
/// Async service calls are a great for GUI apps as they can be called without blocking the UI thread.
/// They are also great for performance as no time is spent on blocking IO calls.
/// </summary>
[TestFixture]
public class AsyncRestClientTests
{
public const string WebServiceHostUrl = "http://localhost:8080/";
private const string ReadmeFileContents = "THIS IS A README FILE";
private const string ReplacedFileContents = "THIS README FILE HAS BEEN REPLACED";
private const string TestUploadFileContents = "THIS FILE IS USED FOR UPLOADING IN TESTS";
public string FilesRootDir;
RestFilesHttpListener appHost;
[TestFixtureSetUp]
public void TextFixtureSetUp()
{
appHost = new RestFilesHttpListener();
appHost.Init();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
if (appHost != null) appHost.Dispose();
appHost = null;
}
[SetUp]
public void OnBeforeEachTest()
{
FilesRootDir = appHost.Config.RootDirectory;
if (Directory.Exists(FilesRootDir))
{
Directory.Delete(FilesRootDir, true);
}
Directory.CreateDirectory(FilesRootDir + "SubFolder");
Directory.CreateDirectory(FilesRootDir + "SubFolder2");
File.WriteAllText(Path.Combine(FilesRootDir, "README.txt"), ReadmeFileContents);
File.WriteAllText(Path.Combine(FilesRootDir, "TESTUPLOAD.txt"), TestUploadFileContents);
}
public IRestClientAsync CreateAsyncRestClient()
{
return new JsonServiceClient(WebServiceHostUrl); //Best choice for Ajax web apps, faster than XML
//return new XmlServiceClient(WebServiceHostUrl); //Ubiquitous structured data format best for supporting non .NET clients
//return new JsvServiceClient(WebServiceHostUrl); //Fastest, most compact and resilient format great for .NET to .NET client / server
}
private static void FailOnAsyncError<T>(T response, Exception ex)
{
Assert.Fail(ex.Message);
}
[Test]
public void Can_GetAsync_to_retrieve_existing_file()
{
var restClient = CreateAsyncRestClient();
FilesResponse response = null;
restClient.GetAsync<FilesResponse>("files/README.txt",
r => response = r, FailOnAsyncError);
Thread.Sleep(1000);
Assert.That(response.File.Contents, Is.EqualTo("THIS IS A README FILE"));
}
[Test]
public void Can_GetAsync_to_retrieve_existing_folder_listing()
{
var restClient = CreateAsyncRestClient();
FilesResponse response = null;
restClient.GetAsync<FilesResponse>("files/",
r => response = r, FailOnAsyncError);
Thread.Sleep(1000);
Assert.That(response.Directory.Folders.Count, Is.EqualTo(2));
Assert.That(response.Directory.Files.Count, Is.EqualTo(2));
}
[Test]
public void Can_PostAsync_to_path_without_uploaded_files_to_create_a_new_Directory()
{
var restClient = CreateAsyncRestClient();
FilesResponse response = null;
restClient.PostAsync<FilesResponse>("files/SubFolder/NewFolder",
new Files(),
r => response = r, FailOnAsyncError);
Thread.Sleep(1000);
Assert.That(Directory.Exists(FilesRootDir + "SubFolder/NewFolder"));
}
[Test]
public void Can_WebRequest_POST_upload_file_to_save_new_file_and_create_new_Directory()
{
var webRequest = WebRequest.Create(WebServiceHostUrl + "files/UploadedFiles/");
var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt");
webRequest.UploadFile(fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name));
Assert.That(Directory.Exists(FilesRootDir + "UploadedFiles"));
Assert.That(File.ReadAllText(FilesRootDir + "UploadedFiles/TESTUPLOAD.txt"),
Is.EqualTo(TestUploadFileContents));
}
[Test]
public void Can_RestClient_POST_upload_file_to_save_new_file_and_create_new_Directory()
{
var restClient = (IRestClient) CreateAsyncRestClient();
var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt");
restClient.PostFile<FilesResponse>("files/UploadedFiles/",
fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name));
Assert.That(Directory.Exists(FilesRootDir + "UploadedFiles"));
Assert.That(File.ReadAllText(FilesRootDir + "UploadedFiles/TESTUPLOAD.txt"),
Is.EqualTo(TestUploadFileContents));
}
[Test]
public void Can_PutAsync_to_replace_text_content_of_an_existing_file()
{
var restClient = CreateAsyncRestClient();
FilesResponse response = null;
restClient.PutAsync<FilesResponse>("files/README.txt",
new Files { TextContents = ReplacedFileContents },
r => response = r, FailOnAsyncError);
Thread.Sleep(1000);
Assert.That(File.ReadAllText(FilesRootDir + "README.txt"),
Is.EqualTo(ReplacedFileContents));
}
[Test]
public void Can_DeleteAsync_to_replace_text_content_of_an_existing_file()
{
var restClient = CreateAsyncRestClient();
FilesResponse response = null;
restClient.DeleteAsync<FilesResponse>("files/README.txt",
r => response = r, FailOnAsyncError);
Thread.Sleep(1000);
Assert.That(!File.Exists(FilesRootDir + "README.txt"));
}
/*
* Error Handling Tests
*/
[Test]
public void GET_a_file_that_doesnt_exist_throws_a_404_FileNotFoundException()
{
var restClient = CreateAsyncRestClient();
WebServiceException webEx = null;
FilesResponse response = null;
restClient.GetAsync<FilesResponse>("files/UnknownFolder",
r => response = r,
(r, ex) =>
{
response = r;
webEx = (WebServiceException)ex;
});
Thread.Sleep(1000);
Assert.That(webEx.StatusCode, Is.EqualTo(404));
Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(FileNotFoundException).Name));
Assert.That(response.ResponseStatus.Message, Is.EqualTo("Could not find: UnknownFolder"));
}
[Test]
public void POST_to_an_existing_file_throws_a_500_NotSupportedException()
{
var restClient = (IRestClient)CreateAsyncRestClient();
var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt");
try
{
var response = restClient.PostFile<FilesResponse>("files/README.txt",
fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name));
Assert.Fail("Should fail with NotSupportedException");
}
catch (WebServiceException webEx)
{
Assert.That(webEx.StatusCode, Is.EqualTo(500));
var response = (FilesResponse)webEx.ResponseDto;
Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(NotSupportedException).Name));
Assert.That(response.ResponseStatus.Message,
Is.EqualTo("POST only supports uploading new files. Use PUT to replace contents of an existing file"));
}
}
[Test]
public void PUT_to_replace_a_non_existing_file_throws_404()
{
var restClient = CreateAsyncRestClient();
WebServiceException webEx = null;
FilesResponse response = null;
restClient.PutAsync<FilesResponse>("files/non-existing-file.txt",
new Files { TextContents = ReplacedFileContents },
r => response = r,
(r, ex) =>
{
response = r;
webEx = (WebServiceException)ex;
});
Thread.Sleep(1000);
Assert.That(webEx.StatusCode, Is.EqualTo(404));
Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(FileNotFoundException).Name));
Assert.That(response.ResponseStatus.Message, Is.EqualTo("Could not find: non-existing-file.txt"));
}
[Test]
public void DELETE_a_non_existing_file_throws_404()
{
var restClient = CreateAsyncRestClient();
WebServiceException webEx = null;
FilesResponse response = null;
restClient.DeleteAsync<FilesResponse>("files/non-existing-file.txt",
r => response = r,
(r, ex) =>
{
response = r;
webEx = (WebServiceException)ex;
});
Thread.Sleep(1000);
Assert.That(webEx.StatusCode, Is.EqualTo(404));
Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(FileNotFoundException).Name));
Assert.That(response.ResponseStatus.Message, Is.EqualTo("Could not find: non-existing-file.txt"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
using Umbraco.Cms.Infrastructure.Persistence.Querying;
using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
{
/// <summary>
/// Represents a repository for doing CRUD operations for <see cref="IContentType"/>
/// </summary>
internal class ContentTypeRepository : ContentTypeRepositoryBase<IContentType>, IContentTypeRepository
{
public ContentTypeRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger<ContentTypeRepository> logger, IContentTypeCommonRepository commonRepository, ILanguageRepository languageRepository, IShortStringHelper shortStringHelper)
: base(scopeAccessor, cache, logger, commonRepository, languageRepository, shortStringHelper)
{ }
protected override bool SupportsPublishing => ContentType.SupportsPublishingConst;
protected override IRepositoryCachePolicy<IContentType, int> CreateCachePolicy()
{
return new FullDataSetRepositoryCachePolicy<IContentType, int>(GlobalIsolatedCache, ScopeAccessor, GetEntityId, /*expires:*/ true);
}
// every GetExists method goes cachePolicy.GetSomething which in turns goes PerformGetAll,
// since this is a FullDataSet policy - and everything is cached
// so here,
// every PerformGet/Exists just GetMany() and then filters
// except PerformGetAll which is the one really doing the job
// TODO: the filtering is highly inefficient as we deep-clone everything
// there should be a way to GetMany(predicate) right from the cache policy!
// and ah, well, this all caching should be refactored + the cache refreshers
// should to repository.Clear() not deal with magic caches by themselves
protected override IContentType PerformGet(int id)
=> GetMany().FirstOrDefault(x => x.Id == id);
protected override IContentType PerformGet(Guid id)
=> GetMany().FirstOrDefault(x => x.Key == id);
protected override IContentType PerformGet(string alias)
=> GetMany().FirstOrDefault(x => x.Alias.InvariantEquals(alias));
protected override bool PerformExists(Guid id)
=> GetMany().FirstOrDefault(x => x.Key == id) != null;
protected override IEnumerable<IContentType> GetAllWithFullCachePolicy()
{
return CommonRepository.GetAllTypes().OfType<IContentType>();
}
protected override IEnumerable<IContentType> PerformGetAll(params Guid[] ids)
{
var all = GetMany();
return ids.Any() ? all.Where(x => ids.Contains(x.Key)) : all;
}
protected override IEnumerable<IContentType> PerformGetByQuery(IQuery<IContentType> query)
{
var baseQuery = GetBaseQuery(false);
var translator = new SqlTranslator<IContentType>(baseQuery, query);
var sql = translator.Translate();
var ids = Database.Fetch<int>(sql).Distinct().ToArray();
return ids.Length > 0 ? GetMany(ids).OrderBy(x => x.Name) : Enumerable.Empty<IContentType>();
}
/// <inheritdoc />
public IEnumerable<IContentType> GetByQuery(IQuery<PropertyType> query)
{
var ints = PerformGetByQuery(query).ToArray();
return ints.Length > 0 ? GetMany(ints) : Enumerable.Empty<IContentType>();
}
protected IEnumerable<int> PerformGetByQuery(IQuery<PropertyType> query)
{
// used by DataTypeService to remove properties
// from content types if they have a deleted data type - see
// notes in DataTypeService.Delete as it's a bit weird
var sqlClause = Sql()
.SelectAll()
.From<PropertyTypeGroupDto>()
.RightJoin<PropertyTypeDto>()
.On<PropertyTypeGroupDto, PropertyTypeDto>(left => left.Id, right => right.PropertyTypeGroupId)
.InnerJoin<DataTypeDto>()
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId);
var translator = new SqlTranslator<PropertyType>(sqlClause, query);
var sql = translator.Translate()
.OrderBy<PropertyTypeDto>(x => x.PropertyTypeGroupId);
return Database
.FetchOneToMany<PropertyTypeGroupDto>(x => x.PropertyTypeDtos, sql)
.Select(x => x.ContentTypeNodeId).Distinct();
}
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAllPropertyTypeAliases()
{
return Database.Fetch<string>("SELECT DISTINCT Alias FROM cmsPropertyType ORDER BY Alias");
}
/// <summary>
/// Gets all content type aliases
/// </summary>
/// <param name="objectTypes">
/// If this list is empty, it will return all content type aliases for media, members and content, otherwise
/// it will only return content type aliases for the object types specified
/// </param>
/// <returns></returns>
public IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes)
{
var sql = Sql()
.Select("cmsContentType.alias")
.From<ContentTypeDto>()
.InnerJoin<NodeDto>()
.On<ContentTypeDto, NodeDto>(dto => dto.NodeId, dto => dto.NodeId);
if (objectTypes.Any())
{
sql = sql.WhereIn<NodeDto>(dto => dto.NodeObjectType, objectTypes);
}
return Database.Fetch<string>(sql);
}
public IEnumerable<int> GetAllContentTypeIds(string[] aliases)
{
if (aliases.Length == 0) return Enumerable.Empty<int>();
var sql = Sql()
.Select<ContentTypeDto>(x => x.NodeId)
.From<ContentTypeDto>()
.InnerJoin<NodeDto>()
.On<ContentTypeDto, NodeDto>(dto => dto.NodeId, dto => dto.NodeId)
.Where<ContentTypeDto>(dto => aliases.Contains(dto.Alias));
return Database.Fetch<int>(sql);
}
protected override Sql<ISqlContext> GetBaseQuery(bool isCount)
{
var sql = Sql();
sql = isCount
? sql.SelectCount()
: sql.Select<ContentTypeDto>(x => x.NodeId);
sql
.From<ContentTypeDto>()
.InnerJoin<NodeDto>().On<ContentTypeDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.LeftJoin<ContentTypeTemplateDto>().On<ContentTypeTemplateDto, ContentTypeDto>(left => left.ContentTypeNodeId, right => right.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
return sql;
}
protected override string GetBaseWhereClause()
{
return $"{Constants.DatabaseSchema.Tables.Node}.id = @id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var l = (List<string>) base.GetDeleteClauses(); // we know it's a list
l.Add("DELETE FROM cmsDocumentType WHERE contentTypeNodeId = @id");
l.Add("DELETE FROM cmsContentType WHERE nodeId = @id");
l.Add("DELETE FROM umbracoNode WHERE id = @id");
return l;
}
protected override Guid NodeObjectTypeId => Cms.Core.Constants.ObjectTypes.DocumentType;
/// <summary>
/// Deletes a content type
/// </summary>
/// <param name="entity"></param>
/// <remarks>
/// First checks for children and removes those first
/// </remarks>
protected override void PersistDeletedItem(IContentType entity)
{
var query = Query<IContentType>().Where(x => x.ParentId == entity.Id);
var children = Get(query);
foreach (var child in children)
{
PersistDeletedItem(child);
}
//Before we call the base class methods to run all delete clauses, we need to first
// delete all of the property data associated with this document type. Normally this will
// be done in the ContentTypeService by deleting all associated content first, but in some cases
// like when we switch a document type, there is property data left over that is linked
// to the previous document type. So we need to ensure it's removed.
var sql = Sql()
.Select("DISTINCT " + Cms.Core.Constants.DatabaseSchema.Tables.PropertyData + ".propertytypeid")
.From<PropertyDataDto>()
.InnerJoin<PropertyTypeDto>()
.On<PropertyDataDto, PropertyTypeDto>(dto => dto.PropertyTypeId, dto => dto.Id)
.InnerJoin<ContentTypeDto>()
.On<ContentTypeDto, PropertyTypeDto>(dto => dto.NodeId, dto => dto.ContentTypeId)
.Where<ContentTypeDto>(dto => dto.NodeId == entity.Id);
//Delete all PropertyData where propertytypeid EXISTS in the subquery above
Database.Execute(SqlSyntax.GetDeleteSubquery(Cms.Core.Constants.DatabaseSchema.Tables.PropertyData, "propertytypeid", sql));
base.PersistDeletedItem(entity);
}
protected override void PersistNewItem(IContentType entity)
{
if (string.IsNullOrWhiteSpace(entity.Alias))
{
var ex = new Exception($"ContentType '{entity.Name}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.");
Logger.LogError("ContentType '{EntityName}' cannot have an empty Alias. This is most likely due to invalid characters stripped from the Alias.", entity.Name);
throw ex;
}
entity.AddingEntity();
PersistNewBaseContentType(entity);
PersistTemplates(entity, false);
PersistHistoryCleanup(entity);
entity.ResetDirtyProperties();
}
protected void PersistTemplates(IContentType entity, bool clearAll)
{
// remove and insert, if required
Database.Delete<ContentTypeTemplateDto>("WHERE contentTypeNodeId = @Id", new { Id = entity.Id });
// we could do it all in foreach if we assume that the default template is an allowed template??
var defaultTemplateId = entity.DefaultTemplateId;
if (defaultTemplateId > 0)
{
Database.Insert(new ContentTypeTemplateDto
{
ContentTypeNodeId = entity.Id,
TemplateNodeId = defaultTemplateId,
IsDefault = true
});
}
foreach (var template in entity.AllowedTemplates.Where(x => x != null && x.Id != defaultTemplateId))
{
Database.Insert(new ContentTypeTemplateDto
{
ContentTypeNodeId = entity.Id,
TemplateNodeId = template.Id,
IsDefault = false
});
}
}
protected override void PersistUpdatedItem(IContentType entity)
{
ValidateAlias(entity);
//Updates Modified date
entity.UpdatingEntity();
//Look up parent to get and set the correct Path if ParentId has changed
if (entity.IsPropertyDirty("ParentId"))
{
var parent = Database.First<NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
entity.Path = string.Concat(parent.Path, ",", entity.Id);
entity.Level = parent.Level + 1;
var maxSortOrder =
Database.ExecuteScalar<int>(
"SELECT coalesce(max(sortOrder),0) FROM umbracoNode WHERE parentid = @ParentId AND nodeObjectType = @NodeObjectType",
new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });
entity.SortOrder = maxSortOrder + 1;
}
PersistUpdatedBaseContentType(entity);
PersistTemplates(entity, true);
PersistHistoryCleanup(entity);
entity.ResetDirtyProperties();
}
private void PersistHistoryCleanup(IContentType entity)
{
// historyCleanup property is not mandatory for api endpoint, handle the case where it's not present.
// DocumentTypeSave doesn't handle this for us like ContentType constructors do.
if (entity is IContentTypeWithHistoryCleanup entityWithHistoryCleanup)
{
ContentVersionCleanupPolicyDto dto = new ContentVersionCleanupPolicyDto()
{
ContentTypeId = entity.Id,
Updated = DateTime.Now,
PreventCleanup = entityWithHistoryCleanup.HistoryCleanup?.PreventCleanup ?? false,
KeepAllVersionsNewerThanDays = entityWithHistoryCleanup.HistoryCleanup?.KeepAllVersionsNewerThanDays,
KeepLatestVersionPerDayForDays = entityWithHistoryCleanup.HistoryCleanup?.KeepLatestVersionPerDayForDays
};
Database.InsertOrUpdate(dto);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PagerSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
/// <devdoc>
/// <para>Specifies the <see cref='System.Web.UI.WebControls.GridView'/> pager setting for the control. This class cannot be inherited.</para>
/// </devdoc>
[TypeConverter(typeof(ExpandableObjectConverter))]
public sealed class PagerSettings : IStateManager {
private StateBag _viewState;
private bool _isTracking;
[
Browsable(false)
]
public event EventHandler PropertyChanged;
/// <devdoc>
/// Creates a new instance of PagerSettings.
/// </devdoc>
public PagerSettings() {
_viewState = new StateBag();
}
/// <devdoc>
/// <para>Gets or sets the image path to be used for the First
/// page button.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
NotifyParentProperty(true),
Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
UrlProperty(),
WebSysDescription(SR.PagerSettings_FirstPageImageUrl)
]
public string FirstPageImageUrl {
get {
object o = ViewState["FirstPageImageUrl"];
if (o != null) {
return(string)o;
}
return String.Empty;
}
set {
string oldValue = FirstPageImageUrl;
if (oldValue != value) {
ViewState["FirstPageImageUrl"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// Gets or sets the text to be used for the First page
/// button.
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue("<<"),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_FirstPageText)
]
public string FirstPageText {
get {
object o = ViewState["FirstPageText"];
if (o != null) {
return(string)o;
}
return "<<";
}
set {
string oldValue = FirstPageText;
if (oldValue != value) {
ViewState["FirstPageText"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// </devdoc>
internal bool IsPagerOnBottom {
get {
PagerPosition position = Position;
return(position == PagerPosition.Bottom) ||
(position == PagerPosition.TopAndBottom);
}
}
/// <devdoc>
/// </devdoc>
internal bool IsPagerOnTop {
get {
PagerPosition position = Position;
return(position == PagerPosition.Top) ||
(position == PagerPosition.TopAndBottom);
}
}
/// <devdoc>
/// <para>Gets or sets the image path to be used for the Last
/// page button.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
NotifyParentProperty(true),
Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
UrlProperty(),
WebSysDescription(SR.PagerSettings_LastPageImageUrl)
]
public string LastPageImageUrl {
get {
object o = ViewState["LastPageImageUrl"];
if (o != null) {
return(string)o;
}
return String.Empty;
}
set {
string oldValue = LastPageImageUrl;
if (oldValue != value) {
ViewState["LastPageImageUrl"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// Gets or sets the text to be used for the Last page
/// button.
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(">>"),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_LastPageText)
]
public string LastPageText {
get {
object o = ViewState["LastPageText"];
if (o != null) {
return(string)o;
}
return ">>";
}
set {
string oldValue = LastPageText;
if (oldValue != value) {
ViewState["LastPageText"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// Gets or sets the type of Paging UI to use.
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(PagerButtons.Numeric),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_Mode)
]
public PagerButtons Mode {
get {
object o = ViewState["PagerMode"];
if (o != null) {
return(PagerButtons)o;
}
return PagerButtons.Numeric;
}
set {
if (value < PagerButtons.NextPrevious || value > PagerButtons.NumericFirstLast) {
throw new ArgumentOutOfRangeException("value");
}
PagerButtons oldValue = Mode;
if (oldValue != value) {
ViewState["PagerMode"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// <para>Gets or sets the image path to be used for the Next
/// page button.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
NotifyParentProperty(true),
Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
UrlProperty(),
WebSysDescription(SR.PagerSettings_NextPageImageUrl)
]
public string NextPageImageUrl {
get {
object o = ViewState["NextPageImageUrl"];
if (o != null) {
return(string)o;
}
return String.Empty;
}
set {
string oldValue = NextPageImageUrl;
if (oldValue != value) {
ViewState["NextPageImageUrl"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// Gets or sets the text to be used for the Next page
/// button.
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(">"),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_NextPageText)
]
public string NextPageText {
get {
object o = ViewState["NextPageText"];
if (o != null) {
return(string)o;
}
return ">";
}
set {
string oldValue = NextPageText;
if (oldValue != value) {
ViewState["NextPageText"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// <para>Gets or sets the number of pages to show in the
/// paging UI when the mode is <see langword='PagerMode.NumericPages'/>
/// .</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(10),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_PageButtonCount)
]
public int PageButtonCount {
get {
object o = ViewState["PageButtonCount"];
if (o != null) {
return(int)o;
}
return 10;
}
set {
if (value < 1) {
throw new ArgumentOutOfRangeException("value");
}
int oldValue = PageButtonCount;
if (oldValue != value) {
ViewState["PageButtonCount"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// <para> Gets or sets the vertical
/// position of the paging UI bar with
/// respect to its associated control.</para>
/// </devdoc>
[
WebCategory("Layout"),
DefaultValue(PagerPosition.Bottom),
NotifyParentProperty(true),
WebSysDescription(SR.PagerStyle_Position)
]
public PagerPosition Position {
get {
object o = ViewState["Position"];
if (o != null) {
return(PagerPosition)o;
}
return PagerPosition.Bottom;
}
set {
if (value < PagerPosition.Bottom || value > PagerPosition.TopAndBottom) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["Position"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets the image path to be used for the Previous
/// page button.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(""),
NotifyParentProperty(true),
Editor("System.Web.UI.Design.ImageUrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
UrlProperty(),
WebSysDescription(SR.PagerSettings_PreviousPageImageUrl)
]
public string PreviousPageImageUrl {
get {
object o = ViewState["PreviousPageImageUrl"];
if (o != null) {
return(string)o;
}
return String.Empty;
}
set {
string oldValue = PreviousPageImageUrl;
if (oldValue != value) {
ViewState["PreviousPageImageUrl"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// <para>Gets or sets the text to be used for the Previous
/// page button.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue("<"),
NotifyParentProperty(true),
WebSysDescription(SR.PagerSettings_PreviousPageText)
]
public string PreviousPageText {
get {
object o = ViewState["PreviousPageText"];
if (o != null) {
return(string)o;
}
return "<";
}
set {
string oldValue = PreviousPageText;
if (oldValue != value) {
ViewState["PreviousPageText"] = value;
OnPropertyChanged();
}
}
}
/// <devdoc>
/// <para> Gets or set whether the paging
/// UI is to be shown.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(true),
NotifyParentProperty(true),
WebSysDescription(SR.PagerStyle_Visible)
]
public bool Visible {
get {
object o = ViewState["PagerVisible"];
if (o != null) {
return(bool)o;
}
return true;
}
set {
ViewState["PagerVisible"] = value;
}
}
/// <devdoc>
/// <para>Gets the statebag for the PagerSettings. This property is read-only.</para>
/// </devdoc>
private StateBag ViewState {
get {
return _viewState;
}
}
/// <devdoc>
/// DataBound Controls use this event to rebind when settings have changed.
/// </devdoc>
void OnPropertyChanged() {
if (PropertyChanged != null) {
PropertyChanged(this, EventArgs.Empty);
}
}
/// <devdoc>
/// The propertyGrid uses ToString() to determine what text should be in the PagerSetting's edit box.
/// </devdoc>
public override string ToString() {
return String.Empty;
}
#region IStateManager implementation
/// <internalonly/>
bool IStateManager.IsTrackingViewState {
get {
return _isTracking;
}
}
/// <internalonly/>
void IStateManager.LoadViewState(object state) {
if (state != null) {
((IStateManager)ViewState).LoadViewState(state);
}
}
/// <internalonly/>
object IStateManager.SaveViewState() {
object state = ((IStateManager)ViewState).SaveViewState();
return state;
}
/// <internalonly/>
void IStateManager.TrackViewState() {
_isTracking = true;
ViewState.TrackViewState();
}
#endregion
}
}
| |
using NBitcoin;
using NBitcoin.RPC;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.Backend.Models.Responses;
using WalletWasabi.Bases;
using WalletWasabi.Blockchain.Analysis.FeesEstimation;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Models;
using WalletWasabi.Stores;
using WalletWasabi.Tor.Socks5.Exceptions;
using WalletWasabi.WebClients.Wasabi;
namespace WalletWasabi.Services
{
public class WasabiSynchronizer : NotifyPropertyChangedBase, IFeeProvider
{
private const long StateNotStarted = 0;
private const long StateRunning = 1;
private const long StateStopping = 2;
private const long StateStopped = 3;
private decimal _usdExchangeRate;
private AllFeeEstimate _allFeeEstimate;
private TorStatus _torStatus;
private BackendStatus _backendStatus;
/// <summary>
/// Value can be any of: <see cref="StateNotStarted"/>, <see cref="StateRunning"/>, <see cref="StateStopping"/> and <see cref="StateStopped"/>.
/// </summary>
private long _running;
private long _blockRequests; // There are priority requests in queue.
/// <param name="httpClientFactory">The class takes ownership of the instance.</param>
public WasabiSynchronizer(Network network, BitcoinStore bitcoinStore, HttpClientFactory httpClientFactory)
{
Network = network;
LastResponse = null;
_running = StateNotStarted;
BitcoinStore = bitcoinStore;
HttpClientFactory = httpClientFactory;
WasabiClient = httpClientFactory.SharedWasabiClient;
StopCts = new CancellationTokenSource();
}
#region EventsPropertiesMembers
public event EventHandler<AllFeeEstimate>? AllFeeEstimateChanged;
public event EventHandler<bool>? ResponseArrivedIsGenSocksServFail;
public event EventHandler<SynchronizeResponse>? ResponseArrived;
public SynchronizeResponse? LastResponse { get; private set; }
/// <summary><see cref="WasabiSynchronizer"/> is responsible for disposing of this object.</summary>
public HttpClientFactory HttpClientFactory { get; }
public WasabiClient WasabiClient { get; }
public Network Network { get; private set; }
/// <summary>
/// Gets the Bitcoin price in USD.
/// </summary>
public decimal UsdExchangeRate
{
get => _usdExchangeRate;
private set => RaiseAndSetIfChanged(ref _usdExchangeRate, value);
}
public AllFeeEstimate AllFeeEstimate
{
get => _allFeeEstimate;
private set
{
if (RaiseAndSetIfChanged(ref _allFeeEstimate, value))
{
AllFeeEstimateChanged?.Invoke(this, value);
}
}
}
public TorStatus TorStatus
{
get => _torStatus;
private set => RaiseAndSetIfChanged(ref _torStatus, value);
}
public BackendStatus BackendStatus
{
get => _backendStatus;
private set => RaiseAndSetIfChanged(ref _backendStatus, value);
}
public TimeSpan MaxRequestIntervalForMixing { get; set; }
public BitcoinStore BitcoinStore { get; private set; }
public bool IsRunning => Interlocked.Read(ref _running) == StateRunning;
/// <summary>
/// Cancellation token source for stopping <see cref="WasabiSynchronizer"/>.
/// </summary>
private CancellationTokenSource StopCts { get; }
public bool AreRequestsBlocked() => Interlocked.Read(ref _blockRequests) == 1;
public void BlockRequests() => Interlocked.Exchange(ref _blockRequests, 1);
public void EnableRequests() => Interlocked.Exchange(ref _blockRequests, 0);
#endregion EventsPropertiesMembers
#region Initializers
public void Start(TimeSpan requestInterval, TimeSpan feeQueryRequestInterval, int maxFiltersToSyncAtInitialization)
{
Logger.LogTrace($"> {nameof(requestInterval)}={requestInterval}, {nameof(feeQueryRequestInterval)}={feeQueryRequestInterval}, {nameof(maxFiltersToSyncAtInitialization)}={maxFiltersToSyncAtInitialization}");
Guard.NotNull(nameof(requestInterval), requestInterval);
Guard.MinimumAndNotNull(nameof(feeQueryRequestInterval), feeQueryRequestInterval, requestInterval);
Guard.MinimumAndNotNull(nameof(maxFiltersToSyncAtInitialization), maxFiltersToSyncAtInitialization, 0);
MaxRequestIntervalForMixing = requestInterval; // Let's start with this, it'll be modified from outside.
if (Interlocked.CompareExchange(ref _running, StateRunning, StateNotStarted) != StateNotStarted)
{
return;
}
Task.Run(async () =>
{
Logger.LogTrace("> Wasabi synchronizer thread starts.");
try
{
DateTimeOffset lastFeeQueried = DateTimeOffset.UtcNow - feeQueryRequestInterval;
bool ignoreRequestInterval = false;
var hashChain = BitcoinStore.SmartHeaderChain;
EnableRequests();
while (IsRunning)
{
try
{
while (AreRequestsBlocked())
{
await Task.Delay(3000, StopCts.Token).ConfigureAwait(false);
}
EstimateSmartFeeMode? estimateMode = null;
TimeSpan elapsed = DateTimeOffset.UtcNow - lastFeeQueried;
if (elapsed >= feeQueryRequestInterval)
{
estimateMode = EstimateSmartFeeMode.Conservative;
}
SynchronizeResponse response;
var lastUsedApiVersion = WasabiClient.ApiVersion;
try
{
if (!IsRunning)
{
return;
}
response = await WasabiClient.GetSynchronizeAsync(hashChain.TipHash, maxFiltersToSyncAtInitialization, estimateMode, StopCts.Token)
.WithAwaitCancellationAsync(StopCts.Token, 300)
.ConfigureAwait(false);
// NOT GenSocksServErr
BackendStatus = BackendStatus.Connected;
TorStatus = TorStatus.Running;
DoNotGenSocksServFail();
}
catch (HttpRequestException ex) when (ex.InnerException is TorException innerEx)
{
TorStatus = innerEx is TorConnectionException ? TorStatus.NotRunning : TorStatus.Running;
BackendStatus = BackendStatus.NotConnected;
HandleIfGenSocksServFail(ex);
HandleIfGenSocksServFail(innerEx);
throw;
}
catch (HttpRequestException ex) when (ex.Message.Contains("Not Found"))
{
TorStatus = TorStatus.Running;
BackendStatus = BackendStatus.NotConnected;
try
{
// Backend API version might be updated meanwhile. Trying to update the versions.
var result = await WasabiClient.CheckUpdatesAsync(StopCts.Token).ConfigureAwait(false);
// If the backend is compatible and the Api version updated then we just used the wrong API.
if (result.BackendCompatible && lastUsedApiVersion != WasabiClient.ApiVersion)
{
// Next request will be fine, do not throw exception.
ignoreRequestInterval = true;
continue;
}
else
{
throw;
}
}
catch (Exception x)
{
HandleIfGenSocksServFail(x);
throw;
}
}
catch (Exception ex)
{
TorStatus = TorStatus.Running;
BackendStatus = BackendStatus.Connected;
HandleIfGenSocksServFail(ex);
throw;
}
if (response.AllFeeEstimate is { } && response.AllFeeEstimate.Estimations.Any())
{
lastFeeQueried = DateTimeOffset.UtcNow;
AllFeeEstimate = response.AllFeeEstimate;
}
if (response.Filters.Count() == maxFiltersToSyncAtInitialization)
{
ignoreRequestInterval = true;
}
else
{
ignoreRequestInterval = false;
}
hashChain.UpdateServerTipHeight((uint)response.BestHeight);
ExchangeRate? exchangeRate = response.ExchangeRates.FirstOrDefault();
if (exchangeRate is { Rate: > 0 })
{
UsdExchangeRate = exchangeRate.Rate;
}
if (response.FiltersResponseState == FiltersResponseState.NewFilters)
{
var filters = response.Filters;
var firstFilter = filters.First();
if (hashChain.TipHeight + 1 != firstFilter.Header.Height)
{
// We have a problem.
// We have wrong filters, the heights are not in sync with the server's.
Logger.LogError($"Inconsistent index state detected.{Environment.NewLine}" +
$"{nameof(hashChain)}.{nameof(hashChain.TipHeight)}:{hashChain.TipHeight}{Environment.NewLine}" +
$"{nameof(hashChain)}.{nameof(hashChain.HashesLeft)}:{hashChain.HashesLeft}{Environment.NewLine}" +
$"{nameof(hashChain)}.{nameof(hashChain.TipHash)}:{hashChain.TipHash}{Environment.NewLine}" +
$"{nameof(hashChain)}.{nameof(hashChain.HashCount)}:{hashChain.HashCount}{Environment.NewLine}" +
$"{nameof(hashChain)}.{nameof(hashChain.ServerTipHeight)}:{hashChain.ServerTipHeight}{Environment.NewLine}" +
$"{nameof(firstFilter)}.{nameof(firstFilter.Header)}.{nameof(firstFilter.Header.BlockHash)}:{firstFilter.Header.BlockHash}{Environment.NewLine}" +
$"{nameof(firstFilter)}.{nameof(firstFilter.Header)}.{nameof(firstFilter.Header.Height)}:{firstFilter.Header.Height}");
await BitcoinStore.IndexStore.RemoveAllImmmatureFiltersAsync(StopCts.Token, deleteAndCrashIfMature: true).ConfigureAwait(false);
}
else
{
await BitcoinStore.IndexStore.AddNewFiltersAsync(filters, StopCts.Token).ConfigureAwait(false);
if (filters.Count() == 1)
{
Logger.LogInfo($"Downloaded filter for block {firstFilter.Header.Height}.");
}
else
{
Logger.LogInfo($"Downloaded filters for blocks from {firstFilter.Header.Height} to {filters.Last().Header.Height}.");
}
}
}
else if (response.FiltersResponseState == FiltersResponseState.BestKnownHashNotFound)
{
// Reorg happened
// 1. Rollback index
FilterModel reorgedFilter = await BitcoinStore.IndexStore.RemoveLastFilterAsync(StopCts.Token).ConfigureAwait(false);
Logger.LogInfo($"REORG Invalid Block: {reorgedFilter.Header.BlockHash}.");
ignoreRequestInterval = true;
}
else if (response.FiltersResponseState == FiltersResponseState.NoNewFilter)
{
// We are synced.
// Assert index state.
if (response.BestHeight > hashChain.TipHeight) // If the server's tip height is larger than ours, we're missing a filter, our index got corrupted.
{
// If still bad delete filters and crash the software?
await BitcoinStore.IndexStore.RemoveAllImmmatureFiltersAsync(StopCts.Token, deleteAndCrashIfMature: true).ConfigureAwait(false);
}
}
LastResponse = response;
ResponseArrived?.Invoke(this, response);
}
catch (OperationCanceledException)
{
Logger.LogInfo("Wasabi Synchronizer execution was canceled.");
}
catch (TorConnectionException ex)
{
Logger.LogError(ex);
try
{
await Task.Delay(3000, StopCts.Token).ConfigureAwait(false); // Give other threads time to do stuff.
}
catch (TaskCanceledException ex2)
{
Logger.LogTrace(ex2);
}
}
catch (TimeoutException ex)
{
Logger.LogTrace(ex);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
finally
{
if (IsRunning && !ignoreRequestInterval)
{
try
{
int delay = (int)Math.Min(requestInterval.TotalMilliseconds, MaxRequestIntervalForMixing.TotalMilliseconds);
await Task.Delay(delay, StopCts.Token).ConfigureAwait(false); // Ask for new index in every requestInterval.
}
catch (TaskCanceledException ex)
{
Logger.LogTrace(ex);
}
}
}
}
}
finally
{
Interlocked.CompareExchange(ref _running, StateStopped, StateStopping); // If IsStopping, make it stopped.
}
Logger.LogTrace("< Wasabi synchronizer thread ends.");
});
Logger.LogTrace("<");
}
#endregion Initializers
#region Methods
private void HandleIfGenSocksServFail(Exception ex)
{
// IS GenSocksServFail?
if (ex.ToString().Contains("GeneralSocksServerFailure", StringComparison.OrdinalIgnoreCase))
{
// IS GenSocksServFail
DoGenSocksServFail();
}
else
{
// NOT GenSocksServFail
DoNotGenSocksServFail();
}
}
private void DoGenSocksServFail()
{
ResponseArrivedIsGenSocksServFail?.Invoke(this, true);
}
private void DoNotGenSocksServFail()
{
ResponseArrivedIsGenSocksServFail?.Invoke(this, false);
}
#endregion Methods
/// <summary>
/// Stops <see cref="WasabiSynchronizer"/>.
/// </summary>
/// <remarks>The method is supposed to be called just once.</remarks>
public async Task StopAsync()
{
Logger.LogTrace(">");
Interlocked.CompareExchange(ref _running, StateStopping, StateRunning); // If running, make it stopping.
StopCts.Cancel();
while (Interlocked.CompareExchange(ref _running, StateStopped, StateNotStarted) == StateStopping)
{
await Task.Delay(50).ConfigureAwait(false);
}
HttpClientFactory.Dispose();
StopCts.Dispose();
EnableRequests(); // Enable requests (it's possible something is being blocked outside the class by AreRequestsBlocked.
Logger.LogTrace("<");
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Runtime.InteropServices;
using System.Text;
namespace HWD
{
public class SQLEngine
{
public static SqlConnection sqlcon = new SqlConnection();
public static IList items = null;
internal static void GetDB()
{
items = new ArrayList();
if (sqlcon.ConnectionString.Length < 1)
GetSQL();
SqlCommand sqlcommand = new SqlCommand("SELECT DISTINCT ComputerName FROM HWD", sqlcon);
sqlcon.Open();
SqlDataReader sqlrd = sqlcommand.ExecuteReader();
while(sqlrd.Read())
{
items.Add(new MyItem(sqlrd.GetString(0)));
}
sqlrd.Close();
sqlcon.Close();
}
internal static void GetSQL()
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\HWD\\config.xml");
string auth = xmldoc.FirstChild["Auth"].InnerText;
string SQLServer = xmldoc.FirstChild["SQLServer"].InnerText;
string SQLUser = xmldoc.FirstChild["SQLUser"].InnerText;
string SQLPwd = Utilities.Decrypt(xmldoc.FirstChild["SQLPwd"].InnerText);
string SQLCatalog = xmldoc.FirstChild["SQLCatalog"].InnerText;
string strConn = ";data source=\"" + SQLServer +
"\";persist security info=True;initial catalog=" + SQLCatalog;
if (auth == "sql")
{
strConn = "user id=" + SQLUser + ";password=" + SQLPwd + strConn;
}
else
{
strConn = "Integrated Security=SSPI" + strConn;
}
sqlcon.ConnectionString = strConn;
}
internal static string GetValue(string column, string system)
{
string temp = string.Empty;
SqlCommand sqlcommand = new SqlCommand("SELECT " + column + " FROM HWD WHERE ComputerName = '" + system + "'", sqlcon);
sqlcon.Open();
SqlDataReader sqlrd = sqlcommand.ExecuteReader();
while(sqlrd.Read())
{
temp = sqlrd.GetString(0);
}
sqlrd.Close();
sqlcon.Close();
return temp;
}
public SQLEngine()
{
}
}
class Utilities
{
[DllImport( "crypt32.dll",
SetLastError=true,
CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private static extern
bool CryptProtectData( ref DATA_BLOB pPlainText,
string szDescription,
ref DATA_BLOB pEntropy,
IntPtr pReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPrompt,
int dwFlags,
ref DATA_BLOB pCipherText);
[DllImport( "crypt32.dll",
SetLastError=true,
CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private static extern
bool CryptUnprotectData(ref DATA_BLOB pCipherText,
ref string pszDescription,
ref DATA_BLOB pEntropy,
IntPtr pReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPrompt,
int dwFlags,
ref DATA_BLOB pPlainText);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct DATA_BLOB
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct CRYPTPROTECT_PROMPTSTRUCT
{
public int cbSize;
public int dwPromptFlags;
public IntPtr hwndApp;
public string szPrompt;
}
public enum KeyType {UserKey = 1, MachineKey};
private const int CRYPTPROTECT_UI_FORBIDDEN = 0x1;
private const int CRYPTPROTECT_LOCAL_MACHINE = 0x4;
private static byte [] Encrypt (byte [] text, KeyType keyType)
{
if(text==null) text = new byte[0];
DATA_BLOB blobText = new DATA_BLOB();
DATA_BLOB fill = new DATA_BLOB();
DATA_BLOB textEncryptedBlob = new DATA_BLOB();
byte[] cipherTextBytes;
try
{
blobText.pbData = Marshal.AllocHGlobal(text.Length);
blobText.cbData = text.Length;
Marshal.Copy(text, 0, blobText.pbData, text.Length);
byte[] strFill={0};
fill.pbData = Marshal.AllocHGlobal(strFill.Length);
fill.cbData = strFill.Length;
Marshal.Copy(strFill, 0, fill.pbData, strFill.Length);
int flags = CRYPTPROTECT_UI_FORBIDDEN;
if (keyType == KeyType.MachineKey)
flags |= CRYPTPROTECT_LOCAL_MACHINE;
string desc="Password Sql Server";
CRYPTPROTECT_PROMPTSTRUCT ps =
new CRYPTPROTECT_PROMPTSTRUCT();
ps.cbSize = Marshal.SizeOf(
typeof(CRYPTPROTECT_PROMPTSTRUCT));
ps.dwPromptFlags= 0;
ps.hwndApp = IntPtr.Zero ;
ps.szPrompt = null;
bool success = CryptProtectData(ref blobText,
desc,
ref fill,
IntPtr.Zero,
ref ps,
flags,
ref textEncryptedBlob);
cipherTextBytes = new byte[textEncryptedBlob.cbData];
Marshal.Copy(textEncryptedBlob.pbData,
cipherTextBytes,
0,
textEncryptedBlob.cbData);
}
catch
{
throw new Exception("Can not Decryp Message");
}
finally
{
if(textEncryptedBlob.pbData!=IntPtr.Zero)
Marshal.FreeHGlobal (textEncryptedBlob.pbData);
if(blobText.pbData!=IntPtr.Zero)
Marshal.FreeHGlobal (blobText.pbData);
if(fill.pbData!=IntPtr.Zero)
Marshal.FreeHGlobal (fill.pbData);
}
return cipherTextBytes;
}
public static string Encrypt(string text, KeyType keyType)
{
return Convert.ToBase64String(
Encrypt(Encoding.UTF8.GetBytes(text), keyType)
);
}
public static string Decrypt(string encryptedText)
{
return Encoding.UTF8.GetString(
Decrypt( Convert.FromBase64String(encryptedText) ));
}
public static byte[] Decrypt( byte[] encryptedText )
{
if(encryptedText==null) encryptedText = new byte[0];
DATA_BLOB plainTextBlob = new DATA_BLOB();
DATA_BLOB cipherTextBlob = new DATA_BLOB();
DATA_BLOB fill = new DATA_BLOB();
byte[] plainTextBytes;
try
{
cipherTextBlob.pbData = Marshal.AllocHGlobal(encryptedText.Length);
cipherTextBlob.cbData = encryptedText.Length;
Marshal.Copy(encryptedText, 0, cipherTextBlob.pbData, encryptedText.Length);
byte[] strFill={0};
fill.pbData = Marshal.AllocHGlobal(strFill.Length);
fill.cbData = strFill.Length;
Marshal.Copy(strFill, 0, fill.pbData, strFill.Length);
CRYPTPROTECT_PROMPTSTRUCT ps =
new CRYPTPROTECT_PROMPTSTRUCT();
ps.cbSize = Marshal.SizeOf(
typeof(CRYPTPROTECT_PROMPTSTRUCT));
ps.dwPromptFlags= 0;
ps.hwndApp = IntPtr.Zero ;
ps.szPrompt = null;
string description = String.Empty;
int flags = CRYPTPROTECT_UI_FORBIDDEN;
bool success = CryptUnprotectData(ref cipherTextBlob,
ref description,
ref fill,
IntPtr.Zero,
ref ps,
flags,
ref plainTextBlob);
plainTextBytes = new byte[plainTextBlob.cbData];
Marshal.Copy(plainTextBlob.pbData,
plainTextBytes,
0,
plainTextBlob.cbData);
}
catch
{
throw new Exception("Can not decrypy message");
}
finally
{
if (plainTextBlob.pbData !=IntPtr.Zero)
Marshal.FreeHGlobal(plainTextBlob.pbData);
if (cipherTextBlob.pbData !=IntPtr.Zero)
Marshal.FreeHGlobal(cipherTextBlob.pbData);
if (fill.pbData !=IntPtr.Zero)
Marshal.FreeHGlobal(fill.pbData);
}
return plainTextBytes;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Blizzard
{
class Client
{
public Client() {
_client = new HttpClient(new HttpClientHandler {
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
});
_client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip,deflate");
_client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
}
public List<Card> LoadCards() {
var pages = GetLatestPages();
return pages
.Select(c => c.Path)
.Select(p => File.ReadAllText(p))
.Select(c => JsonConvert.DeserializeObject<CardsResponse>(c))
.SelectMany(r => r.Cards)
.ToList();
}
public async Task<List<Card>> UpdateCards() {
var pages = GetLatestPages();
var etags = pages.Select(c => c.Entry.ETag).ToArray();
var result = await FetchCards(etags);
if (result.Modified) {
int timestamp = (int)DateTimeOffset.Now.ToUnixTimeSeconds();
for (int i = 0; i < result.Responses.Count; i++) {
var response = result.Responses[i];
var entry = new CacheEntry {
Timestamp = timestamp,
ETag = response.ETag,
Page = i + 1,
};
string path = entry.ToPath(CacheDir);
File.WriteAllText(path, response.Content);
}
}
return LoadCards();
}
IEnumerable<(string Path, CacheEntry Entry)> GetLatestPages() {
var cache = Directory.EnumerateFileSystemEntries(CacheDir).Select<string, (string Path, CacheEntry Entry)>(path => {
return (path, CacheEntry.FromPath(path));
});
int latest = cache.Any() ? cache.Max(c => c.Entry.Timestamp) : 0;
var pages = cache
.Where(c => c.Entry.Timestamp == latest)
.OrderBy(c => c.Entry.Page);
return pages;
}
async Task<(bool Modified, List<(string ETag, string Content)> Responses)> FetchCards(string[] etags) {
bool modified = false;
var responses = new List<(string, string)>();
for (int page = 1; ; page++) {
string etag = etags.Length >= page ? etags[page - 1] : "";
var result = await FetchCards(etag, page);
modified = modified || result.Modified;
responses.Add((result.ETag, result.Content));
if (result.Modified) {
var pagination = JsonConvert.DeserializeObject<PageResponse>(result.Content);
Console.WriteLine($"Page {pagination.Page} of {pagination.PageCount}.");
if (pagination.Page == pagination.PageCount) {
break;
}
} else if (!modified && page == etags.Length) {
break;
}
}
return (modified, responses);
}
async Task<(bool Modified, string ETag, string Content)> FetchCards(string etag, int page) {
return await _throttle.Invoke(async () => {
var builder = new UriBuilder("https://api.blizzard.com/hearthstone/cards") {
Query = await new FormUrlEncodedContent(new Dictionary<string, string> {
{ "page", page.ToString() },
{ "collectible", "0,1" }
}).ReadAsStringAsync()
};
var uri = builder.Uri;
using (var request = new HttpRequestMessage(HttpMethod.Get, uri)) {
string authToken = await FetchAuthToken();
request.Headers.Add("Authorization", $"Bearer {authToken}");
if (!string.IsNullOrEmpty(etag)) {
request.Headers.Add("If-None-Match", etag);
}
Console.WriteLine($"Fetch {uri}.");
using (var response = await _client.SendAsync(request)) {
if (response.StatusCode != HttpStatusCode.NotModified && response.StatusCode != HttpStatusCode.OK) {
throw new Exception($"Unexpected response status: {response.StatusCode}.");
}
if (response.StatusCode == HttpStatusCode.NotModified) {
Console.WriteLine("304 Not Modified.");
return (false, "", "");
}
Console.WriteLine("200 OK.");
string newETag = response.Headers.ETag.Tag;
return (true, newETag, await response.Content.ReadAsStringAsync());
}
}
});
}
async Task<string> FetchAuthToken() {
if (!string.IsNullOrEmpty(_authToken)) {
return _authToken;
}
Func<Task<string>> fetch = async () => {
string content = await _client.GetStringAsync("https://playhearthstone.com/en-us/cards");
var pattern = new Regex("cardApiSettings=\"(.*?)\"");
var match = pattern.Match(content);
if (!match.Success) {
return null;
}
string encoded = match.Groups[1].Value;
if (string.IsNullOrEmpty(encoded)) {
return null;
}
var settings = JObject.Parse(HttpUtility.HtmlDecode(encoded));
string token = settings["token"]["access_token"].ToString();
if (string.IsNullOrEmpty(token)) {
return null;
}
return token;
};
_authToken = await fetch();
if (string.IsNullOrEmpty(_authToken)) {
throw new Exception("Authorization token not found.");
}
Console.WriteLine($"Use auth token {_authToken}.");
return _authToken;
}
HttpClient _client;
string _authToken;
Throttle _throttle = new Throttle(TimeSpan.FromSeconds(1));
readonly string CacheDir = Path.Join(".cache", "blizzard");
}
public enum Locale
{
en_US,
de_DE,
es_ES,
es_MX,
fr_FR,
it_IT,
ja_JP,
ko_KR,
pl_PL,
pt_BR,
ru_RU,
th_TH,
zh_CN,
zh_TW
}
public class CacheEntry
{
[JsonProperty("timestamp")]
public int Timestamp;
[JsonProperty("etag")]
public string ETag;
[JsonProperty("page")]
public int Page;
public static CacheEntry FromPath(string path) {
string fileName = Path.GetFileNameWithoutExtension(path);
string json = Encoding.UTF8.GetString(Convert.FromBase64String(fileName));
return JsonConvert.DeserializeObject<CacheEntry>(json);
}
public string ToPath(string path) {
string json = JsonConvert.SerializeObject(this);
var bytes = Encoding.UTF8.GetBytes(json);
string fileName = Convert.ToBase64String(bytes, Base64FormattingOptions.None);
return Path.Join(path, $"{fileName}.json");
}
}
public class PageResponse
{
[JsonProperty("pageCount")]
public int? PageCount;
[JsonProperty("page")]
public int Page;
}
public class CardsResponse
{
[JsonProperty("cards")]
public Card[] Cards = new Card[0];
[JsonProperty("cardCount")]
public int CardCount;
[JsonProperty("pageCount")]
public int? PageCount;
[JsonProperty("page")]
public int Page;
}
public class Card
{
[JsonProperty("id")]
public int DbfId;
[JsonProperty("image")]
public Dictionary<Locale, string> Images;
}
}
| |
//#define IOS_ID
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if UNITY_METRO && !UNITY_EDITOR
using GA_Compatibility.Collections;
#endif
/// <summary>
/// The GA_Settings object contains an array of options which allows you to customize your use of GameAnalytics. Most importantly you will need to fill in your Game Key and Secret Key on the GA_Settings object to use the service.
/// </summary>
///
public class GA_Settings : ScriptableObject
{
#if UNITY_IPHONE && !UNITY_EDITOR && IOS_ID
[DllImport ("__Internal")]
private static extern string GetUserID ();
#endif
/// <summary>
/// Types of help given in the help box of the GA inspector
/// </summary>
public enum HelpTypes { None, FpsCriticalAndTrackTargetHelp, GuiAndTrackTargetHelp, IncludeSystemSpecsHelp, ProvideCustomUserID };
public enum MessageTypes { None, Error, Info, Warning };
/// <summary>
/// A message and message type for the help box displayed on the GUI inspector
/// </summary>
public struct HelpInfo
{
public string Message;
public MessageTypes MsgType;
public HelpTypes HelpType;
}
#region public static values
/// <summary>
/// The version of the GA Unity Wrapper plugin
/// </summary>
[HideInInspector]
public static string VERSION = "0.5.9";
#endregion
#region public values
public int TotalMessagesSubmitted;
public int TotalMessagesFailed;
public int DesignMessagesSubmitted;
public int DesignMessagesFailed;
public int QualityMessagesSubmitted;
public int QualityMessagesFailed;
public int ErrorMessagesSubmitted;
public int ErrorMessagesFailed;
public int BusinessMessagesSubmitted;
public int BusinessMessagesFailed;
public int UserMessagesSubmitted;
public int UserMessagesFailed;
public string CustomArea = string.Empty;
//Set the track target to use for predefined events, such as CriticalFPS (position of track target is sent with these events).
public Transform TrackTarget;
[SerializeField]
public string GameKey = "";
[SerializeField]
public string SecretKey = "";
[SerializeField]
public string ApiKey = "";
[SerializeField]
public string Build = "0.1";
public bool DebugMode = true;
public bool DebugAddEvent = false;
public bool SendExampleGameDataToMyGame = false;
public bool RunInEditorPlayMode = true;
public bool UseBundleVersion = false;
public bool AllowRoaming = true;
public bool ArchiveData = true;
public bool NewSessionOnResume = true;
public bool AutoSubmitUserInfo = true;
public Vector3 HeatmapGridSize = Vector3.one;
//bytes
public long ArchiveMaxFileSize = 2000;
public bool CustomUserID;
public float SubmitInterval = 10;
public bool InternetConnectivity;
//These values are used for the GA_Inspector only
public enum InspectorStates { Basic, QA, Debugging, Data, Pref }
public InspectorStates CurrentInspectorState;
public List<HelpTypes> ClosedHints = new List<HelpTypes>();
public bool DisplayHints;
public Vector2 DisplayHintsScrollState;
public Texture2D Logo;
public Texture2D UpdateIcon;
#endregion
#region public methods
/// <summary>
/// Help/hints/tips messages used for the GA inspector hints box. This function decides which hint to display.
/// Garbos: Depricated because: Was duplicated to return list of messages instead. Use GetHelpMessageList
/// </summary>
/// <returns>
/// The help message.
/// </returns>
public List<HelpInfo> GetHelpMessageList()
{
List<HelpInfo> result = new List<HelpInfo>();
if (GameKey.Equals("") || SecretKey.Equals(""))
{
result.Add( new HelpInfo() { Message = "Please fill in your Game Key and Secret Key, obtained from the GameAnalytics website where you created your game.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None });
}
if (Build.Equals(""))
{
result.Add( new HelpInfo() { Message = "Please fill in a name for your build, representing the current version of the game. Updating the build name for each version of the game will allow you to filter by build when viewing your data on the GA website.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None });
}
if (CustomUserID && !ClosedHints.Contains(HelpTypes.ProvideCustomUserID))
{
result.Add( new HelpInfo() { Message = "You have indicated that you will provide a custom user ID - no data will be submitted until it is provided. This should be defined from code through: GA.Settings.SetCustomUserID", MsgType = MessageTypes.Info, HelpType = HelpTypes.ProvideCustomUserID });
}
return result;
}
/// <summary>
/// Help/hints/tips messages used for the GA inspector hints box. This function decides which hint to display.
/// Garbos: Depricated because: Was duplicated to return list of messages instead. Use GetHelpMessageList
/// </summary>
/// <returns>
/// The help message.
/// </returns>
public HelpInfo GetHelpMessage()
{
if (GameKey.Equals("") || SecretKey.Equals(""))
{
return new HelpInfo() { Message = "Please fill in your Game Key and Secret Key, obtained from the GameAnalytics website where you created your game.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None };
}
else if (Build.Equals(""))
{
return new HelpInfo() { Message = "Please fill in a name for your build, representing the current version of the game. Updating the build name for each version of the game will allow you to filter by build when viewing your data on the GA website.", MsgType = MessageTypes.Warning, HelpType = HelpTypes.None };
}
else if (CustomUserID && !ClosedHints.Contains(HelpTypes.ProvideCustomUserID))
{
return new HelpInfo() { Message = "You have indicated that you will provide a custom user ID - no data will be submitted until it is provided. This should be defined from code through: GA.Settings.SetCustomUserID", MsgType = MessageTypes.Info, HelpType = HelpTypes.ProvideCustomUserID };
}
return new HelpInfo() { Message = "No hints to display. The \"Reset Hints\" button resets closed hints.", MsgType = MessageTypes.None, HelpType = HelpTypes.None };
}
/// <summary>
/// Checks the internet connectivity, and sets INTERNETCONNECTIVITY
/// </summary>
public IEnumerator CheckInternetConnectivity(bool startQueue)
{
// Application.internetReachability returns the type of Internet reachability currently possible on the device, but does not check if the there is an actual route to the network. So we can check this instantly.
if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork && !GA.SettingsGA.AllowRoaming)
{
InternetConnectivity = false;
}
else
{
//Try to ping the server
WWW www = new WWW(GA.API.Submit.GetBaseURL(true) + "/ping");
//Wait for response
yield return www;
try
{
if (GA.API.Submit.CheckServerReply(www))
{
InternetConnectivity = true;
}
else if (!string.IsNullOrEmpty(www.error))
{
InternetConnectivity = false;
}
else
{
//Get the JSON object from the response
Hashtable returnParam = (Hashtable)GA_MiniJSON.JsonDecode(www.text);
//If the response contains the key "status" with the value "ok" we know that we are connected
if (returnParam != null && returnParam.ContainsKey("status") && returnParam["status"].ToString().Equals("ok"))
{
InternetConnectivity = true;
}
else
{
InternetConnectivity = false;
}
}
}
catch
{
InternetConnectivity = false;
}
}
if (startQueue)
{
if (InternetConnectivity)
GA.Log("GA has confirmed internet connection..");
else
GA.Log("GA detects no internet connection..");
//Try to add additional IDs
if (AddUniqueIDs())
{
//Start the submit queue for sending messages to the server
GA.RunCoroutine(GA_Queue.SubmitQueue());
GA.Log("GameAnalytics: Submission queue started.");
#if UNITY_EDITOR
GameObject gaTracking = new GameObject("GA_Tracking");
gaTracking.AddComponent<GA_Tracking>();
#else
GameObject fbGameObject = new GameObject("GA_FacebookSDK");
fbGameObject.AddComponent<GA_FacebookSDK>();
#endif
}
else
{
GA.LogWarning("GA failed to add unique IDs and will not send any data. If you are using iOS or Android please see the readme file in the iOS/Android folder in the GameAnalytics/Plugins directory.");
}
}
}
private bool AddUniqueIDs()
{
bool returnValue = false;
#if !UNITY_EDITOR && UNITY_WEBPLAYER
if (Application.absoluteURL.StartsWith("http"))
{
Application.ExternalEval(
"try{var __scr = document.createElement('script'); __scr.setAttribute('async', 'true'); __scr.type = 'text/javascript'; __scr.src = 'https://d17ay18sztndlo.cloudfront.net/resources/js/ga_sdk_tracking.js'; ((document.getElementsByTagName('head') || [null])[0] || document.getElementsByTagName('script')[0].parentNode).appendChild(__scr);}catch(e){}"
);
}
#endif
#if !UNITY_EDITOR && UNITY_STANDALONE_WIN
string device = "PC";
#elif !UNITY_EDITOR
string device = SystemInfo.deviceModel;
#endif
#if !UNITY_EDITOR
string os = "";
string[] osSplit = SystemInfo.operatingSystem.Split(' ');
if (osSplit.Length > 0)
os = osSplit[0];
#endif
#if UNITY_IPHONE && !UNITY_EDITOR && IOS_ID
try
{
string iOSid = GetUniqueIDiOS();
if (iOSid != null && iOSid != string.Empty)
{
if (iOSid.StartsWith("VENDOR-"))
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, null, AutoSubmitUserInfo?GA.API.GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?SystemInfo.operatingSystem:null, "GA Unity SDK " + VERSION);
else
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, iOSid, null, AutoSubmitUserInfo?GA.API.GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?SystemInfo.operatingSystem:null, "GA Unity SDK " + VERSION);
returnValue = true;
}
}
catch
{ }
#elif UNITY_ANDROID && !UNITY_EDITOR
try
{
string androidID = GetUniqueIDAndroid();
if (androidID != null && androidID != string.Empty)
{
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, androidID, AutoSubmitUserInfo?GA.API.GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?SystemInfo.operatingSystem:null, "GA Unity SDK " + VERSION);
returnValue = true;
}
}
catch
{ }
#elif UNITY_FLASH && !UNITY_EDITOR
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, null, AutoSubmitUserInfo?GA.API.GenericInfo.GetSystem():null, "Flash", AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?SystemInfo.operatingSystem:null, "GA Unity SDK " + VERSION);
returnValue = true;
#elif !UNITY_EDITOR && !UNITY_IPHONE && !UNITY_ANDROID
GA.API.User.NewUser(GA_User.Gender.Unknown, null, null, null, null, AutoSubmitUserInfo?GA.API.GenericInfo.GetSystem():null, AutoSubmitUserInfo?device:null, AutoSubmitUserInfo?os:null, AutoSubmitUserInfo?SystemInfo.operatingSystem:null, "GA Unity SDK " + VERSION);
returnValue = true;
#elif UNITY_IPHONE && UNITY_EDITOR && !IOS_ID
GetUniqueIDiOS ();
returnValue = true;
#elif UNITY_EDITOR
returnValue = true;
#endif
return returnValue;
}
public string GetUniqueIDiOS ()
{
string uid = "";
#if UNITY_IPHONE && !UNITY_EDITOR && IOS_ID
uid = GetUserID();
#endif
#if UNITY_IPHONE && UNITY_EDITOR && !IOS_ID
GA.LogWarning("GA Warning: Remember to read the iOS_Readme in the GameAnalytics > Plugins > iOS folder, for information on how to setup advertiser ID for iOS. GA will not work on iOS if you do not follow these steps.");
#endif
return uid;
}
public string GetUniqueIDAndroid ()
{
string uid = "";
#if UNITY_ANDROID && !UNITY_EDITOR
try
{
AndroidJavaClass up = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = up.GetStatic<AndroidJavaObject> ("currentActivity");
AndroidJavaObject contentResolver = currentActivity.Call<AndroidJavaObject> ("getContentResolver");
AndroidJavaClass secure = new AndroidJavaClass ("android.provider.Settings$Secure");
uid = secure.CallStatic<string> ("getString", contentResolver, "android_id");
}
catch
{ }
#endif
return uid;
}
/// <summary>
/// Sets a custom user ID.
/// Make sure each user has a unique user ID. This is useful if you have your own log-in system with unique user IDs.
/// NOTE: Only use this method if you have enabled "Custom User ID" on the GA inspector!
/// </summary>
/// <param name="customID">
/// The custom user ID - this should be unique for each user
/// </param>
public void SetCustomUserID(string customID)
{
if (customID != string.Empty)
{
GA.API.GenericInfo.SetCustomUserID(customID);
}
}
/// <summary>
/// Sets a custom area string. An area is often just a level, but you can set it to whatever makes sense for your game. F.x. in a big open world game you will probably need custom areas to identify regions etc.
/// By default, if no custom area is set, the Application.loadedLevelName string is used.
/// </summary>
/// <param name="customID">
/// The custom area.
/// </param>
public void SetCustomArea(string customArea)
{
CustomArea = customArea;
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using Microsoft.Build.Framework;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
using ProjectCollection = Microsoft.Build.Evaluation.ProjectCollection;
namespace Microsoft.Build.UnitTests
{
/*
* Class: MockLogger
*
* Mock logger class. Keeps track of errors and warnings and also builds
* up a raw string (fullLog) that contains all messages, warnings, errors.
* Thread-safe.
*/
internal sealed class MockLogger : ILogger
{
#region Properties
private readonly object _lockObj = new object(); // Protects _fullLog, _testOutputHelper, lists, counts
private StringBuilder _fullLog = new StringBuilder();
private readonly ITestOutputHelper _testOutputHelper;
private readonly bool _profileEvaluation;
private readonly bool _printEventsToStdout;
/// <summary>
/// Should the build finished event be logged in the log file. This is to work around the fact we have different
/// localized strings between env and xmake for the build finished event.
/// </summary>
internal bool LogBuildFinished { get; set; } = true;
/*
* Method: ErrorCount
*
* The count of all errors seen so far.
*
*/
internal int ErrorCount { get; private set; }
/*
* Method: WarningCount
*
* The count of all warnings seen so far.
*
*/
internal int WarningCount { get; private set; }
/// <summary>
/// Return the list of logged errors
/// </summary>
internal List<BuildErrorEventArgs> Errors { get; } = new List<BuildErrorEventArgs>();
/// <summary>
/// Returns the list of logged warnings
/// </summary>
internal List<BuildWarningEventArgs> Warnings { get; } = new List<BuildWarningEventArgs>();
/// <summary>
/// When set to true, allows task crashes to be logged without causing an assert.
/// </summary>
internal bool AllowTaskCrashes { get; set; }
/// <summary>
/// List of ExternalProjectStarted events
/// </summary>
internal List<ExternalProjectStartedEventArgs> ExternalProjectStartedEvents { get; } = new List<ExternalProjectStartedEventArgs>();
/// <summary>
/// List of ExternalProjectFinished events
/// </summary>
internal List<ExternalProjectFinishedEventArgs> ExternalProjectFinishedEvents { get; } = new List<ExternalProjectFinishedEventArgs>();
/// <summary>
/// List of ProjectStarted events
/// </summary>
internal List<ProjectStartedEventArgs> ProjectStartedEvents { get; } = new List<ProjectStartedEventArgs>();
/// <summary>
/// List of ProjectFinished events
/// </summary>
internal List<ProjectFinishedEventArgs> ProjectFinishedEvents { get; } = new List<ProjectFinishedEventArgs>();
/// <summary>
/// List of TargetStarted events
/// </summary>
internal List<TargetStartedEventArgs> TargetStartedEvents { get; } = new List<TargetStartedEventArgs>();
/// <summary>
/// List of TargetFinished events
/// </summary>
internal List<TargetFinishedEventArgs> TargetFinishedEvents { get; } = new List<TargetFinishedEventArgs>();
/// <summary>
/// List of TaskStarted events
/// </summary>
internal List<TaskStartedEventArgs> TaskStartedEvents { get; } = new List<TaskStartedEventArgs>();
/// <summary>
/// List of TaskFinished events
/// </summary>
internal List<TaskFinishedEventArgs> TaskFinishedEvents { get; } = new List<TaskFinishedEventArgs>();
/// <summary>
/// List of BuildMessage events
/// </summary>
internal List<BuildMessageEventArgs> BuildMessageEvents { get; } = new List<BuildMessageEventArgs>();
/// <summary>
/// List of BuildStarted events, thought we expect there to only be one, a valid check is to make sure this list is length 1
/// </summary>
internal List<BuildStartedEventArgs> BuildStartedEvents { get; } = new List<BuildStartedEventArgs>();
/// <summary>
/// List of BuildFinished events, thought we expect there to only be one, a valid check is to make sure this list is length 1
/// </summary>
internal List<BuildFinishedEventArgs> BuildFinishedEvents { get; } = new List<BuildFinishedEventArgs>();
internal List<BuildEventArgs> AllBuildEvents { get; } = new List<BuildEventArgs>();
/*
* Method: FullLog
*
* The raw concatenation of all messages, errors and warnings seen so far.
*
*/
internal string FullLog
{
get
{
lock (_lockObj)
{
return _fullLog.ToString();
}
}
}
#endregion
#region Minimal ILogger implementation
/*
* Property: Verbosity
*
* The level of detail to show in the event log.
*
*/
public LoggerVerbosity Verbosity
{
get => LoggerVerbosity.Normal;
set {/* do nothing */}
}
/*
* Property: Parameters
*
* The mock logger does not take parameters.
*
*/
public string Parameters
{
get => null;
set {/* do nothing */}
}
/*
* Method: Initialize
*
* Add a new build event.
*
*/
public void Initialize(IEventSource eventSource)
{
eventSource.AnyEventRaised += LoggerEventHandler;
if (_profileEvaluation)
{
var eventSource3 = eventSource as IEventSource3;
eventSource3.ShouldNotBeNull();
eventSource3.IncludeEvaluationProfiles();
}
}
/// <summary>
/// Clears the content of the log "file"
/// </summary>
public void ClearLog()
{
lock (_lockObj)
{
_fullLog = new StringBuilder();
}
}
/*
* Method: Shutdown
*
* The mock logger does not need to release any resources.
*
*/
public void Shutdown()
{
// do nothing
}
#endregion
public MockLogger(ITestOutputHelper testOutputHelper = null, bool profileEvaluation = false, bool printEventsToStdout = true)
{
_testOutputHelper = testOutputHelper;
_profileEvaluation = profileEvaluation;
_printEventsToStdout = printEventsToStdout;
}
public List<Action<object, BuildEventArgs>> AdditionalHandlers { get; set; } = new List<Action<object, BuildEventArgs>>();
/*
* Method: LoggerEventHandler
*
* Receives build events and logs them the way we like.
*
*/
internal void LoggerEventHandler(object sender, BuildEventArgs eventArgs)
{
lock (_lockObj)
{
AllBuildEvents.Add(eventArgs);
foreach (Action<object, BuildEventArgs> handler in AdditionalHandlers)
{
handler(sender, eventArgs);
}
// Log the string part of the event
switch (eventArgs)
{
case BuildWarningEventArgs w:
// hack: disregard the MTA warning.
// need the second condition to pass on ploc builds
if (w.Code != "MSB4056" && !w.Message.Contains("MSB4056"))
{
string logMessage = $"{w.File}({w.LineNumber},{w.ColumnNumber}): {w.Subcategory} warning {w.Code}: {w.Message}";
_fullLog.AppendLine(logMessage);
_testOutputHelper?.WriteLine(logMessage);
++WarningCount;
Warnings.Add(w);
}
break;
case BuildErrorEventArgs e:
{
string logMessage = $"{e.File}({e.LineNumber},{e.ColumnNumber}): {e.Subcategory} error {e.Code}: {e.Message}";
_fullLog.AppendLine(logMessage);
_testOutputHelper?.WriteLine(logMessage);
++ErrorCount;
Errors.Add(e);
break;
}
default:
{
// Log the message unless we are a build finished event and logBuildFinished is set to false.
bool logMessage = !(eventArgs is BuildFinishedEventArgs) || LogBuildFinished;
if (logMessage)
{
_fullLog.AppendLine(eventArgs.Message);
_testOutputHelper?.WriteLine(eventArgs.Message);
}
break;
}
}
// Log the specific type of event it was
switch (eventArgs)
{
case ExternalProjectStartedEventArgs args:
{
ExternalProjectStartedEvents.Add(args);
break;
}
case ExternalProjectFinishedEventArgs finishedEventArgs:
{
ExternalProjectFinishedEvents.Add(finishedEventArgs);
break;
}
case ProjectStartedEventArgs startedEventArgs:
{
ProjectStartedEvents.Add(startedEventArgs);
break;
}
case ProjectFinishedEventArgs finishedEventArgs:
{
ProjectFinishedEvents.Add(finishedEventArgs);
break;
}
case TargetStartedEventArgs targetStartedEventArgs:
{
TargetStartedEvents.Add(targetStartedEventArgs);
break;
}
case TargetFinishedEventArgs targetFinishedEventArgs:
{
TargetFinishedEvents.Add(targetFinishedEventArgs);
break;
}
case TaskStartedEventArgs taskStartedEventArgs:
{
TaskStartedEvents.Add(taskStartedEventArgs);
break;
}
case TaskFinishedEventArgs taskFinishedEventArgs:
{
TaskFinishedEvents.Add(taskFinishedEventArgs);
break;
}
case BuildMessageEventArgs buildMessageEventArgs:
{
BuildMessageEvents.Add(buildMessageEventArgs);
break;
}
case BuildStartedEventArgs buildStartedEventArgs:
{
BuildStartedEvents.Add(buildStartedEventArgs);
break;
}
case BuildFinishedEventArgs buildFinishedEventArgs:
{
BuildFinishedEvents.Add(buildFinishedEventArgs);
if (!AllowTaskCrashes)
{
// We should not have any task crashes. Sometimes a test will validate that their expected error
// code appeared, but not realize it then crashed.
AssertLogDoesntContain("MSB4018");
}
// We should not have any Engine crashes.
AssertLogDoesntContain("MSB0001");
// Console.Write in the context of a unit test is very expensive. A hundred
// calls to Console.Write can easily take two seconds on a fast machine. Therefore, only
// do the Console.Write once at the end of the build.
PrintFullLog();
break;
}
}
}
}
private void PrintFullLog()
{
if (_printEventsToStdout)
{
Console.Write(FullLog);
}
}
// Lazy-init property returning the MSBuild engine resource manager
private static ResourceManager EngineResourceManager => s_engineResourceManager ?? (s_engineResourceManager = new ResourceManager(
"Microsoft.Build.Strings",
typeof(ProjectCollection).GetTypeInfo().Assembly));
private static ResourceManager s_engineResourceManager;
// Gets the resource string given the resource ID
public static string GetString(string stringId) => EngineResourceManager.GetString(stringId, CultureInfo.CurrentUICulture);
/// <summary>
/// Assert that the log file contains the given strings, in order.
/// </summary>
/// <param name="contains"></param>
internal void AssertLogContains(params string[] contains) => AssertLogContains(true, contains);
/// <summary>
/// Assert that the log file contains the given string, in order. Includes the option of case invariance
/// </summary>
/// <param name="isCaseSensitive">False if we do not care about case sensitivity</param>
/// <param name="contains"></param>
internal void AssertLogContains(bool isCaseSensitive, params string[] contains)
{
lock (_lockObj)
{
var reader = new StringReader(FullLog);
int index = 0;
string currentLine = reader.ReadLine();
if (!isCaseSensitive)
{
currentLine = currentLine.ToUpper();
}
while (currentLine != null)
{
string comparer = contains[index];
if (!isCaseSensitive)
{
comparer = comparer.ToUpper();
}
if (currentLine.Contains(comparer))
{
index++;
if (index == contains.Length) break;
}
currentLine = reader.ReadLine();
if (!isCaseSensitive)
{
currentLine = currentLine?.ToUpper();
}
}
if (index != contains.Length)
{
if (_testOutputHelper != null)
{
_testOutputHelper.WriteLine(FullLog);
}
else
{
PrintFullLog();
}
Assert.True(
false,
$"Log was expected to contain '{contains[index]}', but did not. Full log:\n=======\n{FullLog}\n=======");
}
}
}
/// <summary>
/// Assert that the log file does not contain the given string.
/// </summary>
/// <param name="contains"></param>
internal void AssertLogDoesntContain(string contains)
{
lock (_lockObj)
{
if (FullLog.Contains(contains))
{
if (_testOutputHelper != null)
{
_testOutputHelper.WriteLine(FullLog);
}
else
{
PrintFullLog();
}
Assert.True(false, $"Log was not expected to contain '{contains}', but did.");
}
}
}
/// <summary>
/// Assert that no errors were logged
/// </summary>
internal void AssertNoErrors() => Assert.Equal(0, ErrorCount);
/// <summary>
/// Assert that no warnings were logged
/// </summary>
internal void AssertNoWarnings() => Assert.Equal(0, WarningCount);
}
}
| |
// 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 a line by line port of callingconvention.h from the CLR with the intention that we may wish to merge
// changes from the CLR in at a later time. As such, the normal coding conventions are ignored.
//
//
#if ARM
#define _TARGET_ARM_
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define FEATURE_HFA
#elif ARM64
#define _TARGET_ARM64_
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define ENREGISTERED_PARAMTYPE_MAXSIZE
#define FEATURE_HFA
#elif X86
#define _TARGET_X86_
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#elif AMD64
#if PLATFORM_UNIX
#define UNIX_AMD64_ABI
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#else
#endif
#define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter
#define _TARGET_AMD64_
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define ENREGISTERED_PARAMTYPE_MAXSIZE
#else
#error Unknown architecture!
#endif
// Provides an abstraction over platform specific calling conventions (specifically, the calling convention
// utilized by the JIT on that platform). The caller enumerates each argument of a signature in turn, and is
// provided with information mapping that argument into registers and/or stack locations.
using System;
namespace Internal.Runtime
{
#if _TARGET_AMD64_
#pragma warning disable 0169
#if UNIX_AMD64_ABI
struct ReturnBlock
{
IntPtr returnValue;
IntPtr returnValue2;
}
struct ArgumentRegisters
{
IntPtr rdi;
IntPtr rsi;
IntPtr rdx;
IntPtr rcx;
IntPtr r8;
IntPtr r9;
}
#else // UNIX_AMD64_ABI
struct ReturnBlock
{
IntPtr returnValue;
}
struct ArgumentRegisters
{
IntPtr rdx;
IntPtr rcx;
IntPtr r8;
IntPtr r9;
}
#endif // UNIX_AMD64_ABI
#pragma warning restore 0169
#pragma warning disable 0169
struct M128A
{
IntPtr a;
IntPtr b;
}
struct FloatArgumentRegisters
{
M128A d0;
M128A d1;
M128A d2;
M128A d3;
#if UNIX_AMD64_ABI
M128A d4;
M128A d5;
M128A d6;
M128A d7;
#endif
}
#pragma warning restore 0169
struct ArchitectureConstants
{
// To avoid corner case bugs, limit maximum size of the arguments with sufficient margin
public const int MAX_ARG_SIZE = 0xFFFFFF;
#if UNIX_AMD64_ABI
public const int NUM_ARGUMENT_REGISTERS = 6;
#else
public const int NUM_ARGUMENT_REGISTERS = 4;
#endif
public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 8;
public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 8;
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 8;
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 8;
public const int ENREGISTERED_PARAMTYPE_MAXSIZE = 8;
public const int STACK_ELEM_SIZE = 8;
public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); }
}
#elif _TARGET_ARM64_
#pragma warning disable 0169
struct ReturnBlock
{
IntPtr returnValue;
IntPtr returnValue2;
IntPtr returnValue3;
IntPtr returnValue4;
IntPtr returnValue5;
IntPtr returnValue6;
IntPtr returnValue7;
IntPtr returnValue8;
}
struct CalleeSavedRegisters
{
IntPtr x29;
public IntPtr m_ReturnAddress; // Also known as x30
IntPtr x19;
IntPtr x20;
IntPtr x21;
IntPtr x22;
IntPtr x23;
IntPtr x24;
IntPtr x25;
IntPtr x26;
IntPtr x27;
IntPtr x28;
}
struct ArgumentRegisters
{
IntPtr x0;
IntPtr x1;
IntPtr x2;
IntPtr x3;
IntPtr x4;
IntPtr x5;
IntPtr x6;
IntPtr x7;
}
#pragma warning restore 0169
#pragma warning disable 0169
struct FloatArgumentRegisters
{
double d0;
double d1;
double d2;
double d3;
double d4;
double d5;
double d6;
double d7;
}
#pragma warning restore 0169
struct ArchitectureConstants
{
// To avoid corner case bugs, limit maximum size of the arguments with sufficient margin
public const int MAX_ARG_SIZE = 0xFFFFFF;
public const int NUM_ARGUMENT_REGISTERS = 8;
public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 8;
public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 64; //(maximum HFA size is 8 doubles)
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 8;
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 8;
public const int ENREGISTERED_PARAMTYPE_MAXSIZE = 16; //(max value type size than can be passed by value)
public const int STACK_ELEM_SIZE = 8;
public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); }
}
#elif _TARGET_X86_
#pragma warning disable 0169, 0649
struct ReturnBlock
{
public IntPtr returnValue;
public IntPtr returnValue2;
}
struct ArgumentRegisters
{
public IntPtr edx;
public static unsafe int GetOffsetOfEdx()
{
return 0;
}
public IntPtr ecx;
public static unsafe int GetOffsetOfEcx()
{
return sizeof(IntPtr);
}
}
// This struct isn't used by x86, but exists for compatibility with the definition of the CallDescrData struct
struct FloatArgumentRegisters
{
}
#pragma warning restore 0169, 0649
struct ArchitectureConstants
{
// To avoid corner case bugs, limit maximum size of the arguments with sufficient margin
public const int MAX_ARG_SIZE = 0xFFFFFF;
public const int NUM_ARGUMENT_REGISTERS = 2;
public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 4;
public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 8;
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 4;
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 4;
public const int STACK_ELEM_SIZE = 4;
public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); }
}
#elif _TARGET_ARM_
#pragma warning disable 0169
struct ReturnBlock
{
IntPtr returnValue;
IntPtr returnValue2;
IntPtr returnValue3;
IntPtr returnValue4;
IntPtr returnValue5;
IntPtr returnValue6;
IntPtr returnValue7;
IntPtr returnValue8;
}
struct ArgumentRegisters
{
IntPtr r0;
IntPtr r1;
IntPtr r2;
IntPtr r3;
}
struct FloatArgumentRegisters
{
double d0;
double d1;
double d2;
double d3;
double d4;
double d5;
double d6;
double d7;
}
#pragma warning restore 0169
struct ArchitectureConstants
{
// To avoid corner case bugs, limit maximum size of the arguments with sufficient margin
public const int MAX_ARG_SIZE = 0xFFFFFF;
public const int NUM_ARGUMENT_REGISTERS = 4;
public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 4;
public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 32;
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 4;
public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 8;
public const int STACK_ELEM_SIZE = 4;
public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); }
}
#endif
//
// TransitionBlock is layout of stack frame of method call, saved argument registers and saved callee saved registers. Even though not
// all fields are used all the time, we use uniform form for simplicity.
//
struct TransitionBlock
{
#pragma warning disable 0169,0649
#if _TARGET_X86_
public ArgumentRegisters m_argumentRegisters;
public static unsafe int GetOffsetOfArgumentRegisters()
{
return 0;
}
public ReturnBlock m_returnBlock;
public static unsafe int GetOffsetOfReturnValuesBlock()
{
return sizeof(ArgumentRegisters);
}
IntPtr m_ebp;
IntPtr m_ReturnAddress;
#elif _TARGET_AMD64_
#if UNIX_AMD64_ABI
public ReturnBlock m_returnBlock;
public static unsafe int GetOffsetOfReturnValuesBlock()
{
return 0;
}
public ArgumentRegisters m_argumentRegisters;
public static unsafe int GetOffsetOfArgumentRegisters()
{
return sizeof(ReturnBlock);
}
IntPtr m_alignmentPadding;
IntPtr m_ReturnAddress;
#else // UNIX_AMD64_ABI
IntPtr m_returnBlockPadding;
ReturnBlock m_returnBlock;
public static unsafe int GetOffsetOfReturnValuesBlock()
{
return sizeof(IntPtr);
}
IntPtr m_alignmentPadding;
IntPtr m_ReturnAddress;
public static unsafe int GetOffsetOfArgumentRegisters()
{
return sizeof(TransitionBlock);
}
#endif // UNIX_AMD64_ABI
#elif _TARGET_ARM_
public ReturnBlock m_returnBlock;
public static unsafe int GetOffsetOfReturnValuesBlock()
{
return 0;
}
public ArgumentRegisters m_argumentRegisters;
public static unsafe int GetOffsetOfArgumentRegisters()
{
return sizeof(ReturnBlock);
}
#elif _TARGET_ARM64_
public ReturnBlock m_returnBlock;
public static unsafe int GetOffsetOfReturnValuesBlock()
{
return 0;
}
public ArgumentRegisters m_argumentRegisters;
public static unsafe int GetOffsetOfArgumentRegisters()
{
return sizeof(ReturnBlock);
}
#else
#error Portability problem
#endif
#pragma warning restore 0169,0649
// The transition block should define everything pushed by callee. The code assumes in number of places that
// end of the transition block is caller's stack pointer.
public static unsafe byte GetOffsetOfArgs()
{
return (byte)sizeof(TransitionBlock);
}
public static bool IsStackArgumentOffset(int offset)
{
int ofsArgRegs = GetOffsetOfArgumentRegisters();
return offset >= (int)(ofsArgRegs + ArchitectureConstants.ARGUMENTREGISTERS_SIZE);
}
static bool IsArgumentRegisterOffset(int offset)
{
int ofsArgRegs = GetOffsetOfArgumentRegisters();
return offset >= ofsArgRegs && offset < (int)(ofsArgRegs + ArchitectureConstants.ARGUMENTREGISTERS_SIZE);
}
#if !_TARGET_X86_
public static unsafe int GetArgumentIndexFromOffset(int offset)
{
return ((offset - GetOffsetOfArgumentRegisters()) / IntPtr.Size);
}
#endif
#if CALLDESCR_FPARGREGS
public static bool IsFloatArgumentRegisterOffset(int offset)
{
return offset < 0;
}
public static int GetOffsetOfFloatArgumentRegisters()
{
return -GetNegSpaceSize();
}
#endif
public static unsafe int GetNegSpaceSize()
{
int negSpaceSize = 0;
#if CALLDESCR_FPARGREGS
negSpaceSize += sizeof(FloatArgumentRegisters);
#endif
return negSpaceSize;
}
public static int GetThisOffset()
{
// This pointer is in the first argument register by default
int ret = TransitionBlock.GetOffsetOfArgumentRegisters();
#if _TARGET_X86_
// x86 is special as always
ret += ArgumentRegisters.GetOffsetOfEcx();
#endif
return ret;
}
public const int InvalidOffset = -1;
};
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace System.Spatial {
using System;
using System.Resources;
/// <summary>
/// Strongly-typed and parameterized string resources.
/// </summary>
internal static class Strings {
/// <summary>
/// A string like "The queue doesn't contain an item with the priority {0}."
/// </summary>
internal static string PriorityQueueDoesNotContainItem(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.PriorityQueueDoesNotContainItem,p0);
}
/// <summary>
/// A string like "The operation is not valid on an empty queue."
/// </summary>
internal static string PriorityQueueOperationNotValidOnEmptyQueue {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.PriorityQueueOperationNotValidOnEmptyQueue);
}
}
/// <summary>
/// A string like "An item with the same priority already exists."
/// </summary>
internal static string PriorityQueueEnqueueExistingPriority {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.PriorityQueueEnqueueExistingPriority);
}
}
/// <summary>
/// A string like "No operations are registered. Please provide operations using SpatialImplementation.CurrentImplementation.Operations property."
/// </summary>
internal static string SpatialImplementation_NoRegisteredOperations {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.SpatialImplementation_NoRegisteredOperations);
}
}
/// <summary>
/// A string like "The value '{0}' is not valid for the coordinate '{1}'."
/// </summary>
internal static string InvalidPointCoordinate(object p0, object p1) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.InvalidPointCoordinate,p0,p1);
}
/// <summary>
/// A string like "Access to the coordinate properties of an empty point is not supported."
/// </summary>
internal static string Point_AccessCoordinateWhenEmpty {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Point_AccessCoordinateWhenEmpty);
}
}
/// <summary>
/// A string like "The builder cannot create an instance until all pipeline calls are completed."
/// </summary>
internal static string SpatialBuilder_CannotCreateBeforeDrawn {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.SpatialBuilder_CannotCreateBeforeDrawn);
}
}
/// <summary>
/// A string like "Incorrect GML Format: The XmlReader instance encountered an unexpected element "{0}"."
/// </summary>
internal static string GmlReader_UnexpectedElement(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_UnexpectedElement,p0);
}
/// <summary>
/// A string like "Incorrect GML Format: the XmlReader instance is expected to be at the start of a GML element."
/// </summary>
internal static string GmlReader_ExpectReaderAtElement {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_ExpectReaderAtElement);
}
}
/// <summary>
/// A string like "Incorrect GML Format: unknown spatial type tag "{0}"."
/// </summary>
internal static string GmlReader_InvalidSpatialType(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_InvalidSpatialType,p0);
}
/// <summary>
/// A string like "Incorrect GML Format: a LinearRing element must not be empty."
/// </summary>
internal static string GmlReader_EmptyRingsNotAllowed {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_EmptyRingsNotAllowed);
}
}
/// <summary>
/// A string like "Incorrect GML Format: a pos element must contain at least two coordinates."
/// </summary>
internal static string GmlReader_PosNeedTwoNumbers {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_PosNeedTwoNumbers);
}
}
/// <summary>
/// A string like "Incorrect GML Format: a posList element must contain an even number of coordinates."
/// </summary>
internal static string GmlReader_PosListNeedsEvenCount {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_PosListNeedsEvenCount);
}
}
/// <summary>
/// A string like "Incorrect GML Format: a srsName attribute must begin with the namespace "{0}"."
/// </summary>
internal static string GmlReader_InvalidSrsName(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_InvalidSrsName,p0);
}
/// <summary>
/// A string like "The attribute '{0}' on element '{1}' is not supported."
/// </summary>
internal static string GmlReader_InvalidAttribute(object p0, object p1) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GmlReader_InvalidAttribute,p0,p1);
}
/// <summary>
/// A string like "Expecting token type "{0}" with text "{1}" but found "{2}"."
/// </summary>
internal static string WellKnownText_UnexpectedToken(object p0, object p1, object p2) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.WellKnownText_UnexpectedToken,p0,p1,p2);
}
/// <summary>
/// A string like "Unexpected character '{0}' found in text."
/// </summary>
internal static string WellKnownText_UnexpectedCharacter(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.WellKnownText_UnexpectedCharacter,p0);
}
/// <summary>
/// A string like "Unknown Tagged Text "{0}"."
/// </summary>
internal static string WellKnownText_UnknownTaggedText(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.WellKnownText_UnknownTaggedText,p0);
}
/// <summary>
/// A string like "The WellKnownTextReader is configured to allow only two dimensions, and a third dimension was encountered."
/// </summary>
internal static string WellKnownText_TooManyDimensions {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.WellKnownText_TooManyDimensions);
}
}
/// <summary>
/// A string like "Invalid spatial data: An instance of spatial type can have only one unique CoordinateSystem for all of its coordinates."
/// </summary>
internal static string Validator_SridMismatch {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_SridMismatch);
}
}
/// <summary>
/// A string like "Invalid spatial data: Invalid spatial type "{0}"."
/// </summary>
internal static string Validator_InvalidType(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_InvalidType,p0);
}
/// <summary>
/// A string like "Invalid spatial data: the spatial type "FullGlobe" cannot be part of a collection type."
/// </summary>
internal static string Validator_FullGlobeInCollection {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_FullGlobeInCollection);
}
}
/// <summary>
/// A string like "Invalid spatial data: the spatial type "LineString" must contain at least two points."
/// </summary>
internal static string Validator_LineStringNeedsTwoPoints {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_LineStringNeedsTwoPoints);
}
}
/// <summary>
/// A string like "Invalid spatial data: the spatial type "FullGlobe" cannot contain figures."
/// </summary>
internal static string Validator_FullGlobeCannotHaveElements {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_FullGlobeCannotHaveElements);
}
}
/// <summary>
/// A string like "Invalid spatial data: only {0} levels of nesting are supported in collection types."
/// </summary>
internal static string Validator_NestingOverflow(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_NestingOverflow,p0);
}
/// <summary>
/// A string like "Invalid spatial data: the coordinates ({0} {1} {2} {3}) are not valid."
/// </summary>
internal static string Validator_InvalidPointCoordinate(object p0, object p1, object p2, object p3) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_InvalidPointCoordinate,p0,p1,p2,p3);
}
/// <summary>
/// A string like "Invalid spatial data: expected call to "{0}" but got call to "{1}"."
/// </summary>
internal static string Validator_UnexpectedCall(object p0, object p1) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_UnexpectedCall,p0,p1);
}
/// <summary>
/// A string like "Invalid spatial data: expected call to "{0}" or "{1}" but got call to "{2}"."
/// </summary>
internal static string Validator_UnexpectedCall2(object p0, object p1, object p2) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_UnexpectedCall2,p0,p1,p2);
}
/// <summary>
/// A string like "Invalid spatial data: A polygon ring must contain at least four points, and the last point must be equal to the first point."
/// </summary>
internal static string Validator_InvalidPolygonPoints {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_InvalidPolygonPoints);
}
}
/// <summary>
/// A string like "Invalid latitude coordinate {0}. A latitude coordinate must be a value between -90.0 and +90.0 degrees."
/// </summary>
internal static string Validator_InvalidLatitudeCoordinate(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_InvalidLatitudeCoordinate,p0);
}
/// <summary>
/// A string like "Invalid longitude coordinate {0}. A longitude coordinate must be a value between -15069.0 and +15069.0 degrees"
/// </summary>
internal static string Validator_InvalidLongitudeCoordinate(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_InvalidLongitudeCoordinate,p0);
}
/// <summary>
/// A string like "A geography operation was called while processing a geometric shape."
/// </summary>
internal static string Validator_UnexpectedGeography {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_UnexpectedGeography);
}
}
/// <summary>
/// A string like "A geometry operation was called while processing a geographic shape."
/// </summary>
internal static string Validator_UnexpectedGeometry {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.Validator_UnexpectedGeometry);
}
}
/// <summary>
/// A string like "Invalid GeoJSON. The '{0}' member is required, but was not found."
/// </summary>
internal static string GeoJsonReader_MissingRequiredMember(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_MissingRequiredMember,p0);
}
/// <summary>
/// A string like "Invalid GeoJSON. A position must contain at least two and no more than four elements."
/// </summary>
internal static string GeoJsonReader_InvalidPosition {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_InvalidPosition);
}
}
/// <summary>
/// A string like "Invalid GeoJSON. The value '{0}' is not a valid value for the 'type' member."
/// </summary>
internal static string GeoJsonReader_InvalidTypeName(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_InvalidTypeName,p0);
}
/// <summary>
/// A string like "Invalid GeoJSON. A null value was found in an array element where nulls are not allowed."
/// </summary>
internal static string GeoJsonReader_InvalidNullElement {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_InvalidNullElement);
}
}
/// <summary>
/// A string like "Invalid GeoJSON. A non-numeric value was found in an array element where a numeric value was expected."
/// </summary>
internal static string GeoJsonReader_ExpectedNumeric {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_ExpectedNumeric);
}
}
/// <summary>
/// A string like "Invalid GeoJSON. A primitive value was found in an array element where an array was expected."
/// </summary>
internal static string GeoJsonReader_ExpectedArray {
get {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_ExpectedArray);
}
}
/// <summary>
/// A string like "Invalid GeoJSON. The value '{0}' is not a recognized CRS type."
/// </summary>
internal static string GeoJsonReader_InvalidCrsType(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_InvalidCrsType,p0);
}
/// <summary>
/// A string like "Invalid GeoJSON. The value '{0}' is not a recognized CRS name."
/// </summary>
internal static string GeoJsonReader_InvalidCrsName(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.GeoJsonReader_InvalidCrsName,p0);
}
/// <summary>
/// A string like "Cannot read the value '{0}' for the property '{1}' as a quoted JSON string value."
/// </summary>
internal static string JsonReaderExtensions_CannotReadPropertyValueAsString(object p0, object p1) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.JsonReaderExtensions_CannotReadPropertyValueAsString,p0,p1);
}
/// <summary>
/// A string like "Cannot read the value '{0}' as a JSON object."
/// </summary>
internal static string JsonReaderExtensions_CannotReadValueAsJsonObject(object p0) {
return System.Spatial.TextRes.GetString(System.Spatial.TextRes.JsonReaderExtensions_CannotReadValueAsJsonObject,p0);
}
}
/// <summary>
/// Strongly-typed and parameterized exception factory.
/// </summary>
internal static partial class Error {
/// <summary>
/// The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
/// </summary>
internal static Exception ArgumentNull(string paramName) {
return new ArgumentNullException(paramName);
}
/// <summary>
/// The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
/// </summary>
internal static Exception ArgumentOutOfRange(string paramName) {
return new ArgumentOutOfRangeException(paramName);
}
/// <summary>
/// The exception that is thrown when the author has yet to implement the logic at this point in the program. This can act as an exception based TODO tag.
/// </summary>
internal static Exception NotImplemented() {
return new NotImplementedException();
}
/// <summary>
/// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
/// </summary>
internal static Exception NotSupported() {
return new NotSupportedException();
}
}
}
| |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
namespace UnitTests
{
using System;
using System.IO;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.VCProjectEngine;
using NaCl.Build.CPPTasks;
using NativeClientVSAddIn;
/// <summary>
/// This test class contains tests related to the custom project settings
/// and property pages for PPAPI and NaCl configurations.
/// </summary>
[TestClass]
public class ProjectSettingsTest
{
/// <summary>
/// The below string holds the path to a NaCl solution used in some tests.
/// A NaCl solution is a valid nacl/pepper plug-in VS solution.
/// It is copied into the testing deployment directory and opened in some tests.
/// In this solution, NaCl and pepper settings are copied from 'Empty' initial settings.
/// </summary>
private static string naclSolutionEmptyInitialization;
/// <summary>
/// The main visual studio object.
/// </summary>
private DTE2 dte_;
/// <summary>
/// The project configuration for debug settings of a test's platform.
/// </summary>
private VCConfiguration debug_;
/// <summary>
/// The project configuration for release settings of a test's platform
/// </summary>
private VCConfiguration release_;
/// <summary>
/// Gets or sets the test context which provides information about,
/// and functionality for the current test run.
/// </summary>
public TestContext TestContext { get; set; }
/// <summary>
/// This is run one time before any test methods are called. Here we set-up test-copies of
/// new NaCl solutions for use in the tests.
/// </summary>
/// <param name="testContext">Holds information about the current test run</param>
[ClassInitialize]
public static void ClassSetup(TestContext testContext)
{
DTE2 dte = TestUtilities.StartVisualStudioInstance();
try
{
naclSolutionEmptyInitialization = TestUtilities.CreateBlankValidNaClSolution(
dte,
"ProjectSettingsTestEmptyInit",
Strings.PepperPlatformName,
Strings.NaCl64PlatformName,
testContext);
}
finally
{
TestUtilities.CleanUpVisualStudioInstance(dte);
}
}
/// <summary>
/// This is run before each test to create test resources.
/// </summary>
[TestInitialize]
public void TestSetup()
{
dte_ = TestUtilities.StartVisualStudioInstance();
try
{
TestUtilities.AssertAddinLoaded(dte_, Strings.AddInName);
}
catch
{
TestUtilities.CleanUpVisualStudioInstance(dte_);
throw;
}
}
/// <summary>
/// This is run after each test to clean up things created in TestSetup().
/// </summary>
[TestCleanup]
public void TestCleanup()
{
TestUtilities.CleanUpVisualStudioInstance(dte_);
}
/// <summary>
/// Test method which verifies that NaCl and pepper platforms have correct default properties
/// when initialized from the Win32 platform.
/// </summary>
[TestMethod]
public void VerifySettingsWin32Initialization()
{
if (TestUtilities.IsVS2012())
{
// TODO(sbc): This test is unreliable under VS2012. http://crbug.com/246253
Assert.Inconclusive();
}
string solutionWin32Initialization = TestUtilities.CreateBlankValidNaClSolution(
dte_, "ProjectSettingsTestWin32Init", "Win32", "Win32", TestContext);
VerifyDefaultPepperSettings(solutionWin32Initialization);
VerifyDefaultNaClSettings(solutionWin32Initialization);
// Win32 inherit specific checks on the Pepper platform.
OpenSolutionAndGetProperties(solutionWin32Initialization, Strings.PepperPlatformName);
// When inheriting from Win32 preprocessor the PPAPI preprocessor definition gets grouped
// into the inherited %(PreprocessorDefinitions) variable. It still exists but doesn't appear
// in the property page, thus we can't check for it here.
// TODO(tysand): When inheriting from Win32 this won't set and the Win32 platform
// incorrectly(?) sets this to true in the Release config even for regular win32 projects.
//TestUtilities.AssertPropertyEquals(
// release_, "Link", "GenerateDebugInformation", "false", false);
dte_.Solution.Close();
// NaCl inherit specific checks on the NaCl platform.
OpenSolutionAndGetProperties(solutionWin32Initialization, Strings.NaCl64PlatformName);
AllConfigsAssertPropertyEquals("ConfigurationGeneral", "TargetExt", ".so", true);
AllConfigsAssertPropertyEquals(
"ConfigurationGeneral", "ConfigurationType", "DynamicLibrary", true);
dte_.Solution.Close();
}
/// <summary>
/// Test method which verifies that the NaCl platform has correct default properties
/// when initialized from the Pepper platform. And that the pepper platform has the correct
/// settings when initialized from the 'empty' settings.
/// </summary>
[TestMethod]
public void VerifySettingsPepperInitialization()
{
if (TestUtilities.IsVS2012())
{
// TODO(sbc): This test is unreliable under VS2012. http://crbug.com/246253
Assert.Inconclusive();
}
string solutionPepperInitialization = TestUtilities.CreateBlankValidNaClSolution(
dte_,
"ProjectSettingsTestPepperInit",
Strings.PepperPlatformName,
Strings.PepperPlatformName,
TestContext);
VerifyDefaultPepperSettings(solutionPepperInitialization);
VerifyDefaultNaClSettings(solutionPepperInitialization);
// Pepper inherit specific checks on the Pepper platform.
OpenSolutionAndGetProperties(solutionPepperInitialization, Strings.PepperPlatformName);
AllConfigsAssertPropertyContains("CL", "PreprocessorDefinitions", "PPAPI", false);
TestUtilities.AssertPropertyEquals(
release_, "Link", "GenerateDebugInformation", "false", false);
dte_.Solution.Close();
// NaCl inherit specific checks on the NaCl platform.
OpenSolutionAndGetProperties(solutionPepperInitialization, Strings.NaCl64PlatformName);
AllConfigsAssertPropertyEquals("ConfigurationGeneral", "TargetExt", ".nexe", true);
AllConfigsAssertPropertyEquals(
"ConfigurationGeneral", "ConfigurationType", "Application", true);
dte_.Solution.Close();
}
/// <summary>
/// Test that setting a custom NaClSDKRoot correctly effects the default values for
/// things like IncludePath. This test is needed to protect against regressions where
/// the order of the properties could cause NaClSDKRoot to not effect the defaults.
/// </summary>
[TestMethod]
public void OverrideSDKRootPepper()
{
string slnName = TestUtilities.CreateBlankValidNaClSolution(
dte_,
"OverrideSDKRootPepper",
Strings.PepperPlatformName,
Strings.PepperPlatformName,
TestContext);
OpenSolutionAndGetProperties(slnName, Strings.PepperPlatformName);
// VC++ Directories
string page = "ConfigurationGeneral";
IVCRulePropertyStorage pageStorage = debug_.Rules.Item(page);
pageStorage.SetPropertyValue("VSNaClSDKRoot", @"foo\");
page = "ConfigurationDirectories";
TestUtilities.AssertPropertyContains(debug_, page, "IncludePath", @"foo\include;", true, true);
TestUtilities.AssertPropertyContains(debug_, page, "IncludePath", @"foo\include\win;", true, true);
TestUtilities.AssertPropertyContains(debug_, page, "IncludePath", @"foo\include", true, true);
TestUtilities.AssertPropertyContains(debug_,
page, "LibraryPath", @"foo\lib\win_x86_32_host", true, true);
TestUtilities.AssertPropertyContains(debug_, page, "LibraryPath", @"foo\lib", true, true);
dte_.Solution.Close();
}
/// <summary>
/// Test that setting a custom NaClSDKRoot correctly effects the default values for
/// things like IncludePath. This test is needed to protect against regressions where
/// the order of the properties could cause NaClSDKRoot to not effect the defaults.
/// </summary>
[TestMethod]
public void OverrideSDKRootNaCl()
{
string slnName = TestUtilities.CreateBlankValidNaClSolution(
dte_,
"OverrideSDKRootNaCl",
Strings.NaCl64PlatformName,
Strings.NaCl64PlatformName,
TestContext);
OpenSolutionAndGetProperties(slnName, Strings.NaCl64PlatformName);
// VC++ Directories
string page = "ConfigurationGeneral";
IVCRulePropertyStorage pageStorage = debug_.Rules.Item(page);
pageStorage.SetPropertyValue("VSNaClSDKRoot", @"foo\");
page = "ConfigurationDirectories";
TestUtilities.AssertPropertyContains(debug_, page, "IncludePath", @"foo\include;", true, true);
TestUtilities.AssertPropertyContains(debug_, page, "LibraryPath", @"foo\lib", true, true);
dte_.Solution.Close();
}
/// <summary>
/// Test method which verifies that the Pepper platform has correct default properties
/// when initialized from the NaCl platform. And that the NaCl platform has the correct
/// settings when initialized from the 'empty' settings.
/// </summary>
[TestMethod]
public void VerifySettingsNaClInitialization()
{
if (TestUtilities.IsVS2012())
{
// TODO(sbc): This test is unreliable under VS2012. http://crbug.com/246253
Assert.Inconclusive();
}
string solutionNaClInitialization = TestUtilities.CreateBlankValidNaClSolution(
dte_,
"ProjectSettingsTestNaClInit",
Strings.NaCl64PlatformName,
Strings.NaCl64PlatformName,
TestContext);
VerifyDefaultPepperSettings(solutionNaClInitialization);
VerifyDefaultNaClSettings(solutionNaClInitialization);
// NaCl inherit specific checks on the Pepper platform.
OpenSolutionAndGetProperties(solutionNaClInitialization, Strings.PepperPlatformName);
AllConfigsAssertPropertyContains("CL", "PreprocessorDefinitions", "PPAPI", false);
TestUtilities.AssertPropertyEquals(
release_, "Link", "GenerateDebugInformation", "false", false);
dte_.Solution.Close();
// NaCl inherit specific checks on the NaCl platform.
OpenSolutionAndGetProperties(solutionNaClInitialization, Strings.NaCl64PlatformName);
AllConfigsAssertPropertyEquals("ConfigurationGeneral", "TargetExt", ".nexe", true);
AllConfigsAssertPropertyEquals(
"ConfigurationGeneral", "ConfigurationType", "Application", true);
dte_.Solution.Close();
}
/// <summary>
/// Method to run a battery of tests on a particular solution. Checks that all Pepper platform
/// settings are set correctly.
/// </summary>
/// <param name="naclSolution">Path to the solution file to verify.</param>
private void VerifyDefaultPepperSettings(string naclSolution)
{
OpenSolutionAndGetProperties(naclSolution, Strings.PepperPlatformName);
string page;
// General
page = "ConfigurationGeneral";
AllConfigsAssertPropertyEquals(page, "OutDir", @"$(ProjectDir)win\", true);
AllConfigsAssertPropertyEquals(page, "IntDir", @"win\$(Configuration)\", true);
AllConfigsAssertPropertyEquals(page, "TargetExt", ".dll", true);
AllConfigsAssertPropertyEquals(page, "ConfigurationType", "DynamicLibrary", true);
AllConfigsAssertPropertyEquals(page, "VSNaClSDKRoot", @"$(NACL_SDK_ROOT)\", false);
AllConfigsAssertPropertyEquals(page, "NaClWebServerPort", "5103", false);
AllConfigsAssertPropertyEquals(page, "CharacterSet", "Unicode", false);
AllConfigsAssertPropertyIsNotNullOrEmpty(page, "NaClAddInVersion");
// Debugging
page = "WindowsLocalDebugger";
string chromePath = System.Environment.GetEnvironmentVariable(
Strings.ChromePathEnvironmentVariable);
AllConfigsAssertPropertyEquals(
page, "LocalDebuggerCommand", chromePath, true);
string propName = "LocalDebuggerCommandArguments";
string dataDir = "--user-data-dir=\"$(ProjectDir)/chrome_data\"";
string address = "http://localhost:$(NaClWebServerPort)";
string targetFlag = "--register-pepper-plugins=\"$(TargetPath)\";application/x-ppapi";
string debugChildrenFlag = "--wait-for-debugger-children";
AllConfigsAssertPropertyContains(page, propName, dataDir, true);
AllConfigsAssertPropertyContains(page, propName, address, true);
AllConfigsAssertPropertyContains(page, propName, targetFlag, true);
TestUtilities.AssertPropertyContains(debug_, page, propName, debugChildrenFlag, true);
// VC++ Directories
page = "ConfigurationDirectories";
AllConfigsAssertPropertyContains(page, "IncludePath", @"$(VSNaClSDKRoot)include;", true);
AllConfigsAssertPropertyContains(page, "IncludePath", @"$(VSNaClSDKRoot)include\win;", true);
AllConfigsAssertPropertyContains(page, "IncludePath", @"$(VCInstallDir)include", true);
AllConfigsAssertPropertyContains(
page, "LibraryPath", @"$(VSNaClSDKRoot)lib\win_x86_32_host\$(Configuration);", true);
AllConfigsAssertPropertyContains(page, "LibraryPath", @"$(VCInstallDir)lib", true);
// C/C++ Code Generation
page = "CL";
TestUtilities.AssertPropertyEquals(release_, page, "RuntimeLibrary", "MultiThreaded", false);
TestUtilities.AssertPropertyEquals(
debug_, page, "RuntimeLibrary", "MultiThreadedDebug", false);
TestUtilities.AssertPropertyEquals(release_, page, "BasicRuntimeChecks", "Default", false);
TestUtilities.AssertPropertyEquals(
debug_, page, "BasicRuntimeChecks", "EnableFastChecks", false);
TestUtilities.AssertPropertyEquals(release_, page, "MinimalRebuild", "false", false);
TestUtilities.AssertPropertyEquals(debug_, page, "MinimalRebuild", "true", false);
TestUtilities.AssertPropertyEquals(
release_, page, "DebugInformationFormat", "ProgramDatabase", false);
TestUtilities.AssertPropertyEquals(
debug_, page, "DebugInformationFormat", "EditAndContinue", false);
// C/C++ Optimization
TestUtilities.AssertPropertyEquals(debug_, page, "Optimization", "Disabled", false);
TestUtilities.AssertPropertyEquals(release_, page, "Optimization", "MaxSpeed", false);
// Linker Input
page = "Link";
AllConfigsAssertPropertyContains(page, "AdditionalDependencies", "ppapi_cpp.lib", true);
AllConfigsAssertPropertyContains(page, "AdditionalDependencies", "ppapi.lib", true);
// Note: Release check of this property is specific to the platform settings were inherited
// from. Checks on release are done in the specific methods testing each inherit type.
TestUtilities.AssertPropertyEquals(debug_, page, "GenerateDebugInformation", "true", false);
TestUtilities.AssertPropertyEquals(release_, page, "LinkIncremental", "false", false);
TestUtilities.AssertPropertyEquals(debug_, page, "LinkIncremental", "true", false);
AllConfigsAssertPropertyEquals(page, "SubSystem", "Windows", false);
dte_.Solution.Close();
}
/// <summary>
/// Method to run a battery of tests on a particular solution. Checks that all NaCl platform
/// settings are set correctly.
/// </summary>
/// <param name="naclSolution">Path to the solution file to verify.</param>
private void VerifyDefaultNaClSettings(string naclSolution)
{
OpenSolutionAndGetProperties(naclSolution, Strings.NaCl64PlatformName);
string page;
// General
page = "ConfigurationGeneral";
AllConfigsAssertPropertyEquals(page, "OutDir", @"$(ProjectDir)$(Platform)\$(ToolchainName)\$(Configuration)\", true);
AllConfigsAssertPropertyEquals(
page, "IntDir", @"$(Platform)\$(ToolchainName)\$(Configuration)\", true);
AllConfigsAssertPropertyEquals(page, "ToolchainName", "newlib", true);
AllConfigsAssertPropertyEquals(page, "TargetArchitecture", "x86_64", true);
AllConfigsAssertPropertyEquals(page, "VSNaClSDKRoot", @"$(NACL_SDK_ROOT)\", false);
AllConfigsAssertPropertyEquals(page, "NaClManifestPath", string.Empty, false);
AllConfigsAssertPropertyEquals(page, "NaClWebServerPort", "5103", false);
AllConfigsAssertPropertyIsNotNullOrEmpty(page, "NaClAddInVersion");
// Debugging
page = "WindowsLocalDebugger";
string chromePath = System.Environment.GetEnvironmentVariable(
Strings.ChromePathEnvironmentVariable);
AllConfigsAssertPropertyEquals(
page, "LocalDebuggerCommand", chromePath, true);
string propName = "LocalDebuggerCommandArguments";
string dataDir = "--user-data-dir=\"$(ProjectDir)/chrome_data\"";
string address = "http://localhost:$(NaClWebServerPort)";
string naclFlag = "--enable-nacl";
string naclDebugFlag = "--enable-nacl-debug";
string noSandBoxFlag = "--no-sandbox";
TestUtilities.AssertPropertyContains(debug_, page, propName, dataDir, true);
TestUtilities.AssertPropertyContains(debug_, page, propName, address, true);
TestUtilities.AssertPropertyContains(debug_, page, propName, naclFlag, true);
TestUtilities.AssertPropertyContains(debug_, page, propName, naclDebugFlag, true);
TestUtilities.AssertPropertyContains(debug_, page, propName, noSandBoxFlag, true);
TestUtilities.AssertPropertyContains(release_, page, propName, dataDir, true);
TestUtilities.AssertPropertyContains(release_, page, propName, address, true);
TestUtilities.AssertPropertyContains(release_, page, propName, naclFlag, true);
// VC++ Directories
page = "ConfigurationDirectories";
AllConfigsAssertPropertyContains(page, "IncludePath", @"$(VSNaClSDKRoot)include;", true);
AllConfigsAssertPropertyContains(page, "LibraryPath", @"$(VSNaClSDKRoot)lib\$(ToolchainName)_x86_64\$(Configuration);", true);
// C/C++ General
page = "CL";
TestUtilities.AssertPropertyEquals(
debug_, page, "GenerateDebuggingInformation", "true", false);
TestUtilities.AssertPropertyEquals(
release_, page, "GenerateDebuggingInformation", "false", false);
AllConfigsAssertPropertyEquals(page, "Warnings", "NormalWarnings", true);
AllConfigsAssertPropertyEquals(page, "WarningsAsErrors", "false", true);
AllConfigsAssertPropertyEquals(page, "ConfigurationType", "$(ConfigurationType)", true);
AllConfigsAssertPropertyEquals(page, "UserHeaderDependenciesOnly", "true", true);
AllConfigsAssertPropertyEquals(page, "OutputCommandLine", "false", false);
// C/C++ Optimization
TestUtilities.AssertPropertyEquals(debug_, page, "OptimizationLevel", "O0", false);
TestUtilities.AssertPropertyEquals(release_, page, "OptimizationLevel", "O3", false);
// C/C++ Preprocessor
AllConfigsAssertPropertyContains(page, "PreprocessorDefinitions", "NACL", false);
// C/C++ Code Generation
AllConfigsAssertPropertyEquals(page, "ExceptionHandling", "true", false);
// C/C++ Output Files
AllConfigsAssertPropertyEquals(page, "ObjectFileName", @"$(IntDir)", false);
// C/C++ Advanced
AllConfigsAssertPropertyEquals(page, "CompileAs", "Default", true);
// Linker Input
page = "Link";
AllConfigsAssertPropertyContains(page, "AdditionalDependencies", "ppapi_cpp;ppapi", true);
dte_.Solution.Close();
}
/// <summary>
/// Helper function to reduce repeated code. Opens the given solution and sets the debug_
/// and release_ member variables to point to the given platform type.
/// </summary>
/// <param name="solutionPath">Path to the solution to open.</param>
/// <param name="platformName">Platform type to load.</param>
private void OpenSolutionAndGetProperties(string solutionPath, string platformName)
{
// Extract the debug and release configurations for Pepper from the project.
dte_.Solution.Open(solutionPath);
Project project = dte_.Solution.Projects.Item(TestUtilities.NaClProjectUniqueName);
Assert.IsNotNull(project, "Testing project was not found");
debug_ = TestUtilities.GetVCConfiguration(project, "Debug", platformName);
release_ = TestUtilities.GetVCConfiguration(project, "Release", platformName);
}
/// <summary>
/// Tests that a given property has a specific value for both Debug and Release
/// configurations under the current test's platform.
/// </summary>
/// <param name="pageName">Property page name where property resides.</param>
/// <param name="propertyName">Name of the property to check.</param>
/// <param name="expectedValue">Expected value of the property.</param>
/// <param name="ignoreCase">Ignore case when comparing the expected and actual values.</param>
private void AllConfigsAssertPropertyEquals(
string pageName,
string propertyName,
string expectedValue,
bool ignoreCase)
{
TestUtilities.AssertPropertyEquals(
debug_,
pageName,
propertyName,
expectedValue,
ignoreCase);
TestUtilities.AssertPropertyEquals(
release_,
pageName,
propertyName,
expectedValue,
ignoreCase);
}
/// <summary>
/// Tests that a given property contains a specific string for both Debug and Release
/// configurations under the current test's platform.
/// </summary>
/// <param name="pageName">Property page name where property resides.</param>
/// <param name="propertyName">Name of the property to check.</param>
/// <param name="expectedValue">Expected value of the property.</param>
/// <param name="ignoreCase">Ignore case when comparing the expected and actual values.</param>
private void AllConfigsAssertPropertyContains(
string pageName,
string propertyName,
string expectedValue,
bool ignoreCase)
{
TestUtilities.AssertPropertyContains(
debug_,
pageName,
propertyName,
expectedValue,
ignoreCase);
TestUtilities.AssertPropertyContains(
release_,
pageName,
propertyName,
expectedValue,
ignoreCase);
}
/// <summary>
/// Tests that a given property's value is not null or empty for both Debug and Release
/// configurations under the current test's platform.
/// </summary>
/// <param name="pageName">Property page name where property resides.</param>
/// <param name="propertyName">Name of the property to check.</param>
private void AllConfigsAssertPropertyIsNotNullOrEmpty(
string pageName,
string propertyName)
{
TestUtilities.AssertPropertyIsNotNullOrEmpty(
debug_,
pageName,
propertyName);
TestUtilities.AssertPropertyIsNotNullOrEmpty(
release_,
pageName,
propertyName);
}
}
}
| |
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
/*
* 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 ZooKeeperNet
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using Org.Apache.Jute;
using Org.Apache.Zookeeper.Proto;
public class ClientConnection : IClientConnection
{
private static readonly ILog LOG = LogManager.GetLogger(typeof(ClientConnection));
private static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromMilliseconds(500);
private static bool disableAutoWatchReset = false;
private static int maximumPacketLength = 1024 * 1024 * 4;
private static int maximumSpin = 30;
/// <summary>
/// Gets a value indicating how many times we should spin during waits.
/// Defaults to 30.
/// </summary>
public static int MaximumSpin
{
get { return maximumSpin; }
set
{
if (value <= 0)
{
string message = string.Format("Cannot set property '{0}' to less than zero. Value is: {1}.", "MaximumSpin", value);
throw new InvalidOperationException(message);
}
maximumSpin = value;
}
}
/// <summary>
/// Gets a value indicating the maximum packet length allowed.
/// Defaults to 4,194,304 (4MB).
/// </summary>
public static int MaximumPacketLength
{
get { return maximumPacketLength; }
set
{
if (value <= 0)
{
string message = string.Format("Cannot set property '{0}' to less than zero. Value is: {1}.", "MaximumPacketLength", value);
throw new InvalidOperationException(message);
}
maximumPacketLength = value;
}
}
/// <summary>
/// Gets a value indicating if auto watch reset should be disabled or not.
/// Defaults to <c>false</c>.
/// </summary>
public static bool DisableAutoWatchReset
{
get { return disableAutoWatchReset; }
set { disableAutoWatchReset = value; }
}
//static ClientConnection()
//{
// // this var should not be public, but otw there is no easy way
// // to test
// var zkSection = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("zookeeper");
// if (zkSection != null)
// {
// Boolean.TryParse(zkSection["disableAutoWatchReset"], out disableAutoWatchReset);
// }
// if (LOG.IsDebugEnabled)
// {
// LOG.DebugFormat("zookeeper.disableAutoWatchReset is {0}",disableAutoWatchReset);
// }
// //packetLen = Integer.getInteger("jute.maxbuffer", 4096 * 1024);
// packetLen = 4096 * 1024;
//}
internal string hosts;
internal readonly ZooKeeper zooKeeper;
internal readonly ZKWatchManager watcher;
internal readonly ISaslClient saslClient;
internal readonly List<IPEndPoint> serverAddrs = new List<IPEndPoint>();
internal readonly List<AuthData> authInfo = new List<AuthData>();
internal TimeSpan readTimeout;
private int isClosed;
public bool IsClosed
{
get
{
return Interlocked.CompareExchange(ref isClosed, 0, 0) == 1;
}
}
internal ClientConnectionRequestProducer producer;
internal ClientConnectionEventConsumer consumer;
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnection"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
/// <param name="sessionTimeout">The session timeout.</param>
/// <param name="zooKeeper">The zoo keeper.</param>
/// <param name="watcher">The watch manager.</param>
/// <param name="saslClient">The SASL client.</param>
public ClientConnection(string connectionString, TimeSpan sessionTimeout, ZooKeeper zooKeeper, ZKWatchManager watcher, ISaslClient saslClient) :
this(connectionString, sessionTimeout, zooKeeper, watcher, saslClient, 0, new byte[16], DefaultConnectTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnection"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
/// <param name="sessionTimeout">The session timeout.</param>
/// <param name="zooKeeper">The zoo keeper.</param>
/// <param name="watcher">The watch manager.</param>
/// <param name="connectTimeout">Connection Timeout.</param>
public ClientConnection(string connectionString, TimeSpan sessionTimeout, ZooKeeper zooKeeper, ZKWatchManager watcher, TimeSpan connectTimeout) :
this(connectionString, sessionTimeout, zooKeeper, watcher, 0, new byte[16], connectTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnection"/> class.
/// </summary>
/// <param name="hosts">The hosts.</param>
/// <param name="sessionTimeout">The session timeout.</param>
/// <param name="zooKeeper">The zoo keeper.</param>
/// <param name="watcher">The watch manager.</param>
/// <param name="sessionId">The session id.</param>
/// <param name="sessionPasswd">The session passwd.</param>
public ClientConnection(string hosts, TimeSpan sessionTimeout, ZooKeeper zooKeeper, ZKWatchManager watcher, long sessionId, byte[] sessionPasswd)
: this(hosts, sessionTimeout, zooKeeper, watcher, 0, new byte[16], DefaultConnectTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnection"/> class.
/// </summary>
/// <param name="hosts">The hosts.</param>
/// <param name="sessionTimeout">The session timeout.</param>
/// <param name="zooKeeper">The zoo keeper.</param>
/// <param name="watcher">The watch manager.</param>
/// <param name="saslClient">The SASL client.</param>
/// <param name="sessionId">The session id.</param>
/// <param name="sessionPasswd">The session passwd.</param>
public ClientConnection(string hosts, TimeSpan sessionTimeout, ZooKeeper zooKeeper, ZKWatchManager watcher, ISaslClient saslClient, long sessionId, byte[] sessionPasswd)
: this(hosts, sessionTimeout, zooKeeper, watcher, saslClient, 0, new byte[16], DefaultConnectTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnection"/> class.
/// </summary>
/// <param name="hosts">The hosts.</param>
/// <param name="sessionTimeout">The session timeout.</param>
/// <param name="zooKeeper">The zoo keeper.</param>
/// <param name="watcher">The watch manager.</param>
/// <param name="sessionId">The session id.</param>
/// <param name="sessionPasswd">The session passwd.</param>
/// <param name="connectTimeout">Connection Timeout.</param>
public ClientConnection(string hosts, TimeSpan sessionTimeout, ZooKeeper zooKeeper, ZKWatchManager watcher, long sessionId, byte[] sessionPasswd, TimeSpan connectTimeout) :
this(hosts, sessionTimeout, zooKeeper, watcher, null, sessionId, sessionPasswd, connectTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientConnection"/> class.
/// </summary>
/// <param name="hosts">The hosts.</param>
/// <param name="sessionTimeout">The session timeout.</param>
/// <param name="zooKeeper">The zoo keeper.</param>
/// <param name="watcher">The watch manager.</param>
/// <param name="saslClient">The SASL client.</param>
/// <param name="sessionId">The session id.</param>
/// <param name="sessionPasswd">The session passwd.</param>
/// <param name="connectTimeout">Connection Timeout.</param>
public ClientConnection(string hosts, TimeSpan sessionTimeout, ZooKeeper zooKeeper, ZKWatchManager watcher, ISaslClient saslClient, long sessionId, byte[] sessionPasswd, TimeSpan connectTimeout)
{
this.hosts = hosts;
this.zooKeeper = zooKeeper;
this.watcher = watcher;
this.saslClient = saslClient;
SessionTimeout = sessionTimeout;
SessionId = sessionId;
SessionPassword = sessionPasswd;
ConnectionTimeout = connectTimeout;
// parse out chroot, if any
hosts = SetChrootPath();
GetHosts(hosts);
SetTimeouts(sessionTimeout);
CreateConsumer();
CreateProducer();
}
private void CreateConsumer()
{
consumer = new ClientConnectionEventConsumer(this);
}
private void CreateProducer()
{
producer = new ClientConnectionRequestProducer(this);
}
private string SetChrootPath()
{
int off = hosts.IndexOf(PathUtils.PathSeparatorChar);
if (off >= 0)
{
string path = hosts.Substring(off);
// ignore "/" chroot spec, same as null
if (path.Length == 1)
ChrootPath = null;
else
{
PathUtils.ValidatePath(path);
ChrootPath = path;
}
hosts = hosts.Substring(0, off);
}
else
ChrootPath = null;
return hosts;
}
private void GetHosts(string hostLst)
{
string[] hostsList = hostLst.Split(',');
List<IPEndPoint> nonRandomizedServerAddrs = new List<IPEndPoint>();
foreach (string h in hostsList)
{
string host = h;
int port = 2181;
int pidx = h.LastIndexOf(':');
if (pidx >= 0)
{
// otherwise : is at the end of the string, ignore
if (pidx < h.Length - 1)
{
port = Int32.Parse(h.Substring(pidx + 1));
}
host = h.Substring(0, pidx);
}
// Handle dns-round robin or hostnames instead of IP addresses
var hostIps = ResolveHostToIpAddresses(host);
foreach (var ip in hostIps)
{
nonRandomizedServerAddrs.Add(new IPEndPoint(ip, port));
}
}
IEnumerable<IPEndPoint> randomizedServerAddrs
= nonRandomizedServerAddrs.OrderBy(s => Guid.NewGuid()); //Random order the servers
serverAddrs.AddRange(randomizedServerAddrs);
}
private IEnumerable<IPAddress> ResolveHostToIpAddresses(string host)
{
// if the host represents an explicit IP address, use it directly. otherwise
// lookup the name into it's IP addresses
IPAddress parsedAddress;
if (IPAddress.TryParse(host, out parsedAddress))
{
yield return parsedAddress;
}
else
{
IPHostEntry hostEntry = Dns.GetHostEntry(host);
IEnumerable<IPAddress> addresses = hostEntry.AddressList.Where(IsAllowedAddressFamily);
foreach (IPAddress address in addresses)
{
yield return address;
}
}
}
/// <summary>
/// Checks to see if the specified address has an allowable address family.
/// </summary>
/// <param name="address">The adress to check.</param>
/// <returns>
/// <c>true</c> if the address is in the allowable address families, otherwise <c>false</c>.
/// </returns>
private static bool IsAllowedAddressFamily(IPAddress address)
{
// in the future, IPv6 (AddressFamily.InterNetworkV6) should be supported
return address.AddressFamily == AddressFamily.InterNetwork;
}
private void SetTimeouts(TimeSpan sessionTimeout)
{
//since we have no need of it just remark it
//connectTimeout = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(sessionTimeout.TotalMilliseconds / serverAddrs.Count));
readTimeout = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(sessionTimeout.TotalMilliseconds * 2 / 3));
}
/// <summary>
/// Gets or sets the session timeout.
/// </summary>
/// <value>The session timeout.</value>
public TimeSpan SessionTimeout { get; private set; }
/// <summary>
/// Gets or sets the connection timeout.
/// </summary>
/// <value>The connection timeout.</value>
public TimeSpan ConnectionTimeout { get; private set; }
/// <summary>
/// Gets or sets the session password.
/// </summary>
/// <value>The session password.</value>
public byte[] SessionPassword { get; internal set; }
/// <summary>
/// Gets or sets the session id.
/// </summary>
/// <value>The session id.</value>
public long SessionId { get; internal set; }
/// <summary>
/// Gets or sets the chroot path.
/// </summary>
/// <value>The chroot path.</value>
public string ChrootPath { get; private set; }
public void Start()
{
consumer.Start();
producer.Start();
}
public void AddAuthInfo(string scheme, byte[] auth)
{
if (!zooKeeper.State.IsAlive())
return;
authInfo.Add(new AuthData(scheme, auth));
QueuePacket(new RequestHeader(-4, (int)OpCode.Auth), null, new AuthPacket(0, scheme, auth), null, null, null, null, null, null);
}
public ReplyHeader SubmitRequest(RequestHeader h, IRecord request, IRecord response, ZooKeeper.WatchRegistration watchRegistration)
{
ReplyHeader r = new ReplyHeader();
Packet p = QueuePacket(h, r, request, response, null, null, watchRegistration, null, null);
if (!p.Task.Wait(SessionTimeout))
{
throw new TimeoutException($"The request {request} timed out while waiting for a response from the server.");
}
return r;
}
public async Task<ReplyHeader> SubmitRequestAsync(RequestHeader h, IRecord request, IRecord response, ZooKeeper.WatchRegistration watchRegistration)
{
ReplyHeader r = new ReplyHeader();
Packet p = QueuePacket(h, r, request, response, null, null, watchRegistration, null, null);
CancellationTokenSource cts = new CancellationTokenSource();
if (await Task.WhenAny(p.Task, Task.Delay(SessionTimeout, cts.Token)).ConfigureAwait(false) != p.Task)
{
throw new TimeoutException($"The request {request} timed out while waiting for a response from the server.");
}
cts.Cancel(); // we haven't timed out - cancel the timeout task
await p.Task; // forces exceptions to be thrown correctly
return r;
}
public Packet QueuePacket(RequestHeader h, ReplyHeader r, IRecord request, IRecord response, string clientPath, string serverPath, ZooKeeper.WatchRegistration watchRegistration, object callback, object ctx)
{
return producer.QueuePacket(h, r, request, response, clientPath, serverPath, watchRegistration);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
private void InternalDispose()
{
if (Interlocked.CompareExchange(ref isClosed, 1, 0) == 0)
{
//closing = true;
if (LOG.IsDebugEnabled)
LOG.DebugFormat("Closing client for session: 0x{0:X}", SessionId);
try
{
SubmitRequest(new RequestHeader { Type = (int)OpCode.CloseSession }, null, null, null);
SpinWait spin = new SpinWait();
DateTime timeoutAt = DateTime.UtcNow.Add(SessionTimeout);
while (!producer.IsConnectionClosedByServer)
{
spin.SpinOnce();
if (spin.Count > MaximumSpin)
{
if (timeoutAt <= DateTime.UtcNow)
{
throw new TimeoutException(
string.Format("Timed out in Dispose() while closing session: 0x{0:X}", SessionId));
}
spin.Reset();
}
}
}
catch (ThreadInterruptedException)
{
// ignore, close the send/event threads
}
catch (Exception ex)
{
LOG.WarnFormat("Error disposing {0} : {1}", this.GetType().FullName, ex.Message);
}
finally
{
if (null != producer)
{
producer.Dispose();
}
if (null != consumer)
{
consumer.Dispose();
}
}
}
}
public void Dispose()
{
InternalDispose();
GC.SuppressFinalize(this);
}
~ClientConnection()
{
InternalDispose();
}
/// <summary>
/// Returns a <see cref="System.string"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.string"/> that represents this instance.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("sessionid:0x").AppendFormat("{0:X}", SessionId)
.Append(" lastZxid:").Append(producer.lastZxid)
.Append(" xid:").Append(producer.xid)
.Append(" sent:").Append(producer.sentCount)
.Append(" recv:").Append(producer.recvCount)
.Append(" queuedpkts:").Append(producer.OutgoingQueueCount)
.Append(" pendingresp:").Append(producer.PendingQueueCount)
.Append(" queuedevents:").Append(consumer.waitingEvents.Count);
return sb.ToString();
}
internal class AuthData
{
public string Scheme
{
get;
private set;
}
private byte[] data;
public byte[] GetData()
{
return data;
}
public AuthData(string scheme, byte[] data)
{
this.Scheme = scheme;
this.data = data;
}
}
internal class WatcherSetEventPair
{
public IEnumerable<IWatcher> Watchers
{
get;
private set;
}
public WatchedEvent WatchedEvent
{
get;
private set;
}
public WatcherSetEventPair(IEnumerable<IWatcher> watchers, WatchedEvent @event)
{
this.Watchers = watchers;
this.WatchedEvent = @event;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.