context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.GenerateType
{
[ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared]
internal class CSharpGenerateTypeService :
AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax>
{
private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
protected override string DefaultFileExtension => ".cs";
protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName)
{
return simpleName.GetLeftSideOfDot();
}
protected override bool IsInCatchDeclaration(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.CatchDeclaration);
}
protected override bool IsArrayElementType(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.ArrayType) &&
expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression);
}
protected override bool IsInValueTypeConstraintContext(
SemanticModel semanticModel,
ExpressionSyntax expression,
CancellationToken cancellationToken)
{
if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList))
{
var typeArgumentList = (TypeArgumentListSyntax)expression.Parent;
var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken);
var symbol = symbolInfo.GetAnySymbol();
if (symbol.IsConstructor())
{
symbol = symbol.ContainingType;
}
var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression);
var type = symbol as INamedTypeSymbol;
if (type != null)
{
type = type.OriginalDefinition;
var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
var method = symbol as IMethodSymbol;
if (method != null)
{
method = method.OriginalDefinition;
var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
}
return false;
}
protected override bool IsInInterfaceList(ExpressionSyntax expression)
{
if (expression is TypeSyntax &&
expression.Parent is BaseTypeSyntax &&
expression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)expression.Parent).Type == expression)
{
var baseList = (BaseListSyntax)expression.Parent.Parent;
// If it's after the first item, then it's definitely an interface.
if (baseList.Types[0] != expression.Parent)
{
return true;
}
// If it's in the base list of an interface or struct, then it's definitely an
// interface.
return
baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) ||
baseList.IsParentKind(SyntaxKind.StructDeclaration);
}
if (expression is TypeSyntax &&
expression.IsParentKind(SyntaxKind.TypeConstraint) &&
expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
{
var typeConstraint = (TypeConstraintSyntax)expression.Parent;
var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent;
var index = constraintClause.Constraints.IndexOf(typeConstraint);
// If it's after the first item, then it's definitely an interface.
return index > 0;
}
return false;
}
protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts)
{
nameParts = new List<string>();
return expression.TryGetNameParts(out nameParts);
}
protected override bool TryInitializeState(
SemanticDocument document,
SimpleNameSyntax simpleName,
CancellationToken cancellationToken,
out GenerateTypeServiceStateOptions generateTypeServiceStateOptions)
{
generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions();
if (simpleName.IsVar)
{
return false;
}
if (SyntaxFacts.IsAliasQualifier(simpleName))
{
return false;
}
// Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly
// unlikely that this would be a location where a user would be wanting to generate
// something. They're really just trying to reference something that exists but
// isn't available for some reason (i.e. a missing reference).
var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword)
{
return false;
}
ExpressionSyntax nameOrMemberAccessExpression = null;
if (simpleName.IsRightSideOfDot())
{
// This simplename comes from the cref
if (simpleName.IsParentKind(SyntaxKind.NameMemberCref))
{
return false;
}
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent;
// If we're on the right side of a dot, then the left side better be a name (and
// not an arbitrary expression).
var leftSideExpression = simpleName.GetLeftSideOfDot();
if (!leftSideExpression.IsKind(
SyntaxKind.QualifiedName,
SyntaxKind.IdentifierName,
SyntaxKind.AliasQualifiedName,
SyntaxKind.GenericName,
SyntaxKind.SimpleMemberAccessExpression))
{
return false;
}
}
else
{
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName;
}
// BUG(5712): Don't offer generate type in an enum's base list.
if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax &&
nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression &&
nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration))
{
return false;
}
// If we can guarantee it's a type only context, great. Otherwise, we may not want to
// provide this here.
var semanticModel = document.SemanticModel;
if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
// Don't offer Generate Type in an expression context *unless* we're on the left
// side of a dot. In that case the user might be making a type that they're
// accessing a static off of.
var syntaxTree = semanticModel.SyntaxTree;
var start = nameOrMemberAccessExpression.SpanStart;
var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken);
var isExpressionOrStatementContext = isExpressionContext || isStatementContext;
// Delegate Type Creation is not allowed in Non Type Namespace Context
generateTypeServiceStateOptions.IsDelegateAllowed = false;
if (!isExpressionOrStatementContext)
{
return false;
}
if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf())
{
if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot())
{
return false;
}
var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol;
var token = simpleName.GetLastToken().GetNextToken();
// We let only the Namespace to be left of the Dot
if (leftSymbol == null ||
!leftSymbol.IsKind(SymbolKind.Namespace) ||
!token.IsKind(SyntaxKind.DotToken))
{
return false;
}
else
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
// Global Namespace
if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess &&
!SyntaxFacts.IsInNamespaceOrTypeContext(simpleName))
{
var token = simpleName.GetLastToken().GetNextToken();
if (token.IsKind(SyntaxKind.DotToken) &&
simpleName.Parent == token.Parent)
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
}
var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>();
if (fieldDeclaration != null &&
fieldDeclaration.Parent is CompilationUnitSyntax &&
document.Document.SourceCodeKind == SourceCodeKind.Regular)
{
return false;
}
// Check to see if Module could be an option in the Type Generation in Cross Language Generation
var nextToken = simpleName.GetLastToken().GetNextToken();
if (simpleName.IsLeftSideOfDot() ||
nextToken.IsKind(SyntaxKind.DotToken))
{
if (simpleName.IsRightSideOfDot())
{
var parent = simpleName.Parent as QualifiedNameSyntax;
if (parent != null)
{
var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol;
if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace))
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
}
}
}
if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
if (nextToken.IsKind(SyntaxKind.DotToken))
{
// In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName
generateTypeServiceStateOptions.IsDelegateAllowed = false;
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
// case: class Foo<T> where T: MyType
if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any())
{
generateTypeServiceStateOptions.IsClassInterfaceTypes = true;
return true;
}
// Events
if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() ||
nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any())
{
// Case : event foo name11
// Only Delegate
if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax))
{
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
// Case : event SomeSymbol.foo name11
if (nameOrMemberAccessExpression is QualifiedNameSyntax)
{
// Only Namespace, Class, Struct and Module are allowed to contain Delegate
// Case : event Something.Mytype.<Delegate> Identifier
if (nextToken.IsKind(SyntaxKind.DotToken))
{
if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax)
{
return true;
}
else
{
Contract.Fail("Cannot reach this point");
}
}
else
{
// Case : event Something.<Delegate> Identifier
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
}
}
}
else
{
// MemberAccessExpression
if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)))
&& nameOrMemberAccessExpression.IsLeftSideOfDot())
{
// Check to see if the expression is part of Invocation Expression
ExpressionSyntax outerMostMemberAccessExpression = null;
if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
outerMostMemberAccessExpression = nameOrMemberAccessExpression;
}
else
{
Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression));
outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent;
}
outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault();
if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax)
{
generateTypeServiceStateOptions.IsEnumNotAllowed = true;
}
}
}
// Cases:
// // 1 - Function Address
// var s2 = new MyD2(foo);
// // 2 - Delegate
// MyD1 d = null;
// var s1 = new MyD2(d);
// // 3 - Action
// Action action1 = null;
// var s3 = new MyD2(action1);
// // 4 - Func
// Func<int> lambda = () => { return 0; };
// var s4 = new MyD3(lambda);
if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax)
{
var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent;
// Enum and Interface not Allowed in Object Creation Expression
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
if (objectCreationExpressionOpt.ArgumentList != null)
{
if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing)
{
return false;
}
// Get the Method symbol for the Delegate to be created
if (generateTypeServiceStateOptions.IsDelegateAllowed &&
objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 &&
objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken);
}
else
{
generateTypeServiceStateOptions.IsDelegateAllowed = false;
}
}
if (objectCreationExpressionOpt.Initializer != null)
{
foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
{
var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
if (simpleAssignmentExpression == null)
{
continue;
}
var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
if (name == null)
{
continue;
}
generateTypeServiceStateOptions.PropertiesToGenerate.Add(name);
}
}
}
if (generateTypeServiceStateOptions.IsDelegateAllowed)
{
// MyD1 z1 = foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration))
{
var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent;
if (variableDeclaration.Variables.Count != 0)
{
var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null);
if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken);
}
}
}
// var w1 = (MyD1)foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression))
{
var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent;
if (castExpression.Expression != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken);
}
}
}
return true;
}
private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
{
if (expression == null)
{
return null;
}
var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken);
if (memberGroup.Length != 0)
{
return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null;
}
var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType.IsDelegateType())
{
return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod;
}
var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol;
if (expressionSymbol.IsKind(SymbolKind.Method))
{
return (IMethodSymbol)expressionSymbol;
}
return null;
}
private Accessibility DetermineAccessibilityConstraint(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return semanticModel.DetermineAccessibilityConstraint(
state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken);
}
protected override IList<ITypeParameterSymbol> GetTypeParameters(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (state.SimpleName is GenericNameSyntax)
{
var genericName = (GenericNameSyntax)state.SimpleName;
var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count
? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList()
: Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity);
return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken);
}
return SpecializedCollections.EmptyList<ITypeParameterSymbol>();
}
protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList)
{
if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null)
{
argumentList = objectCreationExpression.ArgumentList.Arguments.ToList();
return true;
}
argumentList = null;
return false;
}
protected override IList<ParameterName> GenerateParameterNames(
SemanticModel semanticModel, IList<ArgumentSyntax> arguments)
{
return semanticModel.GenerateParameterNames(arguments);
}
public override string GetRootNamespace(CompilationOptions options)
{
return string.Empty;
}
protected override bool IsInVariableTypeContext(ExpressionSyntax expression)
{
return false;
}
protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken);
}
protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken)
{
var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken);
if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess)
{
var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken);
if (accessibilityConstraint == Accessibility.Public ||
accessibilityConstraint == Accessibility.Internal)
{
accessibility = accessibilityConstraint;
}
}
return accessibility;
}
protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
{
return argument.DetermineParameterType(semanticModel, cancellationToken);
}
protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
{
return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
}
public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync(
INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken)
{
var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot;
var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (containers.Length != 0)
{
// Search the NS declaration in the root
var containerList = new List<string>(containers);
var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit);
if (enclosingNamespace != null)
{
var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken);
if (enclosingNamespaceSymbol.Symbol != null)
{
return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol,
(INamespaceOrTypeSymbol)namedTypeSymbol,
enclosingNamespace.CloseBraceToken.GetLocation());
}
}
}
var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken);
var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers);
var lastMember = compilationUnit.Members.LastOrDefault();
Location afterThisLocation = null;
if (lastMember != null)
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0));
}
else
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan());
}
return Tuple.Create(globalNamespace,
rootNamespaceOrType,
afterThisLocation);
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
{
foreach (var member in compilationUnit.Members)
{
var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
if (namespaceDeclaration != null)
{
return namespaceDeclaration;
}
}
return null;
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
{
var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
{
return null;
}
List<string> namespaceContainers = new List<string>();
GetNamespaceContainers(namespaceDecl.Name, namespaceContainers);
if (namespaceContainers.Count + indexDone > containers.Count ||
!IdentifierMatches(indexDone, namespaceContainers, containers))
{
return null;
}
indexDone = indexDone + namespaceContainers.Count;
if (indexDone == containers.Count)
{
return namespaceDecl;
}
foreach (var member in namespaceDecl.Members)
{
var resultant = GetDeclaringNamespace(containers, indexDone, member);
if (resultant != null)
{
return resultant;
}
}
return null;
}
private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers)
{
for (int i = 0; i < namespaceContainers.Count; ++i)
{
if (namespaceContainers[i] != containers[indexDone + i])
{
return false;
}
}
return true;
}
private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers)
{
if (name is QualifiedNameSyntax)
{
GetNamespaceContainers(((QualifiedNameSyntax)name).Left, namespaceContainers);
namespaceContainers.Add(((QualifiedNameSyntax)name).Right.Identifier.ValueText);
}
else
{
Debug.Assert(name is SimpleNameSyntax);
namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText);
}
}
internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue)
{
typeKindValue = TypeKindOptions.AllOptions;
if (expression == null)
{
return false;
}
var node = expression as SyntaxNode;
while (node != null)
{
if (node is BaseListSyntax)
{
if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax))
{
typeKindValue = TypeKindOptions.Interface;
return true;
}
typeKindValue = TypeKindOptions.BaseList;
return true;
}
node = node.Parent;
}
return false;
}
internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project)
{
if (expression == null)
{
return false;
}
if (GeneratedTypesMustBePublic(project))
{
return true;
}
var node = expression as SyntaxNode;
SyntaxNode previousNode = null;
while (node != null)
{
// Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type
if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
var typeDecl = node.Parent as TypeDeclarationSyntax;
if (typeDecl != null)
{
if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return IsAllContainingTypeDeclsPublic(typeDecl);
}
else
{
// The Type Decl which contains the BaseList does not contain Public
return false;
}
}
Contract.Fail("Cannot reach this point");
}
if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
// Make sure the GFU is not inside the Accessors
if (previousNode != null && previousNode is AccessorListSyntax)
{
return false;
}
// Make sure that Event Declaration themselves are Public in the first place
if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return false;
}
return IsAllContainingTypeDeclsPublic(node);
}
previousNode = node;
node = node.Parent;
}
return false;
}
private bool IsAllContainingTypeDeclsPublic(SyntaxNode node)
{
// Make sure that all the containing Type Declarations are also Public
var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>();
if (containingTypeDeclarations.Count() == 0)
{
return true;
}
else
{
return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword));
}
}
internal override bool IsGenericName(SimpleNameSyntax simpleName)
{
if (simpleName == null)
{
return false;
}
var genericName = simpleName as GenericNameSyntax;
return genericName != null;
}
internal override bool IsSimpleName(ExpressionSyntax expression)
{
return expression is SimpleNameSyntax;
}
internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
{
// Nothing to include
if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
{
return updatedSolution;
}
SyntaxNode root = null;
if (modifiedRoot == null)
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
root = modifiedRoot;
}
if (root is CompilationUnitSyntax)
{
var compilationRoot = (CompilationUnitSyntax)root;
var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports));
// Check if the usings is already present
if (compilationRoot.Usings.Where(n => n != null && n.Alias == null)
.Select(n => n.Name.ToString())
.Any(n => n.Equals(includeUsingsOrImports)))
{
return updatedSolution;
}
// Check if the GFU is triggered from the namespace same as the usings namespace
if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false))
{
return updatedSolution;
}
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst);
var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
}
return updatedSolution;
}
private ITypeSymbol GetPropertyType(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken)
{
var parentAssignment = propertyName.Parent as AssignmentExpressionSyntax;
if (parentAssignment != null)
{
return typeInference.InferType(
semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken);
}
var isPatternExpression = propertyName.Parent as IsPatternExpressionSyntax;
if (isPatternExpression != null)
{
return typeInference.InferType(
semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken);
}
return null;
}
private IPropertySymbol CreatePropertySymbol(
SimpleNameSyntax propertyName, ITypeSymbol propertyType)
{
return CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: SpecializedCollections.EmptyList<AttributeData>(),
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
explicitInterfaceSymbol: null,
name: propertyName.Identifier.ValueText,
type: propertyType,
parameters: null,
getMethod: s_accessor,
setMethod: s_accessor,
isIndexer: false);
}
private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: null,
accessibility: Accessibility.Public,
statements: null);
internal override bool TryGenerateProperty(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken,
out IPropertySymbol property)
{
property = null;
var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken);
if (propertyType == null || propertyType is IErrorTypeSymbol)
{
property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType);
return property != null;
}
property = CreatePropertySymbol(propertyName, propertyType);
return property != null;
}
internal override IMethodSymbol GetDelegatingConstructor(
SemanticDocument document,
ObjectCreationExpressionSyntax objectCreation,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken)
{
var model = document.SemanticModel;
var oldNode = objectCreation
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
.LastOrDefault();
var typeNameToReplace = objectCreation.Type;
var newTypeName = namedType.GenerateTypeSyntax();
var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation);
var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation);
var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model);
if (speculativeModel != null)
{
newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken);
var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select(
a => a.DetermineParameterType(speculativeModel, cancellationToken)).ToList();
return GenerateConstructorHelpers.GetDelegatingConstructor(
document, symbolInfo, candidates, namedType, parameterTypes);
}
return null;
}
}
}
| |
// 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.Data.Common;
namespace System.Data.Odbc
{
public sealed partial class OdbcParameter : DbParameter
{
private object _value;
private object _parent;
private ParameterDirection _direction;
private int _size;
private int _offset;
private string _sourceColumn;
private DataRowVersion _sourceVersion;
private bool _sourceColumnNullMapping;
private bool _isNullable;
private object _coercedValue;
private OdbcParameter(OdbcParameter source) : this() { // V1.2.3300, Clone
ADP.CheckArgumentNull(source, nameof(source));
source.CloneHelper(this);
ICloneable cloneable = (_value as ICloneable);
if (null != cloneable)
{ // MDAC 49322
_value = cloneable.Clone();
}
}
private object CoercedValue
{
get
{
return _coercedValue;
}
set
{
_coercedValue = value;
}
}
public override ParameterDirection Direction
{
get
{
ParameterDirection direction = _direction;
return ((0 != direction) ? direction : ParameterDirection.Input);
}
set
{
if (_direction != value)
{
switch (value)
{
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
PropertyChanging();
_direction = value;
break;
default:
throw ADP.InvalidParameterDirection(value);
}
}
}
}
public override bool IsNullable
{
get
{
return _isNullable;
}
set
{
_isNullable = value;
}
}
public int Offset
{
get
{
return _offset;
}
set
{
if (value < 0)
{
throw ADP.InvalidOffsetValue(value);
}
_offset = value;
}
}
public override int Size
{
get
{
int size = _size;
if (0 == size)
{
size = ValueSize(Value);
}
return size;
}
set
{
if (_size != value)
{
if (value < -1)
{
throw ADP.InvalidSizeValue(value);
}
PropertyChanging();
_size = value;
}
}
}
private bool ShouldSerializeSize()
{
return (0 != _size);
}
public override string SourceColumn
{
get
{
string sourceColumn = _sourceColumn;
return ((null != sourceColumn) ? sourceColumn : ADP.StrEmpty);
}
set
{
_sourceColumn = value;
}
}
public override bool SourceColumnNullMapping
{
get
{
return _sourceColumnNullMapping;
}
set
{
_sourceColumnNullMapping = value;
}
}
override public DataRowVersion SourceVersion
{ // V1.2.3300, XXXParameter V1.0.3300
get
{
DataRowVersion sourceVersion = _sourceVersion;
return ((0 != sourceVersion) ? sourceVersion : DataRowVersion.Current);
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case DataRowVersion.Original:
case DataRowVersion.Current:
case DataRowVersion.Proposed:
case DataRowVersion.Default:
_sourceVersion = value;
break;
default:
throw ADP.InvalidDataRowVersion(value);
}
}
}
private void CloneHelperCore(OdbcParameter destination)
{
destination._value = _value;
// NOTE: _parent is not cloned
destination._direction = _direction;
destination._size = _size;
destination._offset = _offset;
destination._sourceColumn = _sourceColumn;
destination._sourceVersion = _sourceVersion;
destination._sourceColumnNullMapping = _sourceColumnNullMapping;
destination._isNullable = _isNullable;
}
internal object CompareExchangeParent(object value, object comparand)
{
object parent = _parent;
if (comparand == parent)
{
_parent = value;
}
return parent;
}
internal void ResetParent()
{
_parent = null;
}
public override string ToString()
{
return ParameterName;
}
private byte ValuePrecisionCore(object value)
{
if (value is decimal)
{
return ((System.Data.SqlTypes.SqlDecimal)(Decimal)value).Precision;
}
return 0;
}
private byte ValueScaleCore(object value)
{
if (value is decimal)
{
return (byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10);
}
return 0;
}
private int ValueSizeCore(object value)
{
if (!ADP.IsNull(value))
{
string svalue = (value as string);
if (null != svalue)
{
return svalue.Length;
}
byte[] bvalue = (value as byte[]);
if (null != bvalue)
{
return bvalue.Length;
}
char[] cvalue = (value as char[]);
if (null != cvalue)
{
return cvalue.Length;
}
if ((value is byte) || (value is char))
{
return 1;
}
}
return 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class File_Exists : FileSystemTest
{
#region Utilities
public virtual bool Exists(string path)
{
return File.Exists(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ReturnsFalse()
{
Assert.False(Exists(null));
}
[Fact]
public void EmptyAsPath_ReturnsFalse()
{
Assert.False(Exists(string.Empty));
}
[Fact]
public void NonExistentValidPath_ReturnsFalse()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (path) =>
{
Assert.False(Exists(path), path);
});
}
[Fact]
public void ValidPathExists_ReturnsTrue()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
{
string path = Path.Combine(TestDirectory, component);
FileInfo testFile = new FileInfo(path);
testFile.Create().Dispose();
Assert.True(Exists(path));
});
}
[Fact]
public void PathWithInvalidCharactersAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on paths with impossible to create characters
Assert.All((IOInputs.GetPathsWithInvalidCharacters()), (component) =>
{
Assert.False(Exists(component));
});
Assert.False(Exists(".."));
Assert.False(Exists("."));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void PathEndsInTrailingSlash()
{
string path = GetTestFilePath() + Path.DirectorySeparatorChar;
Assert.False(Exists(path));
}
[Fact]
public void PathAlreadyExistsAsDirectory()
{
string path = GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) =>
{
Assert.False(Exists(path));
});
}
[Fact]
public void DirectoryLongerThanMaxPathAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath())), (path) =>
{
Assert.False(Exists(path), path);
});
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void SymLinksMayExistIndependentlyOfTarget()
{
var path = GetTestFilePath();
var linkPath = GetTestFilePath();
File.Create(path).Dispose();
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false));
// Both the symlink and the target exist
Assert.True(File.Exists(path), "path should exist");
Assert.True(File.Exists(linkPath), "linkPath should exist");
// Delete the target. The symlink should still exist
File.Delete(path);
Assert.False(File.Exists(path), "path should now not exist");
Assert.True(File.Exists(linkPath), "linkPath should still exist");
// Now delete the symlink.
File.Delete(linkPath);
Assert.False(File.Exists(linkPath), "linkPath should no longer exist");
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix equivalent tested already in CreateDirectory
public void WindowsNonSignificantWhiteSpaceAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on impossible paths
Assert.All((IOInputs.GetWhiteSpace()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void DoesCaseInsensitiveInvariantComparions()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.True(Exists(testFile.FullName));
Assert.True(Exists(testFile.FullName.ToUpperInvariant()));
Assert.True(Exists(testFile.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void DoesCaseSensitiveComparions()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.True(Exists(testFile.FullName));
Assert.False(Exists(testFile.FullName.ToUpperInvariant()));
Assert.False(Exists(testFile.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // In Windows, trailing whitespace in a path is trimmed
public void TrimTrailingWhitespacePath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.All((IOInputs.GetWhiteSpace()), (component) =>
{
Assert.True(Exists(testFile.FullName + component)); // string concat in case Path.Combine() trims whitespace before Exists gets to it
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data stream
public void PathWithAlternateDataStreams_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithAlternativeDataStreams()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[OuterLoop]
[PlatformSpecific(PlatformID.Windows)] // device names
public void PathWithReservedDeviceNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithReservedDeviceNames()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC paths
public void UncPathWithoutShareNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetUncPathsWithoutShareName()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithComponentLongerThanMaxComponent()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void FalseForNonRegularFile()
{
string fileName = GetTestFilePath();
Assert.Equal(0, mkfifo(fileName, 0));
Assert.True(File.Exists(fileName));
}
#endregion
}
}
| |
using System;
using Microsoft.SPOT;
namespace IngenuityMicro.Radius.Fonts
{
public class SegoeBig
{
public static byte[] Zero =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xE0,
0xF0, 0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0,
0xE0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xF8, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x3F, 0x1F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x0F, 0x3F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFC, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC,
0xE0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xF0, 0xFC,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x3F,
0x7F, 0x7F, 0x7F, 0xFF, 0xFE, 0xFE, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0x7F, 0x7F, 0x7F, 0x3F, 0x3F,
0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] One =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0xE0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFC, 0xFC, 0xFC, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE,
0xFF, 0xFF, 0x7F, 0x7F, 0x3F, 0x3F, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Two =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xE0, 0xF0, 0xF0, 0xF0,
0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0, 0xE0,
0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x3F, 0x3F, 0x1F, 0x0F, 0x0F, 0x07,
0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x0F, 0x3F, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF0, 0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF,
0x7F, 0x3F, 0x0F, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF0,
0xF8, 0xFC, 0xFE, 0xFF, 0xFF, 0x7F, 0x7F, 0x3F, 0x1F, 0x0F, 0x0F, 0x07, 0x03, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xF8, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F,
0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Three =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF8, 0xF8,
0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0, 0xF0, 0xE0,
0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0F, 0x0F, 0x07, 0x07, 0x03, 0x03,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x0F, 0x7F, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFC, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF8, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0x7F, 0x3F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x7E, 0x7E,
0x7E, 0x7E, 0x7E, 0x7E, 0xFE, 0xFE, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xE3,
0xC3, 0xC1, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x03, 0x07, 0x1F, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xFC, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x3F, 0x3F, 0x7F, 0x7F, 0x7F, 0x7F, 0xFE, 0xFE,
0xFE, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0x7E, 0x7F, 0x7F, 0x7F, 0x3F, 0x3F, 0x1F,
0x1F, 0x0F, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Four =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xF0, 0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xE0, 0xF0, 0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0x0F, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFE, 0xFF, 0xFF,
0xFF, 0x7F, 0x3F, 0x1F, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xEF, 0xE7, 0xE3,
0xE1, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Five =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x1F, 0x1F, 0x1F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFE, 0xFE, 0xFE,
0xFC, 0xF8, 0xF8, 0xF0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x0F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF8, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x7F, 0x7F, 0x7F, 0x7F, 0xFE, 0xFE,
0xFE, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0xFE, 0x7F, 0x7F, 0x7F, 0x3F, 0x3F, 0x1F,
0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Six =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xC0, 0xC0, 0xE0, 0xE0, 0xF0, 0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8,
0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xF0, 0xF8, 0xFE, 0xFF, 0xFF,
0xFF, 0xFF, 0x7F, 0x3F, 0x0F, 0x0F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F,
0x07, 0x01, 0x00, 0x80, 0x80, 0x80, 0x80, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80, 0x80, 0x80, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC,
0xFE, 0xFF, 0x7F, 0x3F, 0x3F, 0x1F, 0x1F, 0x0F, 0x0F, 0x1F, 0x1F, 0x1F, 0x3F, 0x3F, 0x7F, 0xFF,
0xFF, 0xFF, 0xFE, 0xFE, 0xFC, 0xF8, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F,
0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xF0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0,
0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F,
0x3F, 0x7F, 0x7F, 0x7F, 0xFE, 0xFE, 0xFC, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0xFF, 0x7F, 0x7F, 0x7F,
0x3F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Seven =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x83, 0xE3, 0xFB, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF,
0x7F, 0x1F, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xF8, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x0F, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE0, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F, 0x07, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Eight =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xE0, 0xF0,
0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0,
0xE0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFC, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x7F, 0x0F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x0F, 0x3F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x3F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFC, 0xE0, 0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0xC0, 0xE0, 0xF8, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3F, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE1, 0xF3, 0xF3, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x7F, 0x7F, 0x7F, 0x3F, 0x3F, 0x3F, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xF3, 0xF3, 0xE1, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x0F,
0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07,
0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xE0,
0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0,
0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x3F, 0x7F,
0x7F, 0x7F, 0x7F, 0xFE, 0xFE, 0xFE, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0xFE, 0x7F, 0x7F, 0x7F, 0x7F,
0x3F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Nine =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xE0, 0xF0,
0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0, 0xF0,
0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xF8, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3F,
0x0F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x1F, 0x3F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xF8, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC1, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x1F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xF8, 0xF0, 0xF0, 0xE0, 0xE0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xE0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x07, 0x07,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x07, 0x07, 0x03, 0xC3,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF8, 0xFE, 0xFF,
0xFF, 0xFF, 0xFF, 0x7F, 0x3F, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x7F, 0x7F, 0x7F, 0xFE, 0xFE, 0xFE,
0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0x7F, 0x7F, 0x7F, 0x3F, 0x3F, 0x1F, 0x1F, 0x0F,
0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
public static byte[] Colon =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF8, 0xFC, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFC, 0xFC, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3E, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x7F, 0x1E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
}
}
| |
using Newtonsoft.Json.Linq;
using ReactNative.UIManager;
using ReactNative.UIManager.Annotations;
using ReactNative.UIManager.Events;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace ReactNative.Views.Picker
{
/// <summary>
/// A view manager responsible for rendering picker.
/// </summary>
public class ReactPickerManager : BaseViewManager<ComboBox, ReactPickerShadowNode>
{
/// <summary>
/// The name of the view manager.
/// </summary>
public override string Name
{
get
{
return "RCTPicker";
}
}
/// <summary>
/// Sets whether a picker is enabled.
/// </summary>
/// <param name="view">a combobox view.</param>
/// <param name="enabled">
/// Set to <code>true</code> if the picker should be enabled,
/// otherwise, set to <code>false</code>.
/// </param>
[ReactProp("enabled")]
public void SetEnabled(ComboBox view, bool enabled)
{
view.IsEnabled = enabled;
}
/// <summary>
/// Sets the selected item.
/// </summary>
/// <param name="view">a combobox instance.</param>
/// <param name="selected">The selected item.</param>
[ReactProp("selected")]
public void SetSelected(ComboBox view, int selected)
{
// Temporarily disable selection changed event handler.
view.SelectionChanged -= OnSelectionChanged;
view.SelectedIndex = view.Items.Count > selected ? selected : -1;
if (view.SelectedIndex != -1)
{
view.Foreground = ((ComboBoxItem)(view.Items[view.SelectedIndex])).Foreground;
}
view.SelectionChanged += OnSelectionChanged;
}
/// <summary>
/// Populates a <see cref="ComboBox"/>
/// </summary>
/// <param name="view">a combobox instance.</param>
/// <param name="items">The picker items.</param>
[ReactProp("items")]
public void SetItems(ComboBox view, JArray items)
{
// Temporarily disable selection changed event handler.
view.SelectionChanged -= OnSelectionChanged;
var selectedIndex = view.SelectedIndex;
view.Items.Clear();
foreach (var itemToken in items)
{
var itemData = (JObject)itemToken;
var label = itemData.Value<string>("label");
if (label != null)
{
var item = new ComboBoxItem
{
Content = label,
};
var color = itemData.GetValue("color", StringComparison.Ordinal);
if (color != null)
{
var rgb = color.Value<uint>();
item.Foreground = new SolidColorBrush(ColorHelpers.Parse(rgb));
}
view.Items.Add(item);
}
}
if (selectedIndex < items.Count)
{
view.SelectedIndex = selectedIndex;
}
view.SelectionChanged += OnSelectionChanged;
}
/// <summary>
/// This method should return the <see cref="ReactPickerShadowNode"/>
/// which will be then used for measuring the position and size of the
/// view.
/// </summary>
/// <returns>The shadow node instance.</returns>
public override ReactPickerShadowNode CreateShadowNodeInstance()
{
return new ReactPickerShadowNode();
}
/// <summary>
/// Implement this method to receive optional extra data enqueued from
/// the corresponding instance of <see cref="ReactShadowNode"/> in
/// <see cref="ReactShadowNode.OnCollectExtraUpdates"/>.
/// </summary>
/// <param name="root">The root view.</param>
/// <param name="extraData">The extra data.</param>
public override void UpdateExtraData(ComboBox root, object extraData)
{
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup by the <see cref="ReactPickerManager"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view.</param>
public override void OnDropViewInstance(ThemedReactContext reactContext, ComboBox view)
{
base.OnDropViewInstance(reactContext, view);
view.SelectionChanged -= OnSelectionChanged;
}
/// <summary>
/// Creates a new view instance of type <see cref="ComboBox"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <returns>The view instance.</returns>
protected override ComboBox CreateViewInstance(ThemedReactContext reactContext)
{
return new ComboBox();
}
/// <summary>
/// Subclasses can override this method to install custom event
/// emitters on the given view.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view instance.</param>
protected override void AddEventEmitters(ThemedReactContext reactContext, ComboBox view)
{
base.AddEventEmitters(reactContext, view);
view.SelectionChanged += OnSelectionChanged;
}
/// <summary>
/// Selection changed event handler.
/// </summary>
/// <param name="sender">an event sender.</param>
/// <param name="e">the event.</param>
private void OnSelectionChanged(object sender, RoutedEventArgs e)
{
var comboBox = (ComboBox)sender;
var reactContext = comboBox.GetReactContext();
reactContext.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new ReactPickerEvent(
comboBox.GetTag(),
comboBox.SelectedIndex));
}
/// <summary>
/// A picker specific event.
/// </summary>
class ReactPickerEvent : Event
{
private readonly int _selectedIndex;
public ReactPickerEvent(int viewTag, int selectedIndex)
: base(viewTag)
{
_selectedIndex = selectedIndex;
}
public override string EventName
{
get
{
return "topSelect";
}
}
public override void Dispatch(RCTEventEmitter eventEmitter)
{
var eventData = new JObject
{
{ "target", ViewTag },
{ "position", _selectedIndex },
};
eventEmitter.receiveEvent(ViewTag, EventName, eventData);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UI
{
/// <summary>
/// Class which creates (prints) a user interface to the console. Can
/// create multiple input field forms, forms with a single input field,
/// alerts over the current console buffer and has support for
/// pseudo control scrolling (incase the inputted text is wider
/// than the control width in characters).
/// </summary>
public partial class UserInterface
{
/// <summary>
/// Creates a form with multiple input fields, formatted as a two-column
/// table. Prompts are displayed in the left column, whereas the input
/// fields are displayed in the right column.
/// </summary>
/// <param name="prompts">An array of input prompts for each input field.</param>
/// <param name="types">
/// Name of the accepted type in the input field.
/// Must be either string or int.
/// </param>
/// <param name="validators">
/// An array of validator functions which return bool and accept object
/// as their first and only parameter. Two default validators for string
/// and int objects are implemented, but are overriden if a custom validator
/// is passed for the respective input field.
/// </param>
/// <returns>
/// Returns a list of the objects the user entered in each input field.
/// </returns>
public List<object> MultipleInputString(string[] prompts, string[] types, Func<object, bool>[] validators)
{
Table t = new Table();
foreach (string prompt in prompts)
t.AddRow(new object[] { prompt, "" });
t.Draw();
int oldX = Console.CursorLeft;
int oldY = Console.CursorTop;
List<object> toReturn = new List<object>();
for (int i = 0; i < prompts.Length; i++)
{
Console.CursorLeft = t.Rows[i].Cells[1].X;
Console.CursorTop = t.Rows[i].Cells[1].Y;
string vrijednost = InputWithOverflow(t.Rows[i].Cells[1].Width - TableSettings.CELL_PADDING * 2);
if(vrijednost == "")
{
Alert(strings.NoInputError);
ResetField(ref t, i, vrijednost.Length);
i--;
}
else if (types[i] == "string")
{
if (validators.Length > i)
{
bool parsed = validators[i](vrijednost);
if (parsed)
toReturn.Add(vrijednost);
else
{
Alert(strings.NotAStringOrNotValidated);
ResetField(ref t, i, t.Rows[i].Cells[1].Width - TableSettings.CELL_PADDING * 2);
i--;
}
}
}
else if (types[i] == "int")
{
int number = 0;
bool parsed = int.TryParse(vrijednost, out number);
if (validators.Length > i)
if (parsed)
parsed = validators[i](number);
if (!parsed)
{
Alert(strings.NotANumberOrNotValidated);
ResetField(ref t, i, t.Rows[i].Cells[1].Width - TableSettings.CELL_PADDING * 2);
i--;
continue;
}
else
toReturn.Add(number);
}
else if (types[i] == "date")
{
DateTime date;
bool parsed = DateTime.TryParseExact(vrijednost, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
if (validators.Length > i)
if (parsed)
parsed = validators[i](date);
if (!parsed)
{
Alert(strings.NotADate);
ResetField(ref t, i, t.Rows[i].Cells[1].Width - TableSettings.CELL_PADDING * 2);
i--;
continue;
}
else
toReturn.Add(date);
}
}
Console.CursorLeft = oldX;
Console.CursorTop = oldY;
return toReturn;
}
/// <summary>
/// Creates a single input field formatted as a single-row two-column
/// table with the prompt text shown in the left column.
/// </summary>
/// <param name="prompt">The prompt text which appears to the left.</param>
/// <returns>Returns a string entered by the user in the input field.</returns>
public string InputString(string prompt, Func<string, bool> validator = null, string errMsg = null)
{
Table t = new Table();
t.AddRow(new object[] { prompt, "" })
.Draw();
int oldX = Console.CursorLeft;
int oldY = Console.CursorTop;
Console.CursorLeft = t.Rows[0].Cells[1].X;
Console.CursorTop = t.Rows[0].Cells[1].Y;
string toRet = "";
while(true)
{
toRet = InputWithOverflow(t.Rows[0].Cells[1].Width - TableSettings.CELL_PADDING * 2);
if (validator != null)
{
if (!validator(toRet))
{
if (errMsg == null)
Alert(strings.NotAStringOrNotValidated);
else
Alert(errMsg);
ResetField(ref t, 0, t.Rows[0].Cells[1].Width - TableSettings.CELL_PADDING * 2);
}
else if(toRet.Length > 0)
break;
}
else if(toRet.Length > 0)
break;
}
Console.ResetColor();
Console.CursorLeft = oldX;
Console.CursorTop = oldY;
return toRet;
}
/// <summary>
/// This basically creates an input field with a specified maximum
/// display width. That is, if the user enters more characters than
/// this width, the input field will scroll to the right.
/// </summary>
/// <param name="width">
/// Maximum number of characters the input field will display.
/// </param>
/// <returns>Returns a string entered by the user in the input field.</returns>
private string InputWithOverflow(int width)
{
string input = "";
int startX = Console.CursorLeft;
ConsoleKeyInfo ck = new ConsoleKeyInfo();
while ((ck = Console.ReadKey(true)).Key != ConsoleKey.Enter)
{
if (ck.Key == ConsoleKey.Backspace)
{
if (Console.CursorLeft > startX)
{
Console.CursorLeft = Console.CursorLeft - 1;
Console.Write(" ");
Console.CursorLeft = Console.CursorLeft - 1;
input = input.Substring(0, input.Length - 1);
if (input.Length >= width)
{
Console.CursorLeft = startX;
Console.Write(input.Substring(input.Length - width));
}
continue;
}
}
else if (ck.KeyChar >= 33 && ck.KeyChar <= 126 || ck.Key == ConsoleKey.Spacebar)
{
char c = ck.KeyChar;
input += c;
if (input.Length > width)
{
Console.CursorLeft = startX;
Console.Write(input.Substring(input.Length - width));
}
else
{
Console.Write(c);
}
}
}
return input;
}
/// <summary>
/// Displays an alert box over the current console buffer. Can either be
/// an informative alert box, or a yes/no question box. The alert box is
/// 20 characters shorter than the console screen width.
/// </summary>
/// <param name="message">The message that will be displayed inside the box.</param>
/// <param name="foregroundColor">Font color of the alert box text.</param>
/// <param name="backgroundColor">Background color of the alert box.</param>
/// <param name="yesNo">
/// A boolean indicating whether this is a yes/no question box.
/// </param>
/// <returns></returns>
public bool Alert(string message, ConsoleColor foregroundColor = ConsoleColor.White, ConsoleColor backgroundColor = ConsoleColor.Red, bool yesNo = false)
{
int i = 0;
for(int j = 0; j <= 10; j++)
{
i += 2;
}
int oldX = Console.CursorLeft, oldY = Console.CursorTop;
short left = 10, top = (short)oldY, w = (short)(Console.BufferWidth - 20);
List<string> messageLines = Utility.SeparateString(message, w - 4);
short h = (short)messageLines.Count;
h += 4;
if (yesNo) h += 2;
top -= (short)(h + 10);
if (top < 5) top = 5;
IEnumerable<string> prevBuffer = ConsoleReader.ReadFromBuffer(left, top, w, h);
List<string> prevBuffer2 = new List<string>(prevBuffer);
Console.ForegroundColor = foregroundColor;
Console.BackgroundColor = backgroundColor;
// Top border
Console.SetCursorPosition(left, top);
Console.Write(Box.TopLeft);
for (int j = 0; j < w - 2; j++)
Console.Write(Box.Horizontal);
Console.Write(Box.TopRight);
// Spacer
Console.SetCursorPosition(left, top + 1);
Console.Write("{0" + ",-" + (w - 1) + "}{0}", Box.Vertical);
// Message, keep watch on overflow
int i = 0;
for(i = 0; i < messageLines.Count; i++)
{
Console.SetCursorPosition(left, top + 2 + i);
Console.Write("{0} {1,-" + (w - 4) + "} {0}", Box.Vertical, messageLines[i]);
}
// Spacer
Console.SetCursorPosition(left, top + 2 + i);
Console.Write("{0" + ",-" + (w - 1) + "}{0}", Box.Vertical);
if (yesNo)
{
// Spacer
Console.SetCursorPosition(left, top + 2 + i);
Console.Write("{0" + ",-" + (w - 1) + "}{0}", Box.Vertical);
i++;
Console.SetCursorPosition(left, top + 2 + i);
Console.Write("{0} {1,-" + (w - 9) + "}{2,5} {0}", Box.Vertical, "[Y]es", "[N]o");
i++;
// Spacer
Console.SetCursorPosition(left, top + 2 + i);
Console.Write("{0" + ",-" + (w - 1) + "}{0}", Box.Vertical);
}
// Bottom border
Console.SetCursorPosition(left, top + 3 + i);
Console.Write(Box.BottomLeft);
for (int j = 0; j < w - 2; j++)
Console.Write(Box.Horizontal);
Console.Write(Box.BottomRight);
ConsoleKeyInfo keyPressed = Console.ReadKey(true);
// Return the old state
Console.ResetColor();
int k = 0;
foreach (string s in prevBuffer2)
{
Console.CursorLeft = left;
Console.CursorTop = top + k;
Console.Write(s);
k++;
}
Console.CursorLeft = oldX;
Console.CursorTop = oldY;
if (yesNo)
{
return (keyPressed.KeyChar == 'Y' || keyPressed.KeyChar == 'y');
}
return false;
}
/// <summary>
/// Clears the current text/value of the 2nd cell inside a
/// two-columned table used as input forms in some functions.
/// </summary>
/// <param name="t">Reference to the table maker.</param>
/// <param name="i">Row number of the cell.</param>
/// <param name="width">Width of the text that was previously
/// entered, so we don't have to clear the whole cell.</param>
private void ResetField(ref Table t, int i, int width)
{
Console.CursorLeft = t.Rows[i].Cells[1].X;
Console.CursorTop = t.Rows[i].Cells[1].Y;
for (int j = 0; j < width; j++)
Console.Write(" ");
Console.CursorLeft = t.Rows[i].Cells[1].X;
Console.CursorTop = t.Rows[i].Cells[1].Y;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace GDIDrawer
{
internal partial class DrawerWnd : Form
{
string sVersion = "GDIDrawer:" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
internal readonly int m_ciWidth;
internal readonly int m_ciHeight;
// log file
internal StatusLog _log = null;
// position of the window (must be invoked)
internal delegate void delSetPos(Point pos);
internal void SetDTPos(Point pos)
{
DesktopLocation = pos;
}
// position of the window (must be invoked)
internal delegate Point delGetPos();
internal Point GetDTPos()
{
return DesktopLocation;
}
// size of the window (must be invoked)
internal delegate Size delGetSize();
internal Size GetWndSize()
{
return new Size(this.Width, this.Height);
}
// delegate types for owner callbacks
internal delegate int delIntGraphics(Graphics gr);
internal delegate void delVoidPoint(Point p);
internal delegate void delLocalKeyEvent(bool bIsDown, Keys keyCode);
// event delegates (set by owner, null if not in use)
internal delIntGraphics m_delRender;
internal delVoidPoint m_delMouseMove;
internal delVoidPoint m_delMouseLeftClick;
internal delVoidPoint m_delMouseRightClick;
internal delVoidPoint m_delMouseLeftRelease;
internal delVoidPoint m_delMouseRightRelease;
internal delLocalKeyEvent m_delKeyEvent;
// this flag indicates that the drawer window is fully initialized and ready for rendering
internal bool m_bIsInitialized = false;
// flag indicates that thread/form should terminate, flagged from CDrawer.Close(), checked in timer
internal bool m_bTerminate = false;
// image for layer underlay operations
private Bitmap m_bmUnderlay;
// back-buffer parts (created once and reused for efficiency)
BufferedGraphicsContext m_bgc;
BufferedGraphics m_bg;
byte[] m_argbs = null;
// stopwatch for render time calcs
private System.Diagnostics.Stopwatch m_StopWatch = new System.Diagnostics.Stopwatch();
private Queue<long> m_qRenderAvg = new Queue<long>();
private bool m_bContinuousUpdate = true;
public bool ContinuousUpdate
{
get { return m_bContinuousUpdate; }
set { m_bContinuousUpdate = value; }
}
private bool m_bRenderNow = true;
public bool RenderNow
{
get { return m_bRenderNow; }
set { m_bRenderNow = value; }
}
public DrawerWnd(CDrawer dr)
{
InitializeComponent();
// use the log as built from parent
_log = dr._log;
// save window size
m_ciWidth = dr.m_ciWidth;
m_ciHeight = dr.m_ciHeight;
// cap delegates, this will be set by owner
m_delRender = null;
m_delMouseMove = null;
m_delMouseLeftClick = null;
m_delMouseRightClick = null;
m_delMouseLeftRelease = null;
m_delMouseRightRelease = null;
// cap/set references
m_bgc = new BufferedGraphicsContext();
m_bg = null;
// create the bitmap for the underlay and clear it to whatever colour
m_bmUnderlay = new Bitmap(dr.m_ciWidth, dr.m_ciHeight); // docs say will use Format32bppArgb
// fill the bitmap with the default drawer bb colour
FillBB(Color.Black);
// show that drawer is up and running
_log.WriteLine("Drawer Started...");
}
//testing version
internal void FillBBRect(Rectangle rect, Color c)
{
// set region
lock (m_bmUnderlay)
{
if (m_bmUnderlay.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
// for each Y, lock the row to reduce copying
for (int y = rect.Top; y < rect.Bottom; ++y)
{
// ensure it's worth doing
if (y >= 0 && y < m_ciHeight)
{
// grab this scan row
// lock up the parts of the image to write to (rect)
System.Drawing.Imaging.BitmapData bmd = m_bmUnderlay.LockBits(
new Rectangle(0, y, m_ciWidth, 1),
System.Drawing.Imaging.ImageLockMode.ReadWrite,
m_bmUnderlay.PixelFormat);
// copy data out to a buffer
if (m_argbs == null || m_argbs.Length != bmd.Stride)
m_argbs = new byte[bmd.Stride];
System.Runtime.InteropServices.Marshal.Copy(bmd.Scan0, m_argbs, 0, bmd.Stride);
// fill colours (only valid area)
int iPos = 0;
for (int x = rect.Left; x < rect.Right; ++x)
{
if (x >= 0 && x < m_ciWidth)
{
iPos = x * 4;
m_argbs[iPos++] = c.B;
m_argbs[iPos++] = c.G;
m_argbs[iPos++] = c.R;
m_argbs[iPos++] = c.A;
}
}
// write back into array and unlock the image
System.Runtime.InteropServices.Marshal.Copy(m_argbs, 0, bmd.Scan0, bmd.Stride);
m_bmUnderlay.UnlockBits(bmd);
}
}
}
else
{
throw new Exception("Unexpected BB Bitmap Format!");
}
}
}
/*
// fill in a section of the backbuffer (rect), with a color (c)
internal void FillBBRectLast(Rectangle rect, Color c)
{
// set region
lock (m_bmUnderlay)
{
if (m_bmUnderlay.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
// lock up the parts of the image to write to (rect)
System.Drawing.Imaging.BitmapData bmd = m_bmUnderlay.LockBits(
new Rectangle(0, 0, m_ciWidth, m_ciHeight),
System.Drawing.Imaging.ImageLockMode.ReadWrite,
m_bmUnderlay.PixelFormat);
// copy data out to a buffer
if (m_argbs == null || m_argbs.Length != bmd.Stride * bmd.Height)
m_argbs = new byte[bmd.Stride * bmd.Height];
// investigate doing this line by line?
//IntPtr ptr = bmd.Scan0;
//IntPtr b = new IntPtr (ptr.ToInt32() + bmd.Stride);
//Console.WriteLine("Stride is : " + bmd.Stride.ToString());
System.Runtime.InteropServices.Marshal.Copy(bmd.Scan0, m_argbs, 0, bmd.Stride * bmd.Height);
//Console.WriteLine("filling rectangle : " + rect.ToString());
// fill colours (only valid area)
int iPos = 0;
for (int y = rect.Top; y < rect.Bottom; ++y)
{
if (y >= 0 && y < m_ciHeight)
{
for (int x = rect.Left; x < rect.Right; ++x)
{
if (x >= 0 && x < m_ciWidth)
{
iPos = (y * bmd.Stride) + (x * 4);
m_argbs[iPos++] = c.B;
m_argbs[iPos++] = c.G;
m_argbs[iPos++] = c.R;
m_argbs[iPos++] = c.A;
}
}
}
}
// write back into array and unlock the image
System.Runtime.InteropServices.Marshal.Copy(m_argbs, 0, bmd.Scan0, bmd.Stride * bmd.Height);
m_bmUnderlay.UnlockBits(bmd);
}
else
{
throw new Exception("Unexpected BB Bitmap Format!");
}
}
}
*/
internal void FillBB(Color c)
{
lock (m_bmUnderlay)
{
if (m_bmUnderlay.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
{
// lock up the parts of the image to write to (all of it)
System.Drawing.Imaging.BitmapData bmd = m_bmUnderlay.LockBits(
new Rectangle(0, 0, m_ciWidth, m_ciHeight),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
m_bmUnderlay.PixelFormat);
// copy data out to a buffer
if (m_argbs == null || m_argbs.Length != bmd.Stride * bmd.Height)
m_argbs = new byte[bmd.Stride * bmd.Height];
for (int i = 0; i < m_argbs.Length; )
{
m_argbs[i++] = c.B;
m_argbs[i++] = c.G;
m_argbs[i++] = c.R;
m_argbs[i++] = c.A;
}
// write back into array and unlock the image
System.Runtime.InteropServices.Marshal.Copy(m_argbs, 0, bmd.Scan0, m_argbs.Length);
m_bmUnderlay.UnlockBits(bmd);
}
else
{
throw new Exception("Unexpected BB Bitmap Format!");
}
}
}
private void Render()
{
// check to ensure that there is actually a callback registered
if (m_delRender != null)
{
int iNumRendered = 0;
// reset and start the stopwatch
m_StopWatch.Reset();
m_StopWatch.Start();
// stop the timer, could be a long time for rendering
UI_TIM_RENDER.Enabled = false;
// copy the layover bitmap to the backbuffer for erasure/layover (eating mem)
try
{
lock (m_bmUnderlay)
m_bg.Graphics.DrawImage(m_bmUnderlay, new Point(0, 0));
}
catch (Exception err)
{
_log.WriteLine("DrawerWnd::Render (Underlay) : " + err.Message);
}
// invoke controller class rendering...
try
{
iNumRendered = m_delRender(m_bg.Graphics);
}
catch (Exception err)
{
_log.WriteLine("DrawerWnd::Render (main) : " + err.Message);
}
// flip bb to fb
try
{
m_bg.Render();
}
catch (Exception err)
{
_log.WriteLine("DrawerWnd::Render (Flip) : " + err.Message);
}
// stop the stopwatch
m_StopWatch.Stop();
// do avarage calculation
m_qRenderAvg.Enqueue(m_StopWatch.ElapsedMilliseconds);
while (m_qRenderAvg.Count > 75)
m_qRenderAvg.Dequeue();
double dTot = 0;
foreach (long l in m_qRenderAvg)
dTot += l;
dTot = dTot / m_qRenderAvg.Count;
// Show render time...
if (iNumRendered == 1)
Text = sVersion + " - Render Time = " + dTot.ToString("f2") + "ms (" + iNumRendered.ToString() + " shape)";
else
Text = sVersion + " - Render Time = " + dTot.ToString("f2") + "ms (" + iNumRendered.ToString() + " shapes)";
// restart the timer
UI_TIM_RENDER.Enabled = true;
}
}
private void UI_TIM_RENDER_Tick(object sender, EventArgs e)
{
if (m_bTerminate) // that's it we are done,
{
UI_TIM_RENDER.Enabled = false;
Close();
return;
}
if (!m_bContinuousUpdate && !m_bRenderNow)
return;
m_bRenderNow = false;
Render();
}
private void DrawerWnd_MouseMove(object sender, MouseEventArgs e)
{
// if delegate is registered, fire off coords
if (m_delMouseMove != null && e.X >= 0 && e.X < m_ciWidth && e.Y > 0 && e.Y < m_ciHeight)
{
try
{
m_delMouseMove(e.Location);
}
catch (Exception err)
{
_log.WriteLine("Error in MouseMove event - " + err.Message);
}
}
}
private void DrawerWnd_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (m_delMouseLeftClick != null && e.X >= 0 && e.X < m_ciWidth && e.Y > 0 && e.Y < m_ciHeight)
{
try
{
m_delMouseLeftClick(e.Location);
}
catch (Exception err)
{
_log.WriteLine("Error in MouseDown event - " + err.Message);
}
}
}
else if (e.Button == MouseButtons.Right)
{
if (m_delMouseRightClick != null && e.X >= 0 && e.X < m_ciWidth && e.Y > 0 && e.Y < m_ciHeight)
{
try
{
m_delMouseRightClick(e.Location);
}
catch (Exception err)
{
_log.WriteLine("Error in MouseDown event - " + err.Message);
}
}
}
}
internal void SetBBImage (Bitmap bm)
{
// try it the fast way...
try
{
lock (m_bmUnderlay)
{
if ((bm.Width != m_bmUnderlay.Width) || (bm.Height != m_bmUnderlay.Height))
throw new ArgumentException("BBImage must be the same dimensions as the backbuffer!");
m_bmUnderlay = new Bitmap(bm);
}
}
catch (Exception err)
{
_log.WriteLine("DrawerWnd::SetBBImage : " + err.Message);
}
}
internal void SetBBPixel(Point p, Color c)
{
if (m_bmUnderlay != null && p.X >= 0 && p.X < m_ciWidth && p.Y >= 0 && p.Y < m_ciHeight)
{
try
{
lock (m_bmUnderlay)
m_bmUnderlay.SetPixel(p.X, p.Y, c);
}
catch (Exception err)
{
_log.WriteLine("DrawerWnd::SetBBPixel : " + err.Message);
}
}
}
internal Color GetBBPixel(Point p)
{
if (m_bmUnderlay != null && p.X >= 0 && p.X < m_ciWidth && p.Y >= 0 && p.Y < m_ciHeight)
{
try
{
lock (m_bmUnderlay)
return m_bmUnderlay.GetPixel(p.X, p.Y);
}
catch (Exception err)
{
_log.WriteLine("DrawerWnd::GetBBPixel : " + err.Message);
}
}
throw new ArgumentException("Unable to get pixel!");
}
private void DrawerWnd_Shown(object sender, EventArgs e)
{
// create frontbuffer
Graphics gr = CreateGraphics();
// create the re-useable back-buffer object from the context and current display surface
// if the surface is lost, this will be a problem...
m_bg = m_bgc.Allocate(gr, DisplayRectangle);
// start the rendering timer (done here as other inits require time and a primary surface to work)
UI_TIM_RENDER.Enabled = true;
}
// Locate the drawer to the bottom right of the primary display
private void DrawerWnd_Load(object sender, EventArgs e)
{
// set the window size accordingly
ClientSize = new Size(m_ciWidth, m_ciHeight);
// set the window position (as best fit to bottom right)
if (System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width >= Size.Width &&
System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height >= Size.Height)
{
SetDesktopLocation(
System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width - Size.Width,
System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height - Size.Height);
}
else
{
// window position will be upper-left, or whatever Windows thinks is a good idea...
}
}
private void DrawerWnd_Paint(object sender, PaintEventArgs e)
{
Render();
// mark as all initialization of this object is done
m_bIsInitialized = true;
}
private void DrawerWnd_KeyDown(object sender, KeyEventArgs e)
{
if (m_delKeyEvent != null)
{
try
{
m_delKeyEvent(true, e.KeyCode);
}
catch (Exception err)
{
_log.WriteLine("Error in KeyDown event - " + err.Message);
}
}
}
private void DrawerWnd_KeyUp(object sender, KeyEventArgs e)
{
if (m_delKeyEvent != null)
{
try
{
m_delKeyEvent(false, e.KeyCode);
}
catch (Exception err)
{
_log.WriteLine("Error in KeyUp event - " + err.Message);
}
}
}
private void DrawerWnd_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (m_delMouseLeftRelease != null && e.X >= 0 && e.X < m_ciWidth && e.Y > 0 && e.Y < m_ciHeight)
{
try
{
m_delMouseLeftRelease(e.Location);
}
catch (Exception err)
{
_log.WriteLine("Error in MouseUp event - " + err.Message);
}
}
}
else if (e.Button == MouseButtons.Right)
{
if (m_delMouseRightRelease != null && e.X >= 0 && e.X < m_ciWidth && e.Y > 0 && e.Y < m_ciHeight)
{
try
{
m_delMouseRightRelease(e.Location);
}
catch (Exception err)
{
_log.WriteLine("Error in MouseRelease event - " + err.Message);
}
}
}
}
}
}
| |
namespace Orleans.CodeGenerator
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.CodeGeneration;
using Orleans.CodeGenerator.Utilities;
using Orleans.Runtime;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using System.Diagnostics;
/// <summary>
/// Code generator which generates <see cref="GrainReference"/>s for grains.
/// </summary>
public static class GrainReferenceGenerator
{
/// <summary>
/// The suffix appended to the name of generated classes.
/// </summary>
private const string ClassSuffix = "Reference";
/// <summary>
/// A reference to the CheckGrainObserverParamInternal method.
/// </summary>
private static readonly Expression<Action> CheckGrainObserverParamInternalExpression =
() => GrainFactoryBase.CheckGrainObserverParamInternal(null);
/// <summary>
/// Generates the class for the provided grain types.
/// </summary>
/// <param name="grainType">
/// The grain interface type.
/// </param>
/// <param name="onEncounteredType">
/// The callback which is invoked when a type is encountered.
/// </param>
/// <returns>
/// The generated class.
/// </returns>
internal static TypeDeclarationSyntax GenerateClass(Type grainType, Action<Type> onEncounteredType)
{
var grainTypeInfo = grainType.GetTypeInfo();
var genericTypes = grainTypeInfo.IsGenericTypeDefinition
? grainTypeInfo.GetGenericArguments()
.Select(_ => SF.TypeParameter(_.ToString()))
.ToArray()
: new TypeParameterSyntax[0];
// Create the special marker attribute.
var markerAttribute =
SF.Attribute(typeof(GrainReferenceAttribute).GetNameSyntax())
.AddArgumentListArguments(
SF.AttributeArgument(
SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false))));
var attributes = SF.AttributeList()
.AddAttributes(
CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
SF.Attribute(typeof(SerializableAttribute).GetNameSyntax()),
SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()),
markerAttribute);
var className = CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix;
var classDeclaration =
SF.ClassDeclaration(className)
.AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
.AddBaseListTypes(
SF.SimpleBaseType(typeof(GrainReference).GetTypeSyntax()),
SF.SimpleBaseType(grainType.GetTypeSyntax()))
.AddConstraintClauses(grainType.GetTypeConstraintSyntax())
.AddMembers(GenerateConstructors(className))
.AddMembers(
GenerateInterfaceIdProperty(grainType),
GenerateInterfaceNameProperty(grainType),
GenerateIsCompatibleMethod(grainType),
GenerateGetMethodNameMethod(grainType))
.AddMembers(GenerateInvokeMethods(grainType, onEncounteredType))
.AddAttributeLists(attributes);
if (genericTypes.Length > 0)
{
classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
}
return classDeclaration;
}
/// <summary>
/// Generates constructors.
/// </summary>
/// <param name="className">The class name.</param>
/// <returns>Constructor syntax for the provided class name.</returns>
private static MemberDeclarationSyntax[] GenerateConstructors(string className)
{
var baseConstructors =
typeof(GrainReference).GetConstructors(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(_ => !_.IsPrivate);
var constructors = new List<MemberDeclarationSyntax>();
foreach (var baseConstructor in baseConstructors)
{
var args = baseConstructor.GetParameters()
.Select(arg => SF.Argument(arg.Name.ToIdentifierName()))
.ToArray();
var declaration =
baseConstructor.GetDeclarationSyntax(className)
.WithInitializer(
SF.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer)
.AddArgumentListArguments(args))
.AddBodyStatements();
constructors.Add(declaration);
}
return constructors.ToArray();
}
/// <summary>
/// Generates invoker methods.
/// </summary>
/// <param name="grainType">The grain type.</param>
/// <param name="onEncounteredType">
/// The callback which is invoked when a type is encountered.
/// </param>
/// <returns>Invoker methods for the provided grain type.</returns>
private static MemberDeclarationSyntax[] GenerateInvokeMethods(Type grainType, Action<Type> onEncounteredType)
{
var baseReference = SF.BaseExpression();
var methods = GrainInterfaceUtils.GetMethods(grainType);
var members = new List<MemberDeclarationSyntax>();
foreach (var method in methods)
{
onEncounteredType(method.ReturnType);
var methodId = GrainInterfaceUtils.ComputeMethodId(method);
var methodIdArgument =
SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId)));
// Construct a new object array from all method arguments.
var parameters = method.GetParameters();
var body = new List<StatementSyntax>();
foreach (var parameter in parameters)
{
onEncounteredType(parameter.ParameterType);
if (typeof(IGrainObserver).IsAssignableFrom(parameter.ParameterType))
{
body.Add(
SF.ExpressionStatement(
CheckGrainObserverParamInternalExpression.Invoke()
.AddArgumentListArguments(SF.Argument(parameter.Name.ToIdentifierName()))));
}
}
// Get the parameters argument value.
ExpressionSyntax args;
if (parameters.Length == 0)
{
args = SF.LiteralExpression(SyntaxKind.NullLiteralExpression);
}
else
{
args =
SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax())
.WithInitializer(
SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(parameters.Select(GetParameterForInvocation).ToArray()));
}
var options = GetInvokeOptions(method);
// Construct the invocation call.
if (method.ReturnType == typeof(void))
{
var invocation = SF.InvocationExpression(baseReference.Member("InvokeOneWayMethod"))
.AddArgumentListArguments(methodIdArgument)
.AddArgumentListArguments(SF.Argument(args));
if (options != null)
{
invocation = invocation.AddArgumentListArguments(options);
}
body.Add(SF.ExpressionStatement(invocation));
}
//else if (GrainInterfaceUtils.IsReactiveComputationType(method.ReturnType))
//{
// var resultTypeArgument =
// SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId)));
// var returnType = method.ReturnType.GenericTypeArguments[0];
// args =
// SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax())
// .WithInitializer(
// SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression)
// .AddExpressions(parameters.Select(GetParameterForInvocation).ToArray()));
// var invocation =
// SF.InvocationExpression(baseReference.Member("CreateReactiveComputation", returnType.GenericTypeArguments[0]))
// .AddArgumentListArguments(methodIdArgument)
// .AddArgumentListArguments(SF.Argument(args));
// if (options != null)
// {
// invocation = invocation.AddArgumentListArguments(options);
// }
// body.Add(SF.ReturnStatement(invocation));
//}
//else if (grainType is IReactiveGrain)
//{
// var returnType = (method.ReturnType == typeof(Task))
// ? typeof(object)
// : method.ReturnType.GenericTypeArguments[0];
// var invocation =
// SF.InvocationExpression(baseReference.Member("InvokeMethodAsync", returnType))
// .AddArgumentListArguments(methodIdArgument)
// .AddArgumentListArguments(SF.Argument(args));
// if (options != null)
// {
// invocation = invocation.AddArgumentListArguments(options);
// }
// body.Add(SF.ReturnStatement(invocation));
//}
else if (GrainInterfaceUtils.IsTaskType(method.ReturnType))
{
var returnType = (method.ReturnType == typeof(Task))
? typeof(object)
: method.ReturnType.GenericTypeArguments[0];
var invocation =
SF.InvocationExpression(baseReference.Member("InvokeMethodAsync", returnType))
.AddArgumentListArguments(methodIdArgument)
.AddArgumentListArguments(SF.Argument(args));
if (options != null)
{
invocation = invocation.AddArgumentListArguments(options);
}
body.Add(SF.ReturnStatement(invocation));
}
members.Add(method.GetDeclarationSyntax().AddBodyStatements(body.ToArray()));
}
return members.ToArray();
}
/// <summary>
/// Returns syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and <see cref="GrainReference.InvokeOneWayMethod"/>.
/// </summary>
/// <param name="method">The method which an invoke call is being generated for.</param>
/// <returns>
/// Argument syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and
/// <see cref="GrainReference.InvokeOneWayMethod"/>, or <see langword="null"/> if no options are to be specified.
/// </returns>
private static ArgumentSyntax GetInvokeOptions(MethodInfo method)
{
var options = new List<ExpressionSyntax>();
if (GrainInterfaceUtils.IsReadOnly(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.ReadOnly.ToString()));
}
if (GrainInterfaceUtils.IsUnordered(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.Unordered.ToString()));
}
if (GrainInterfaceUtils.IsAlwaysInterleave(method))
{
options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.AlwaysInterleave.ToString()));
}
ExpressionSyntax allOptions;
if (options.Count <= 1)
{
allOptions = options.FirstOrDefault();
}
else
{
allOptions =
options.Aggregate((a, b) => SF.BinaryExpression(SyntaxKind.BitwiseOrExpression, a, b));
}
if (allOptions == null)
{
return null;
}
return SF.Argument(SF.NameColon("options"), SF.Token(SyntaxKind.None), allOptions);
}
private static ExpressionSyntax GetParameterForInvocation(ParameterInfo arg, int argIndex)
{
var argIdentifier = arg.GetOrCreateName(argIndex).ToIdentifierName();
// Addressable arguments must be converted to references before passing.
if (typeof(IAddressable).IsAssignableFrom(arg.ParameterType)
&& (typeof(Grain).IsAssignableFrom(arg.ParameterType) || arg.ParameterType.GetTypeInfo().IsInterface))
{
return
SF.ConditionalExpression(
SF.BinaryExpression(SyntaxKind.IsExpression, argIdentifier, typeof(Grain).GetTypeSyntax()),
SF.InvocationExpression(argIdentifier.Member("AsReference", arg.ParameterType)),
argIdentifier);
}
return argIdentifier;
}
private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType)
{
var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId);
var returnValue = SF.LiteralExpression(
SyntaxKind.NumericLiteralExpression,
SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType)));
return
SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name)
.AddAccessorListAccessors(
SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.AddBodyStatements(SF.ReturnStatement(returnValue)))
.AddModifiers(SF.Token(SyntaxKind.ProtectedKeyword), SF.Token(SyntaxKind.OverrideKeyword));
}
private static MemberDeclarationSyntax GenerateIsCompatibleMethod(Type grainType)
{
var method = TypeUtils.Method((GrainReference _) => _.IsCompatible(default(int)));
var methodDeclaration = method.GetDeclarationSyntax();
var interfaceIdParameter = method.GetParameters()[0].Name.ToIdentifierName();
var interfaceIds =
new HashSet<int>(
new[] { GrainInterfaceUtils.GetGrainInterfaceId(grainType) }.Concat(
GrainInterfaceUtils.GetRemoteInterfaces(grainType).Keys));
var returnValue = default(BinaryExpressionSyntax);
foreach (var interfaceId in interfaceIds)
{
var check = SF.BinaryExpression(
SyntaxKind.EqualsExpression,
interfaceIdParameter,
SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)));
// If this is the first check, assign it, otherwise OR this check with the previous checks.
returnValue = returnValue == null
? check
: SF.BinaryExpression(SyntaxKind.LogicalOrExpression, returnValue, check);
}
return
methodDeclaration.AddBodyStatements(SF.ReturnStatement(returnValue))
.AddModifiers(SF.Token(SyntaxKind.OverrideKeyword));
}
private static MemberDeclarationSyntax GenerateInterfaceNameProperty(Type grainType)
{
var propertyName = TypeUtils.Member((GrainReference _) => _.InterfaceName);
var returnValue = grainType.GetParseableName().GetLiteralExpression();
return
SF.PropertyDeclaration(typeof(string).GetTypeSyntax(), propertyName.Name)
.AddAccessorListAccessors(
SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.AddBodyStatements(SF.ReturnStatement(returnValue)))
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword));
}
private static MethodDeclarationSyntax GenerateGetMethodNameMethod(Type grainType)
{
// Get the method with the correct type.
var method =
typeof(GrainReference)
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(m => m.Name == "GetMethodName");
var methodDeclaration =
method.GetDeclarationSyntax()
.AddModifiers(SF.Token(SyntaxKind.OverrideKeyword));
var parameters = method.GetParameters();
var interfaceIdArgument = parameters[0].Name.ToIdentifierName();
var methodIdArgument = parameters[1].Name.ToIdentifierName();
var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch(
grainType,
methodIdArgument,
methodType => new StatementSyntax[] { SF.ReturnStatement(methodType.Name.GetLiteralExpression()) });
// Generate the default case, which will throw a NotImplementedException.
var errorMessage = SF.BinaryExpression(
SyntaxKind.AddExpression,
"interfaceId=".GetLiteralExpression(),
interfaceIdArgument);
var throwStatement =
SF.ThrowStatement(
SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax())
.AddArgumentListArguments(SF.Argument(errorMessage)));
var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement);
var interfaceIdSwitch =
SF.SwitchStatement(interfaceIdArgument).AddSections(interfaceCases.ToArray()).AddSections(defaultCase);
return methodDeclaration.AddBodyStatements(interfaceIdSwitch);
}
}
}
| |
using System;
using System.Drawing; // Graphics, SolidBrush, etc.
using System.Windows.Forms; // Form, etc.
using System.Xml.Serialization; // XmlSerializer
using EXT = Casey.TraySystemMonitor.Ext;
namespace Casey.TraySystemMonitor.Gui
{
/// <summary>
/// The notify icon that is the main UI for this project
/// </summary>
public partial class MainForm : Form
{
#region Private Fields
/// <summary>Name of the preferences file</summary>
private const string PREFS_FILE = "prefs.xml";
/// <summary>Number of ticks before a graph is decreased</summary>
private const int FALL_TIMEOUT = 30;
/// <summary>Minimum graph maximum</summary>
private const int SMALLEST_MAXIMUM = 100;
/// <summary>Preferences object</summary>
private Preferences _prefs = null;
/// <summary>Provider displaying on the left</summary>
private EXT.IStatusProvider _left = null;
/// <summary>Provider displaying on the right</summary>
private EXT.IStatusProvider _right = null;
/// <summary>List of all the known providers</summary>
System.Collections.Generic.IList<EXT.IStatusProvider> _providers = null;
/// <summary>Maximum value for the left side</summary>
private int _leftMax = 100;
/// <summary>Maximum value for the right side</summary>
private int _rightMax = 100;
/// <summary>Number of ticks the left is below the midline</summary>
private int _leftBelowMidline = 0;
/// <summary>Number of ticks the right is below the midline</summary>
private int _rightBelowMidline = 0;
#endregion Private Fields
#region Public Methods
/// <summary>
/// Constructor
/// </summary>
/// <param name="providers">List of all the known providers</param>
public MainForm(System.Collections.Generic.IList<EXT.IStatusProvider> providers)
{
InitializeComponent();
_providers = providers;
// Establish the preferences, either by reading the existing
// preferences XML or by creating a new one.
if (System.IO.File.Exists(PREFS_FILE))
{
XmlSerializer ser = new XmlSerializer(typeof(Preferences));
using (System.IO.StreamReader sr = new System.IO.StreamReader(PREFS_FILE))
{
_prefs = (Preferences)ser.Deserialize(sr);
}
}
else
{
_prefs = new Preferences();
if (_providers.Count > 1)
{
_prefs.LeftProvider = _providers[0].GetType().FullName;
_prefs.RightProvider = _providers[0].GetType().FullName;
}
else
{
throw new ApplicationException("Could not find at least 2 status providers");
}
}
// Find the two active providers
FindActiveProviders();
// Establish the context menu
if (!_prefs.FancyMenu)
{
_notifyIcon.ContextMenu = new ContextMenu();
_notifyIcon.ContextMenu.Popup += OnContextMenuPopUp;
}
else
{
_notifyIcon.ContextMenuStrip = new ContextMenuStrip();
_notifyIcon.ContextMenuStrip.ImageScalingSize = new Size(36, 36);
_notifyIcon.ContextMenuStrip.Opening += OnContextMenuStripOpening;
}
// Set up the update timer
_timer.Tick += OnTimerTick;
_timer.Start();
}
#endregion Public Methods
#region Private Methods
void OnContextMenuStripOpening(object sender, System.ComponentModel.CancelEventArgs e)
{
_notifyIcon.ContextMenuStrip.Items.Clear();
// Fill the available providers
ToolStripMenuItem left = new ToolStripMenuItem("Left");
ToolStripMenuItem right = new ToolStripMenuItem("Right");
AddMenuItems(left, MenuTag.DisplaySide.Left, _left);
AddMenuItems(right, MenuTag.DisplaySide.Right, _right);
// Left/right sides and separator
_notifyIcon.ContextMenuStrip.Items.Add(left);
_notifyIcon.ContextMenuStrip.Items.Add(right);
_notifyIcon.ContextMenuStrip.Items.Add("-");
// Center line
ToolStripMenuItem item = new ToolStripMenuItem("Center line", null, new EventHandler(OnCenterlineToolStripItemClick));
item.Tag = _prefs.Centerline;
if (_prefs.Centerline)
{
item.Font = new Font(item.Font, FontStyle.Bold);
}
_notifyIcon.ContextMenuStrip.Items.Add(item);
_notifyIcon.ContextMenuStrip.Items.Add("-");
// About/Exit
_notifyIcon.ContextMenuStrip.Items.Add("About...", null, new EventHandler(OnAboutMenuClick));
_notifyIcon.ContextMenuStrip.Items.Add("Exit", null, new EventHandler(OnExitMenuClick));
e.Cancel = false;
}
/// <summary>
/// Handles a context menu opening by generating a new menu
/// </summary>
/// <param name="sender">Menu that sent popup</param>
/// <param name="e">Event arguments</param>
void OnContextMenuPopUp(object sender, EventArgs e)
{
ContextMenu trayMenu = _notifyIcon.ContextMenu;
trayMenu.MenuItems.Clear();
// Fill the available providers
MenuItem left = new MenuItem("Left");
MenuItem right = new MenuItem("Right");
AddMenuItems(left, MenuTag.DisplaySide.Left, _left);
AddMenuItems(right, MenuTag.DisplaySide.Right, _right);
// Left/right sides and separator
trayMenu.MenuItems.Add(left);
trayMenu.MenuItems.Add(right);
trayMenu.MenuItems.Add("-");
// Center line
MenuItem center = new MenuItem("Center line", new EventHandler(OnCenterlineMenuClick));
center.Checked = _prefs.Centerline;
trayMenu.MenuItems.Add(center);
trayMenu.MenuItems.Add("-");
// About/Exit
trayMenu.MenuItems.Add(new MenuItem("&About", new EventHandler(OnAboutMenuClick)));
trayMenu.MenuItems.Add(new MenuItem("E&xit", new EventHandler(OnExitMenuClick)));
}
/// <summary>
/// Handles a click on one of the provider menu items
/// </summary>
/// <param name="sender">Menu item that sent click</param>
/// <param name="e">Event arguments</param>
void OnProviderMenuItemClick(object sender, EventArgs e)
{
MenuItem item = sender as MenuItem;
if (item != null)
{
MenuTag tag = item.Tag as MenuTag;
HandleProviderSwitch(tag);
}
}
/// <summary>
/// Handles a click on one of the provider menu items
/// </summary>
/// <param name="sender">Menu item that sent click</param>
/// <param name="e">Event arguments</param>
void OnProviderToolStripItemClick(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
MenuTag tag = item.Tag as MenuTag;
HandleProviderSwitch(tag);
}
}
/// <summary>
/// Handles a timer tick
/// </summary>
/// <param name="sender">Timer that sent tick</param>
/// <param name="e">Event arguments</param>
void OnTimerTick(object sender, EventArgs e)
{
int seconds = DateTime.Now.Second;
float leftVal = _left.NextValue();
float rightVal = _right.NextValue();
// If the left is below the midline and not a percentage
if (leftVal < _leftMax / 5
&& _left.Type != EXT.StatusType.Percentage
&& (_leftMax / 10) > SMALLEST_MAXIMUM)
{
++_leftBelowMidline;
if (_leftBelowMidline > FALL_TIMEOUT)
{
_leftMax /= 10;
System.Diagnostics.Trace.WriteLine("Decreasing left to " + _rightMax);
_leftBelowMidline = 0;
}
}
else // Otherwise we're over the midline
{
_leftBelowMidline = 0;
// Increase graph maximum if need be. The maximum
// is increased tenfold if the value is at least
// fivefold the current maximum.
while (leftVal > _leftMax * 5)
{
_leftMax *= 10;
System.Diagnostics.Trace.WriteLine("Increasing left to " + _leftMax.ToString());
}
}
// If the right is below the midline and not a percentage
if (rightVal < _rightMax / 5
&& _right.Type != EXT.StatusType.Percentage
&& (_rightMax / 10) > SMALLEST_MAXIMUM)
{
++_rightBelowMidline;
if (_rightBelowMidline > FALL_TIMEOUT)
{
_rightMax /= 10;
System.Diagnostics.Trace.WriteLine("Decreasing right to " + _rightMax);
_rightBelowMidline = 0;
}
}
else // Otherwise we're over the midline
{
_rightBelowMidline = 0;
// Increase graph maximum if need be. The maximum
// is increased tenfold if the value is at least
// fivefold the current maximum.
while (rightVal > _rightMax * 5)
{
_rightMax *= 10;
System.Diagnostics.Trace.WriteLine("Increasing right to " + _rightMax.ToString());
}
}
GenerateTrayIcon(leftVal, rightVal);
_notifyIcon.Text = string.Format(
"{0}: {1}{2}\n{3}: {4}{5}",
_left.ShortName,
(int)leftVal,
_left.Unit,
_right.ShortName,
(int)rightVal,
_right.Unit);
}
/// <summary>
/// Handles a click on the About menu item
/// </summary>
/// <param name="sender">Menu item that sent click</param>
/// <param name="e">Event arguments</param>
void OnAboutMenuClick(object sender, EventArgs e)
{
MessageBox.Show(
"Tray System Monitor\nA small tool to help monitor system resources.\n\n" +
"Copyright (C) 2007-2015 Casey Liss\[email protected]\n\n" +
"Some icons from http://commons.wikimedia.org/wiki/Crystal_Clear",
"About Tray System Monitor",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
/// <summary>
/// Handles an exit menu item click
/// </summary>
/// <param name="sender">Menu item that sent click</param>
/// <param name="e">Event arguments</param>
void OnExitMenuClick(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Handles clicking on the centerline menu item
/// </summary>
/// <param name="sender">Menu item that sent click</param>
/// <param name="e">Event arguments</param>
void OnCenterlineMenuClick(object sender, EventArgs e)
{
MenuItem item = sender as MenuItem;
if (item != null)
{
// Note the Checked property hasn't changed yet.
_prefs.Centerline = !item.Checked;
UpdatePreferences();
}
}
/// <summary>
/// Handles clicking on the centerline menu item
/// </summary>
/// <param name="sender">Menu item that sent click</param>
/// <param name="e">Event arguments</param>
void OnCenterlineToolStripItemClick(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
// Note the Checked property hasn't changed yet.
_prefs.Centerline = !(bool)item.Tag;
UpdatePreferences();
}
}
/// <summary>
/// Adds all the providers to the given menu
/// </summary>
/// <param name="root">Root menu item</param>
/// <param name="side">Which side we're on</param>
/// <param name="current">Current status provider on this side</param>
void AddMenuItems(
MenuItem root,
MenuTag.DisplaySide side,
EXT.IStatusProvider current)
{
foreach (EXT.IStatusProvider provider in _providers)
{
MenuItem item = new MenuItem(provider.Name);
item.Tag = new MenuTag(side, provider);
item.Checked = ReferenceEquals(current, provider);
item.Enabled = !ReferenceEquals(current, provider);
item.Click += OnProviderMenuItemClick;
root.MenuItems.Add(item);
}
}
/// <summary>
/// Adds all the providers to the given menu
/// </summary>
/// <param name="root">Root menu item</param>
/// <param name="side">Which side we're on</param>
/// <param name="current">Current status provider on this side</param>
void AddMenuItems(
ToolStripMenuItem root,
MenuTag.DisplaySide side,
EXT.IStatusProvider current)
{
foreach (EXT.IStatusProvider provider in _providers)
{
ToolStripMenuItem item = new ToolStripMenuItem(provider.Name, provider.Image);
item.Tag = new MenuTag(side, provider);
item.Checked = ReferenceEquals(current, provider);
item.Enabled = !item.Checked;
item.Click += OnProviderToolStripItemClick;
root.DropDownItems.Add(item);
}
}
/// <summary>
/// Generates the tray icon based off passed values
/// </summary>
/// <param name="leftValue">Value of the left provider</param>
/// <param name="rightValue">Value of the right provider</param>
void GenerateTrayIcon(float leftValue, float rightValue)
{
Bitmap bmp = new Bitmap(_notifyIcon.Icon.Width, _notifyIcon.Icon.Height);
using (Graphics g = Graphics.FromImage(bmp))
using (SolidBrush brush = new SolidBrush(_prefs.ForeColor()))
{
RectangleF bounds = g.VisibleClipBounds;
g.Clear(_prefs.BackColor());
float leftHeight = (leftValue / _leftMax) * bounds.Height;
float rightHeight = (rightValue / _rightMax) * bounds.Height;
int centerOffset = _prefs.Centerline ? 1 : 0;
// Draw the left graph
g.FillRectangle(
brush,
0,
bounds.Height - leftHeight,
bounds.Width / 2 - centerOffset,
leftHeight);
// Draw the right graph
g.FillRectangle(
brush,
bounds.Width / 2 + 1 + centerOffset,
bounds.Height - rightHeight,
bounds.Width / 2,
rightHeight);
}
// Save off the old icon, replace it with the new one,
// and then destroy the old one.
IntPtr oldIcon = _notifyIcon.Icon.Handle;
_notifyIcon.Icon = Icon.FromHandle(bmp.GetHicon());
DestroyIcon(oldIcon);
}
/// <summary>
/// Stores the preferences object to disk.
/// </summary>
void UpdatePreferences()
{
XmlSerializer ser = new XmlSerializer(typeof(Preferences));
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(PREFS_FILE))
{
ser.Serialize(sw, _prefs);
}
}
}
/// <summary>
/// Finds the active providers based on the preferences object.
/// </summary>
void FindActiveProviders()
{
foreach (EXT.IStatusProvider provider in _providers)
{
if (provider.GetType().FullName == _prefs.LeftProvider)
{
_left = provider;
}
if (provider.GetType().FullName == _prefs.RightProvider)
{
_right = provider;
}
}
// Handle the case of a provider missing
if (_left == null)
{
_left = _providers[0];
}
if (_right == null)
{
_right = _providers[1];
}
}
/// <summary>
/// Handles a double-click of the tray icon
/// </summary>
/// <param name="sender">Object that sent doubleclick</param>
/// <param name="e">Event arguments</param>
private void OnNotifyIconDoubleClick(object sender, EventArgs e)
{
System.Diagnostics.Process taskMan = null;
try
{
taskMan = new System.Diagnostics.Process();
taskMan.StartInfo = new System.Diagnostics.ProcessStartInfo("taskmgr.exe");
taskMan.Start();
}
catch (System.ComponentModel.Win32Exception ex)
{
System.Diagnostics.Trace.WriteLine("Could not start task manager: " + ex.Message);
}
finally
{
if (taskMan == null)
{
taskMan.Dispose();
}
}
}
/// <summary>
/// Handles the switch of a provider
/// </summary>
/// <param name="tag">Information about the requested new provider</param>
void HandleProviderSwitch(MenuTag tag)
{
if (tag.Side == MenuTag.DisplaySide.Left)
{
_left = tag.Provider;
_leftMax = _left.Type == EXT.StatusType.Percentage ?
100 : 10;
_prefs.LeftProvider = _left.GetType().FullName;
}
else
{
_right = tag.Provider;
_rightMax = _right.Type == EXT.StatusType.Percentage ?
100 : 10;
_prefs.RightProvider = _right.GetType().FullName;
}
UpdatePreferences();
}
/// <summary>
/// Destroys an icon. Used to release GDI+ resources.
/// </summary>
/// <param name="hIcon">Handle to the icon to be destroyed</param>
/// <returns>Success flag</returns>
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool DestroyIcon(IntPtr hIcon);
#endregion Private Methods
#region Private Classes
/// <summary>
/// Defines a tag for a menu item
/// </summary>
private class MenuTag
{
public enum DisplaySide
{
Left = 0,
Right
}
private DisplaySide _side;
private EXT.IStatusProvider _provider;
public MenuTag(DisplaySide side, EXT.IStatusProvider provider)
{
_side = side;
_provider = provider;
}
public DisplaySide Side
{
get { return _side; }
}
public EXT.IStatusProvider Provider
{
get { return _provider; }
}
}
#endregion Private Classes
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Ntfs
{
using System;
using System.Collections.Generic;
using System.IO;
internal class File
{
protected INtfsContext _context;
private MasterFileTable _mft;
private List<FileRecord> _records;
private ObjectCache<string, Index> _indexCache;
private List<NtfsAttribute> _attributes;
private bool _dirty;
public File(INtfsContext context, FileRecord baseRecord)
{
_context = context;
_mft = _context.Mft;
_records = new List<FileRecord>();
_records.Add(baseRecord);
_indexCache = new ObjectCache<string, Index>();
_attributes = new List<NtfsAttribute>();
LoadAttributes();
}
public uint IndexInMft
{
get { return _records[0].MasterFileTableIndex; }
}
public uint MaxMftRecordSize
{
get { return _records[0].AllocatedSize; }
}
public FileRecordReference MftReference
{
get { return _records[0].Reference; }
}
public List<string> Names
{
get
{
List<string> result = new List<string>();
if (IndexInMft == MasterFileTable.RootDirIndex)
{
result.Add(string.Empty);
}
else
{
foreach (StructuredNtfsAttribute<FileNameRecord> attr in GetAttributes(AttributeType.FileName))
{
string name = attr.Content.FileName;
Directory parentDir = _context.GetDirectoryByRef(attr.Content.ParentDirectory);
if (parentDir != null)
{
foreach (string dirName in parentDir.Names)
{
result.Add(Utilities.CombinePaths(dirName, name));
}
}
}
}
return result;
}
}
public bool HasWin32OrDosName
{
get
{
foreach (StructuredNtfsAttribute<FileNameRecord> attr in GetAttributes(AttributeType.FileName))
{
FileNameRecord fnr = attr.Content;
if (fnr.FileNameNamespace != FileNameNamespace.Posix)
{
return true;
}
}
return false;
}
}
public bool MftRecordIsDirty
{
get
{
return _dirty;
}
}
public ushort HardLinkCount
{
get { return _records[0].HardLinkCount; }
set { _records[0].HardLinkCount = value; }
}
public IEnumerable<NtfsStream> AllStreams
{
get
{
foreach (var attr in _attributes)
{
yield return new NtfsStream(this, attr);
}
}
}
public DirectoryEntry DirectoryEntry
{
get
{
if (_context.GetDirectoryByRef == null)
{
return null;
}
NtfsStream stream = GetStream(AttributeType.FileName, null);
if (stream == null)
{
return null;
}
FileNameRecord record = stream.GetContent<FileNameRecord>();
// Root dir is stored without root directory flag set in FileNameRecord, simulate it.
if (_records[0].MasterFileTableIndex == MasterFileTable.RootDirIndex)
{
record.Flags |= FileAttributeFlags.Directory;
}
return new DirectoryEntry(_context.GetDirectoryByRef(record.ParentDirectory), MftReference, record);
}
}
public string BestName
{
get
{
NtfsAttribute[] attrs = GetAttributes(AttributeType.FileName);
string bestName = null;
if (attrs != null && attrs.Length != 0)
{
bestName = attrs[0].ToString();
for (int i = 1; i < attrs.Length; ++i)
{
string name = attrs[i].ToString();
if (Utilities.Is8Dot3(bestName))
{
bestName = name;
}
}
}
return bestName;
}
}
public bool IsDirectory
{
get { return (_records[0].Flags & FileRecordFlags.IsDirectory) != 0; }
}
public StandardInformation StandardInformation
{
get { return GetStream(AttributeType.StandardInformation, null).GetContent<StandardInformation>(); }
}
internal INtfsContext Context
{
get
{
return _context;
}
}
/// <summary>
/// Gets an enumeration of all the attributes.
/// </summary>
internal IEnumerable<NtfsAttribute> AllAttributes
{
get { return _attributes; }
}
public static File CreateNew(INtfsContext context, FileAttributeFlags dirFlags)
{
return CreateNew(context, FileRecordFlags.None, dirFlags);
}
public static File CreateNew(INtfsContext context, FileRecordFlags flags, FileAttributeFlags dirFlags)
{
File newFile = context.AllocateFile(flags);
FileAttributeFlags fileFlags =
FileAttributeFlags.Archive
| FileRecord.ConvertFlags(flags)
| (dirFlags & FileAttributeFlags.Compressed);
AttributeFlags dataAttrFlags = AttributeFlags.None;
if ((dirFlags & FileAttributeFlags.Compressed) != 0)
{
dataAttrFlags |= AttributeFlags.Compressed;
}
StandardInformation.InitializeNewFile(newFile, fileFlags);
if (context.ObjectIds != null)
{
Guid newId = CreateNewGuid(context);
NtfsStream stream = newFile.CreateStream(AttributeType.ObjectId, null);
ObjectId objId = new ObjectId();
objId.Id = newId;
stream.SetContent(objId);
context.ObjectIds.Add(newId, newFile.MftReference, newId, Guid.Empty, Guid.Empty);
}
newFile.CreateAttribute(AttributeType.Data, dataAttrFlags);
newFile.UpdateRecordInMft();
return newFile;
}
public int MftRecordFreeSpace(AttributeType attrType, string attrName)
{
foreach (var record in _records)
{
if (record.GetAttribute(attrType, attrName) != null)
{
return _mft.RecordSize - record.Size;
}
}
throw new IOException("Attempt to determine free space for non-existent attribute");
}
public void Modified()
{
DateTime now = DateTime.UtcNow;
NtfsStream siStream = GetStream(AttributeType.StandardInformation, null);
StandardInformation si = siStream.GetContent<StandardInformation>();
si.LastAccessTime = now;
si.ModificationTime = now;
siStream.SetContent(si);
MarkMftRecordDirty();
}
public void Accessed()
{
DateTime now = DateTime.UtcNow;
NtfsStream siStream = GetStream(AttributeType.StandardInformation, null);
StandardInformation si = siStream.GetContent<StandardInformation>();
si.LastAccessTime = now;
siStream.SetContent(si);
MarkMftRecordDirty();
}
public void MarkMftRecordDirty()
{
_dirty = true;
}
public void UpdateRecordInMft()
{
if (_dirty)
{
if (NtfsTransaction.Current != null)
{
NtfsStream stream = GetStream(AttributeType.StandardInformation, null);
StandardInformation si = stream.GetContent<StandardInformation>();
si.MftChangedTime = NtfsTransaction.Current.Timestamp;
stream.SetContent(si);
}
bool fixesApplied = true;
while (fixesApplied)
{
fixesApplied = false;
for (int i = 0; i < _records.Count; ++i)
{
var record = _records[i];
bool fixedAttribute = true;
while (record.Size > _mft.RecordSize && fixedAttribute)
{
fixedAttribute = false;
if (!fixedAttribute && !record.IsMftRecord)
{
foreach (var attr in record.Attributes)
{
if (!attr.IsNonResident && !_context.AttributeDefinitions.MustBeResident(attr.AttributeType))
{
MakeAttributeNonResident(new AttributeReference(record.Reference, attr.AttributeId), (int)attr.DataLength);
fixedAttribute = true;
break;
}
}
}
if (!fixedAttribute)
{
foreach (var attr in record.Attributes)
{
if (attr.AttributeType == AttributeType.IndexRoot
&& ShrinkIndexRoot(attr.Name))
{
fixedAttribute = true;
break;
}
}
}
if (!fixedAttribute)
{
if (record.Attributes.Count == 1)
{
fixedAttribute = SplitAttribute(record);
}
else
{
if (_records.Count == 1)
{
CreateAttributeList();
}
fixedAttribute = ExpelAttribute(record);
}
}
fixesApplied |= fixedAttribute;
}
}
}
_dirty = false;
foreach (var record in _records)
{
_mft.WriteRecord(record);
}
}
}
public Index CreateIndex(string name, AttributeType attrType, AttributeCollationRule collRule)
{
Index.Create(attrType, collRule, this, name);
return GetIndex(name);
}
public Index GetIndex(string name)
{
Index idx = _indexCache[name];
if (idx == null)
{
idx = new Index(this, name, _context.BiosParameterBlock, _context.UpperCase);
_indexCache[name] = idx;
}
return idx;
}
public void Delete()
{
if (_records[0].HardLinkCount != 0)
{
throw new InvalidOperationException("Attempt to delete in-use file: " + ToString());
}
_context.ForgetFile(this);
NtfsStream objIdStream = GetStream(AttributeType.ObjectId, null);
if (objIdStream != null)
{
ObjectId objId = objIdStream.GetContent<ObjectId>();
Context.ObjectIds.Remove(objId.Id);
}
// Truncate attributes, allowing for truncation silently removing the AttributeList attribute
// in some cases (large file with all attributes first extent in the first MFT record). This
// releases all allocated clusters in most cases.
List<NtfsAttribute> truncateAttrs = new List<NtfsAttribute>(_attributes.Count);
foreach (var attr in _attributes)
{
if (attr.Type != AttributeType.AttributeList)
{
truncateAttrs.Add(attr);
}
}
foreach (NtfsAttribute attr in truncateAttrs)
{
attr.GetDataBuffer().SetCapacity(0);
}
// If the attribute list record remains, free any possible clusters it owns. We've now freed
// all clusters.
NtfsAttribute attrList = GetAttribute(AttributeType.AttributeList, null);
if (attrList != null)
{
attrList.GetDataBuffer().SetCapacity(0);
}
// Now go through the MFT records, freeing them up
foreach (var mftRecord in _records)
{
_context.Mft.RemoveRecord(mftRecord.Reference);
}
_attributes.Clear();
_records.Clear();
}
public bool StreamExists(AttributeType attrType, string name)
{
return GetStream(attrType, name) != null;
}
public NtfsStream GetStream(AttributeType attrType, string name)
{
foreach (NtfsStream stream in GetStreams(attrType, name))
{
return stream;
}
return null;
}
public IEnumerable<NtfsStream> GetStreams(AttributeType attrType, string name)
{
foreach (var attr in _attributes)
{
if (attr.Type == attrType && attr.Name == name)
{
yield return new NtfsStream(this, attr);
}
}
}
public NtfsStream CreateStream(AttributeType attrType, string name)
{
return new NtfsStream(this, CreateAttribute(attrType, name, AttributeFlags.None));
}
public NtfsStream CreateStream(AttributeType attrType, string name, long firstCluster, ulong numClusters, uint bytesPerCluster)
{
return new NtfsStream(this, CreateAttribute(attrType, name, AttributeFlags.None, firstCluster, numClusters, bytesPerCluster));
}
public SparseStream OpenStream(AttributeType attrType, string name, FileAccess access)
{
NtfsAttribute attr = GetAttribute(attrType, name);
if (attr != null)
{
return new FileStream(this, attr, access);
}
return null;
}
public void RemoveStream(NtfsStream stream)
{
RemoveAttribute(stream.Attribute);
}
public FileNameRecord GetFileNameRecord(string name, bool freshened)
{
NtfsAttribute[] attrs = GetAttributes(AttributeType.FileName);
StructuredNtfsAttribute<FileNameRecord> attr = null;
if (String.IsNullOrEmpty(name))
{
if (attrs.Length != 0)
{
attr = (StructuredNtfsAttribute<FileNameRecord>)attrs[0];
}
}
else
{
foreach (StructuredNtfsAttribute<FileNameRecord> a in attrs)
{
if (_context.UpperCase.Compare(a.Content.FileName, name) == 0)
{
attr = a;
}
}
if (attr == null)
{
throw new FileNotFoundException("File name not found on file", name);
}
}
FileNameRecord fnr = attr == null ? new FileNameRecord() : new FileNameRecord(attr.Content);
if (freshened)
{
FreshenFileName(fnr, false);
}
return fnr;
}
public virtual void Dump(TextWriter writer, string indent)
{
writer.WriteLine(indent + "FILE (" + ToString() + ")");
writer.WriteLine(indent + " File Number: " + _records[0].MasterFileTableIndex);
_records[0].Dump(writer, indent + " ");
foreach (AttributeRecord attrRec in _records[0].Attributes)
{
NtfsAttribute.FromRecord(this, MftReference, attrRec).Dump(writer, indent + " ");
}
}
public override string ToString()
{
string bestName = BestName;
if (bestName == null)
{
return "?????";
}
else
{
return bestName;
}
}
internal void RemoveAttributeExtents(NtfsAttribute attr)
{
attr.GetDataBuffer().SetCapacity(0);
foreach (var extentRef in attr.Extents.Keys)
{
RemoveAttributeExtent(extentRef);
}
}
internal void RemoveAttributeExtent(AttributeReference extentRef)
{
FileRecord fileRec = GetFileRecord(extentRef.File);
if (fileRec != null)
{
fileRec.RemoveAttribute(extentRef.AttributeId);
// Remove empty non-primary MFT records
if (fileRec.Attributes.Count == 0 && fileRec.BaseFile.Value != 0)
{
RemoveFileRecord(extentRef.File);
}
}
}
/// <summary>
/// Gets an attribute by reference.
/// </summary>
/// <param name="attrRef">Reference to the attribute.</param>
/// <returns>The attribute.</returns>
internal NtfsAttribute GetAttribute(AttributeReference attrRef)
{
foreach (var attr in _attributes)
{
if (attr.Reference.Equals(attrRef))
{
return attr;
}
}
return null;
}
/// <summary>
/// Gets the first (if more than one) instance of a named attribute.
/// </summary>
/// <param name="type">The attribute type.</param>
/// <param name="name">The attribute's name.</param>
/// <returns>The attribute of <c>null</c>.</returns>
internal NtfsAttribute GetAttribute(AttributeType type, string name)
{
foreach (var attr in _attributes)
{
if (attr.PrimaryRecord.AttributeType == type && attr.Name == name)
{
return attr;
}
}
return null;
}
/// <summary>
/// Gets all instances of an unnamed attribute.
/// </summary>
/// <param name="type">The attribute type.</param>
/// <returns>The attributes.</returns>
internal NtfsAttribute[] GetAttributes(AttributeType type)
{
List<NtfsAttribute> matches = new List<NtfsAttribute>();
foreach (var attr in _attributes)
{
if (attr.PrimaryRecord.AttributeType == type && string.IsNullOrEmpty(attr.Name))
{
matches.Add(attr);
}
}
return matches.ToArray();
}
internal void MakeAttributeNonResident(AttributeReference attrRef, int maxData)
{
NtfsAttribute attr = GetAttribute(attrRef);
if (attr.IsNonResident)
{
throw new InvalidOperationException("Attribute is already non-resident");
}
ushort id = _records[0].CreateNonResidentAttribute(attr.Type, attr.Name, attr.Flags);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
IBuffer attrBuffer = attr.GetDataBuffer();
byte[] tempData = Utilities.ReadFully(attrBuffer, 0, (int)Math.Min(maxData, attrBuffer.Capacity));
RemoveAttributeExtents(attr);
attr.SetExtent(_records[0].Reference, newAttrRecord);
attr.GetDataBuffer().Write(0, tempData, 0, tempData.Length);
UpdateAttributeList();
}
internal void FreshenFileName(FileNameRecord fileName, bool updateMftRecord)
{
//
// Freshen the record from the definitive info in the other attributes
//
StandardInformation si = StandardInformation;
NtfsAttribute anonDataAttr = GetAttribute(AttributeType.Data, null);
fileName.CreationTime = si.CreationTime;
fileName.ModificationTime = si.ModificationTime;
fileName.MftChangedTime = si.MftChangedTime;
fileName.LastAccessTime = si.LastAccessTime;
fileName.Flags = si.FileAttributes;
if (_dirty && NtfsTransaction.Current != null)
{
fileName.MftChangedTime = NtfsTransaction.Current.Timestamp;
}
// Directories don't have directory flag set in StandardInformation, so set from MFT record
if ((_records[0].Flags & FileRecordFlags.IsDirectory) != 0)
{
fileName.Flags |= FileAttributeFlags.Directory;
}
if (anonDataAttr != null)
{
fileName.RealSize = (ulong)anonDataAttr.PrimaryRecord.DataLength;
fileName.AllocatedSize = (ulong)anonDataAttr.PrimaryRecord.AllocatedLength;
}
if (updateMftRecord)
{
foreach (NtfsStream stream in GetStreams(AttributeType.FileName, null))
{
FileNameRecord fnr = stream.GetContent<FileNameRecord>();
if (fnr.Equals(fileName))
{
fnr = new FileNameRecord(fileName);
fnr.Flags &= ~FileAttributeFlags.ReparsePoint;
stream.SetContent(fnr);
}
}
}
}
internal long GetAttributeOffset(AttributeReference attrRef)
{
long recordOffset = _mft.GetRecordOffset(attrRef.File);
FileRecord frs = GetFileRecord(attrRef.File);
return recordOffset + frs.GetAttributeOffset(attrRef.AttributeId);
}
private static Guid CreateNewGuid(INtfsContext context)
{
Random rng = context.Options.RandomNumberGenerator;
if (rng != null)
{
byte[] buffer = new byte[16];
rng.NextBytes(buffer);
return new Guid(buffer);
}
else
{
return Guid.NewGuid();
}
}
private void LoadAttributes()
{
Dictionary<long, FileRecord> extraFileRecords = new Dictionary<long, FileRecord>();
AttributeRecord attrListRec = _records[0].GetAttribute(AttributeType.AttributeList);
if (attrListRec != null)
{
NtfsAttribute lastAttr = null;
StructuredNtfsAttribute<AttributeList> attrListAttr = (StructuredNtfsAttribute<AttributeList>)NtfsAttribute.FromRecord(this, MftReference, attrListRec);
var attrList = attrListAttr.Content;
_attributes.Add(attrListAttr);
foreach (var record in attrList)
{
FileRecord attrFileRecord = _records[0];
if (record.BaseFileReference.MftIndex != _records[0].MasterFileTableIndex)
{
if (!extraFileRecords.TryGetValue(record.BaseFileReference.MftIndex, out attrFileRecord))
{
attrFileRecord = _context.Mft.GetRecord(record.BaseFileReference);
if (attrFileRecord != null)
{
extraFileRecords[attrFileRecord.MasterFileTableIndex] = attrFileRecord;
}
}
}
if (attrFileRecord != null)
{
AttributeRecord attrRec = attrFileRecord.GetAttribute(record.AttributeId);
if (attrRec != null)
{
if (record.StartVcn == 0)
{
lastAttr = NtfsAttribute.FromRecord(this, record.BaseFileReference, attrRec);
_attributes.Add(lastAttr);
}
else
{
lastAttr.AddExtent(record.BaseFileReference, attrRec);
}
}
}
}
foreach (var extraFileRecord in extraFileRecords)
{
_records.Add(extraFileRecord.Value);
}
}
else
{
foreach (var record in _records[0].Attributes)
{
_attributes.Add(NtfsAttribute.FromRecord(this, MftReference, record));
}
}
}
private bool SplitAttribute(FileRecord record)
{
if (record.Attributes.Count != 1)
{
throw new InvalidOperationException("Attempting to split attribute in MFT record containing multiple attributes");
}
return SplitAttribute(record, (NonResidentAttributeRecord)record.FirstAttribute, false);
}
private bool SplitAttribute(FileRecord record, NonResidentAttributeRecord targetAttr, bool atStart)
{
if (targetAttr.DataRuns.Count <= 1)
{
return false;
}
int splitIndex = 1;
if (!atStart)
{
List<DataRun> runs = targetAttr.DataRuns;
splitIndex = runs.Count - 1;
int saved = runs[splitIndex].Size;
while (splitIndex > 1 && record.Size - saved > record.AllocatedSize)
{
--splitIndex;
saved += runs[splitIndex].Size;
}
}
AttributeRecord newAttr = targetAttr.Split(splitIndex);
// Find a home for the new attribute record
FileRecord newAttrHome = null;
foreach (var targetRecord in _records)
{
if (!targetRecord.IsMftRecord && _mft.RecordSize - targetRecord.Size >= newAttr.Size)
{
targetRecord.AddAttribute(newAttr);
newAttrHome = targetRecord;
}
}
if (newAttrHome == null)
{
newAttrHome = _mft.AllocateRecord(_records[0].Flags & (~FileRecordFlags.InUse), record.IsMftRecord);
newAttrHome.BaseFile = record.BaseFile.IsNull ? record.Reference : record.BaseFile;
_records.Add(newAttrHome);
newAttrHome.AddAttribute(newAttr);
}
// Add the new attribute record as an extent on the attribute it split from
bool added = false;
foreach (var attr in _attributes)
{
foreach (var existingRecord in attr.Extents)
{
if (existingRecord.Key.File == record.Reference && existingRecord.Key.AttributeId == targetAttr.AttributeId)
{
attr.AddExtent(newAttrHome.Reference, newAttr);
added = true;
break;
}
}
if (added)
{
break;
}
}
UpdateAttributeList();
return true;
}
private bool ExpelAttribute(FileRecord record)
{
if (record.MasterFileTableIndex == MasterFileTable.MftIndex)
{
// Special case for MFT - can't fully expel attributes, instead split most of the data runs off.
List<AttributeRecord> attrs = record.Attributes;
for (int i = attrs.Count - 1; i >= 0; --i)
{
AttributeRecord attr = attrs[i];
if (attr.AttributeType == AttributeType.Data)
{
if (SplitAttribute(record, (NonResidentAttributeRecord)attr, true))
{
return true;
}
}
}
}
else
{
List<AttributeRecord> attrs = record.Attributes;
for (int i = attrs.Count - 1; i >= 0; --i)
{
AttributeRecord attr = attrs[i];
if (attr.AttributeType > AttributeType.AttributeList)
{
foreach (var targetRecord in _records)
{
if (_mft.RecordSize - targetRecord.Size >= attr.Size)
{
MoveAttribute(record, attr, targetRecord);
return true;
}
}
FileRecord newFileRecord = _mft.AllocateRecord(FileRecordFlags.None, record.IsMftRecord);
newFileRecord.BaseFile = record.Reference;
_records.Add(newFileRecord);
MoveAttribute(record, attr, newFileRecord);
return true;
}
}
}
return false;
}
private void MoveAttribute(FileRecord record, AttributeRecord attrRec, FileRecord targetRecord)
{
AttributeReference oldRef = new AttributeReference(record.Reference, attrRec.AttributeId);
record.RemoveAttribute(attrRec.AttributeId);
targetRecord.AddAttribute(attrRec);
AttributeReference newRef = new AttributeReference(targetRecord.Reference, attrRec.AttributeId);
foreach (var attr in _attributes)
{
attr.ReplaceExtent(oldRef, newRef, attrRec);
}
UpdateAttributeList();
}
private void CreateAttributeList()
{
ushort id = _records[0].CreateAttribute(AttributeType.AttributeList, null, false, AttributeFlags.None);
StructuredNtfsAttribute<AttributeList> newAttr = (StructuredNtfsAttribute<AttributeList>)NtfsAttribute.FromRecord(this, MftReference, _records[0].GetAttribute(id));
_attributes.Add(newAttr);
UpdateAttributeList();
}
private void UpdateAttributeList()
{
if (_records.Count > 1)
{
AttributeList attrList = new AttributeList();
foreach (var attr in _attributes)
{
if (attr.Type != AttributeType.AttributeList)
{
foreach (var extent in attr.Extents)
{
attrList.Add(AttributeListRecord.FromAttribute(extent.Value, extent.Key.File));
}
}
}
StructuredNtfsAttribute<AttributeList> alAttr;
alAttr = (StructuredNtfsAttribute<AttributeList>)GetAttribute(AttributeType.AttributeList, null);
alAttr.Content = attrList;
alAttr.Save();
}
}
/// <summary>
/// Creates a new unnamed attribute.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="flags">The flags of the new attribute.</param>
/// <returns>The new attribute.</returns>
private NtfsAttribute CreateAttribute(AttributeType type, AttributeFlags flags)
{
return CreateAttribute(type, null, flags);
}
/// <summary>
/// Creates a new attribute.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="name">The name of the new attribute.</param>
/// <param name="flags">The flags of the new attribute.</param>
/// <returns>The new attribute.</returns>
private NtfsAttribute CreateAttribute(AttributeType type, string name, AttributeFlags flags)
{
bool indexed = _context.AttributeDefinitions.IsIndexed(type);
ushort id = _records[0].CreateAttribute(type, name, indexed, flags);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
NtfsAttribute newAttr = NtfsAttribute.FromRecord(this, MftReference, newAttrRecord);
_attributes.Add(newAttr);
UpdateAttributeList();
MarkMftRecordDirty();
return newAttr;
}
/// <summary>
/// Creates a new attribute at a fixed cluster.
/// </summary>
/// <param name="type">The type of the new attribute.</param>
/// <param name="name">The name of the new attribute.</param>
/// <param name="flags">The flags of the new attribute.</param>
/// <param name="firstCluster">The first cluster to assign to the attribute.</param>
/// <param name="numClusters">The number of sequential clusters to assign to the attribute.</param>
/// <param name="bytesPerCluster">The number of bytes in each cluster.</param>
/// <returns>The new attribute.</returns>
private NtfsAttribute CreateAttribute(AttributeType type, string name, AttributeFlags flags, long firstCluster, ulong numClusters, uint bytesPerCluster)
{
bool indexed = _context.AttributeDefinitions.IsIndexed(type);
ushort id = _records[0].CreateNonResidentAttribute(type, name, flags, firstCluster, numClusters, bytesPerCluster);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
NtfsAttribute newAttr = NtfsAttribute.FromRecord(this, MftReference, newAttrRecord);
_attributes.Add(newAttr);
UpdateAttributeList();
MarkMftRecordDirty();
return newAttr;
}
private void RemoveAttribute(NtfsAttribute attr)
{
if (attr != null)
{
if (attr.PrimaryRecord.AttributeType == AttributeType.IndexRoot)
{
_indexCache.Remove(attr.PrimaryRecord.Name);
}
RemoveAttributeExtents(attr);
_attributes.Remove(attr);
UpdateAttributeList();
}
}
private bool ShrinkIndexRoot(string indexName)
{
NtfsAttribute attr = GetAttribute(AttributeType.IndexRoot, indexName);
// Nothing to win, can't make IndexRoot smaller than this
// 8 = min size of entry that points to IndexAllocation...
if (attr.Length <= IndexRoot.HeaderOffset + IndexHeader.Size + 8)
{
return false;
}
Index idx = GetIndex(indexName);
return idx.ShrinkRoot();
}
private void MakeAttributeResident(AttributeReference attrRef, int maxData)
{
NtfsAttribute attr = GetAttribute(attrRef);
if (!attr.IsNonResident)
{
throw new InvalidOperationException("Attribute is already resident");
}
ushort id = _records[0].CreateAttribute(attr.Type, attr.Name, _context.AttributeDefinitions.IsIndexed(attr.Type), attr.Flags);
AttributeRecord newAttrRecord = _records[0].GetAttribute(id);
IBuffer attrBuffer = attr.GetDataBuffer();
byte[] tempData = Utilities.ReadFully(attrBuffer, 0, (int)Math.Min(maxData, attrBuffer.Capacity));
RemoveAttributeExtents(attr);
attr.SetExtent(_records[0].Reference, newAttrRecord);
attr.GetDataBuffer().Write(0, tempData, 0, tempData.Length);
UpdateAttributeList();
}
private FileRecord GetFileRecord(FileRecordReference fileReference)
{
foreach (var record in _records)
{
if (record.MasterFileTableIndex == fileReference.MftIndex)
{
return record;
}
}
return null;
}
private void RemoveFileRecord(FileRecordReference fileReference)
{
for (int i = 0; i < _records.Count; ++i)
{
if (_records[i].MasterFileTableIndex == fileReference.MftIndex)
{
FileRecord record = _records[i];
if (record.Attributes.Count > 0)
{
throw new IOException("Attempting to remove non-empty MFT record");
}
_context.Mft.RemoveRecord(fileReference);
_records.Remove(record);
if (_records.Count == 1)
{
NtfsAttribute attrListAttr = GetAttribute(AttributeType.AttributeList, null);
if (attrListAttr != null)
{
RemoveAttribute(attrListAttr);
}
}
}
}
}
/// <summary>
/// Wrapper for Resident/Non-Resident attribute streams, that remains valid
/// despite the attribute oscillating between resident and not.
/// </summary>
private class FileStream : SparseStream
{
private File _file;
private NtfsAttribute _attr;
private SparseStream _wrapped;
public FileStream(File file, NtfsAttribute attr, FileAccess access)
{
_file = file;
_attr = attr;
_wrapped = attr.Open(access);
}
public override IEnumerable<StreamExtent> Extents
{
get
{
return _wrapped.Extents;
}
}
public override bool CanRead
{
get
{
return _wrapped.CanRead;
}
}
public override bool CanSeek
{
get
{
return _wrapped.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _wrapped.CanWrite;
}
}
public override long Length
{
get
{
return _wrapped.Length;
}
}
public override long Position
{
get
{
return _wrapped.Position;
}
set
{
_wrapped.Position = value;
}
}
public override void Close()
{
base.Close();
_wrapped.Close();
}
public override void Flush()
{
_wrapped.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _wrapped.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _wrapped.Seek(offset, origin);
}
public override void SetLength(long value)
{
ChangeAttributeResidencyByLength(value);
_wrapped.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_wrapped.Position + count > Length)
{
ChangeAttributeResidencyByLength(_wrapped.Position + count);
}
_wrapped.Write(buffer, offset, count);
}
public override void Clear(int count)
{
if (_wrapped.Position + count > Length)
{
ChangeAttributeResidencyByLength(_wrapped.Position + count);
}
_wrapped.Clear(count);
}
public override string ToString()
{
return _file.ToString() + ".attr[" + _attr.Id + "]";
}
/// <summary>
/// Change attribute residency if it gets too big (or small).
/// </summary>
/// <param name="value">The new (anticipated) length of the stream.</param>
/// <remarks>Has hysteresis - the decision is based on the input and the current
/// state, not the current state alone.</remarks>
private void ChangeAttributeResidencyByLength(long value)
{
// This is a bit of a hack - but it's really important the bitmap file remains non-resident
if (_file._records[0].MasterFileTableIndex == MasterFileTable.BitmapIndex)
{
return;
}
if (!_attr.IsNonResident && value >= _file.MaxMftRecordSize)
{
_file.MakeAttributeNonResident(_attr.Reference, (int)Math.Min(value, _wrapped.Length));
}
else if (_attr.IsNonResident && value <= _file.MaxMftRecordSize / 4)
{
// Use of 1/4 of record size here is just a heuristic - the important thing is not to end up with
// zero-length non-resident attributes
_file.MakeAttributeResident(_attr.Reference, (int)value);
}
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A head-tracked stereoscopic virtual reality camera rig.
/// </summary>
[ExecuteInEditMode]
public class OVRCameraRig : MonoBehaviour
{
/// <summary>
/// The left eye camera.
/// </summary>
public Camera leftEyeCamera { get; private set; }
/// <summary>
/// The right eye camera.
/// </summary>
public Camera rightEyeCamera { get; private set; }
/// <summary>
/// Provides a root transform for all anchors in tracking space.
/// </summary>
public Transform trackingSpace { get; private set; }
/// <summary>
/// Always coincides with the pose of the left eye.
/// </summary>
public Transform leftEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with average of the left and right eye poses.
/// </summary>
public Transform centerEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the right eye.
/// </summary>
public Transform rightEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the tracker.
/// </summary>
public Transform trackerAnchor { get; private set; }
/// <summary>
/// Occurs when the eye pose anchors have been set.
/// </summary>
public event System.Action<OVRCameraRig> UpdatedAnchors;
private bool needsCameraConfigure;
private readonly string trackingSpaceName = "TrackingSpace";
private readonly string trackerAnchorName = "TrackerAnchor";
private readonly string eyeAnchorName = "EyeAnchor";
private readonly string legacyEyeAnchorName = "Camera";
#region Unity Messages
private void Awake()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
needsCameraConfigure = true;
OVRManager.NativeTextureScaleModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.VirtualTextureScaleModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureAntiAliasingModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureDepthModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureFormatModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.MonoscopicModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.HdrModified += (prev, current) => { needsCameraConfigure = true; };
}
private void Start()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
UpdateCameras();
UpdateAnchors();
}
#if !UNITY_ANDROID || UNITY_EDITOR
private void LateUpdate()
#else
private void Update()
#endif
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
UpdateCameras();
//UpdateAnchors();
}
#endregion
private void UpdateAnchors()
{
bool monoscopic = OVRManager.instance.monoscopic;
OVRPose tracker = OVRManager.tracker.GetPose();
OVRPose hmdLeftEye = OVRManager.display.GetEyePose(OVREye.Left);
OVRPose hmdRightEye = OVRManager.display.GetEyePose(OVREye.Right);
trackerAnchor.localRotation = tracker.orientation;
centerEyeAnchor.localRotation = hmdLeftEye.orientation; // using left eye for now
leftEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : hmdLeftEye.orientation;
rightEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : hmdRightEye.orientation;
trackerAnchor.localPosition = tracker.position;
centerEyeAnchor.localPosition = 0.5f * (hmdLeftEye.position + hmdRightEye.position);
leftEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : hmdLeftEye.position;
rightEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : hmdRightEye.position;
if (UpdatedAnchors != null)
{
UpdatedAnchors(this);
}
}
private void UpdateCameras()
{
if (needsCameraConfigure)
{
leftEyeCamera = ConfigureCamera(OVREye.Left);
rightEyeCamera = ConfigureCamera(OVREye.Right);
#if !UNITY_ANDROID || UNITY_EDITOR
needsCameraConfigure = false;
#endif
}
}
public void EnsureGameObjectIntegrity()
{
if (trackingSpace == null)
trackingSpace = ConfigureRootAnchor(trackingSpaceName);
if (leftEyeAnchor == null)
leftEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Left);
if (centerEyeAnchor == null)
centerEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Center);
if (rightEyeAnchor == null)
rightEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Right);
if (trackerAnchor == null)
trackerAnchor = ConfigureTrackerAnchor(trackingSpace);
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.GetComponent<Camera>();
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>();
}
}
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.GetComponent<Camera>();
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>();
}
}
#if UNITY_ANDROID && !UNITY_EDITOR
if (leftEyeCamera != null)
{
if (leftEyeCamera.GetComponent<OVRPostRender>() == null)
{
leftEyeCamera.gameObject.AddComponent<OVRPostRender>();
}
}
if (rightEyeCamera != null)
{
if (rightEyeCamera.GetComponent<OVRPostRender>() == null)
{
rightEyeCamera.gameObject.AddComponent<OVRPostRender>();
}
}
#endif
}
private Transform ConfigureRootAnchor(string name)
{
Transform root = transform.Find(name);
if (root == null)
{
root = new GameObject(name).transform;
}
root.parent = transform;
root.localScale = Vector3.one;
root.localPosition = Vector3.zero;
root.localRotation = Quaternion.identity;
return root;
}
private Transform ConfigureEyeAnchor(Transform root, OVREye eye)
{
string name = eye.ToString() + eyeAnchorName;
Transform anchor = transform.Find(root.name + "/" + name);
if (anchor == null)
{
anchor = transform.Find(name);
}
if (anchor == null)
{
string legacyName = legacyEyeAnchorName + eye.ToString();
anchor = transform.Find(legacyName);
}
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.name = name;
anchor.parent = root;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Transform ConfigureTrackerAnchor(Transform root)
{
string name = trackerAnchorName;
Transform anchor = transform.Find(root.name + "/" + name);
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.parent = root;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Camera ConfigureCamera(OVREye eye)
{
Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor;
Camera cam = anchor.GetComponent<Camera>();
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye);
cam.fieldOfView = eyeDesc.fov.y;
cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y;
cam.rect = new Rect(0f, 0f, OVRManager.instance.virtualTextureScale, OVRManager.instance.virtualTextureScale);
cam.targetTexture = OVRManager.display.GetEyeTexture(eye);
cam.hdr = OVRManager.instance.hdr;
#if UNITY_ANDROID && !UNITY_EDITOR
// Enforce camera render order
cam.depth = (eye == OVREye.Left) ?
(int)RenderEventType.LeftEyeEndFrame :
(int)RenderEventType.RightEyeEndFrame;
// If we don't clear the color buffer with a glClear, tiling GPUs
// will be forced to do an "unresolve" and read back the color buffer information.
// The clear is free on PowerVR, and possibly Mali, but it is a performance cost
// on Adreno, and we would be better off if we had the ability to discard/invalidate
// the color buffer instead of clearing.
// NOTE: The color buffer is not being invalidated in skybox mode, forcing an additional,
// wasted color buffer read before the skybox is drawn.
bool hasSkybox = ((cam.clearFlags == CameraClearFlags.Skybox) &&
((cam.gameObject.GetComponent<Skybox>() != null) || (RenderSettings.skybox != null)));
cam.clearFlags = (hasSkybox) ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
#endif
// When rendering monoscopic, we will use the left camera render for both eyes.
if (eye == OVREye.Right)
{
cam.enabled = !OVRManager.instance.monoscopic;
}
// AA is documented to have no effect in deferred, but it causes black screens.
if (cam.actualRenderingPath == RenderingPath.DeferredLighting)
OVRManager.instance.eyeTextureAntiAliasing = 0;
return cam;
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.ProviderControls {
public partial class IIS70_Settings {
/// <summary>
/// secServiceSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label secServiceSettings;
/// <summary>
/// lblSharedIP control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSharedIP;
/// <summary>
/// ipAddress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.SelectIPAddress ipAddress;
/// <summary>
/// lblPublicSharedIP control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPublicSharedIP;
/// <summary>
/// txtPublicSharedIP control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPublicSharedIP;
/// <summary>
/// lblGroupName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblGroupName;
/// <summary>
/// txtWebGroupName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtWebGroupName;
/// <summary>
/// chkAssignIPAutomatically control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkAssignIPAutomatically;
/// <summary>
/// WDeployEnabledCheckBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButton WDeployEnabledCheckBox;
/// <summary>
/// WDeployDisabledCheckBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButton WDeployDisabledCheckBox;
/// <summary>
/// WDeployRepairSettingCheckBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox WDeployRepairSettingCheckBox;
/// <summary>
/// secAspNet control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label secAspNet;
/// <summary>
/// lblAspNet11Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAspNet11Path;
/// <summary>
/// txtAspNet11Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet11Path;
/// <summary>
/// lblAspNet20Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAspNet20Path;
/// <summary>
/// txtAspNet20Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet20Path;
/// <summary>
/// lblAspNet20x64Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAspNet20x64Path;
/// <summary>
/// txtAspNet20x64Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet20x64Path;
/// <summary>
/// txtAspNet40Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet40Path;
/// <summary>
/// txtAspNet40x64Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet40x64Path;
/// <summary>
/// secPools control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label secPools;
/// <summary>
/// lblAsp11Pool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAsp11Pool;
/// <summary>
/// txtAspNet11Pool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet11Pool;
/// <summary>
/// lblAsp20Pool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAsp20Pool;
/// <summary>
/// txtAspNet20Pool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet20Pool;
/// <summary>
/// lblAsp20IntegratedPool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAsp20IntegratedPool;
/// <summary>
/// txtAspNet20IntegratedPool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspNet20IntegratedPool;
/// <summary>
/// ClassicAspNet40Pool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox ClassicAspNet40Pool;
/// <summary>
/// IntegratedAspNet40Pool control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox IntegratedAspNet40Pool;
/// <summary>
/// AspNetBitnessMode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList AspNetBitnessMode;
/// <summary>
/// lblWebAppGallery control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblWebAppGallery;
/// <summary>
/// radioFilterAppsList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RadioButtonList radioFilterAppsList;
/// <summary>
/// FilterDialogButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button FilterDialogButton;
/// <summary>
/// chkGalleryAppsAlwaysIgnoreDependencies control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkGalleryAppsAlwaysIgnoreDependencies;
/// <summary>
/// wpiEditFeedsList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.EditFeedsList wpiEditFeedsList;
/// <summary>
/// FilterDialogPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel FilterDialogPanel;
/// <summary>
/// WebAppGalleryList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBoxList WebAppGalleryList;
/// <summary>
/// OkButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button OkButton;
/// <summary>
/// ResetButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button ResetButton;
/// <summary>
/// CancelButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button CancelButton;
/// <summary>
/// WebAppGalleryListDS control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ObjectDataSource WebAppGalleryListDS;
/// <summary>
/// FilterDialogModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender FilterDialogModal;
/// <summary>
/// secWebExtensions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label secWebExtensions;
/// <summary>
/// lblAspPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblAspPath;
/// <summary>
/// txtAspPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtAspPath;
/// <summary>
/// php4Path control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox php4Path;
/// <summary>
/// php4Mode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList php4Mode;
/// <summary>
/// lblPhpPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPhpPath;
/// <summary>
/// txtPhpPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPhpPath;
/// <summary>
/// ddlPhpMode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlPhpMode;
/// <summary>
/// litPHP5Info control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litPHP5Info;
/// <summary>
/// perlPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox perlPath;
/// <summary>
/// perlMode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList perlMode;
/// <summary>
/// txtWmSvcServiceUrl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtWmSvcServiceUrl;
/// <summary>
/// txtWmSvcServicePort control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtWmSvcServicePort;
/// <summary>
/// ddlWmSvcCredentialsMode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlWmSvcCredentialsMode;
/// <summary>
/// Label1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label Label1;
/// <summary>
/// txtWmSvcNETBIOS control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtWmSvcNETBIOS;
/// <summary>
/// secColdFusion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label secColdFusion;
/// <summary>
/// lblColdFusionPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblColdFusionPath;
/// <summary>
/// txtColdFusionPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtColdFusionPath;
/// <summary>
/// lblScriptsDirectory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblScriptsDirectory;
/// <summary>
/// txtScriptsDirectory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtScriptsDirectory;
/// <summary>
/// lblFlashRemotingDir control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFlashRemotingDir;
/// <summary>
/// txtFlashRemotingDir control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFlashRemotingDir;
/// <summary>
/// secureFoldersLabel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label secureFoldersLabel;
/// <summary>
/// lblSecureFoldersModulesAsm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSecureFoldersModulesAsm;
/// <summary>
/// txtSecureFoldersModuleAsm control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSecureFoldersModuleAsm;
/// <summary>
/// lblProtectedUsersFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblProtectedUsersFile;
/// <summary>
/// txtProtectedUsersFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtProtectedUsersFile;
/// <summary>
/// lblProtectedGroupsFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblProtectedGroupsFile;
/// <summary>
/// txtProtectedGroupsFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtProtectedGroupsFile;
/// <summary>
/// downloadApePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel downloadApePanel;
/// <summary>
/// Localize1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize Localize1;
/// <summary>
/// InstallHeliconApeLink control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton InstallHeliconApeLink;
/// <summary>
/// configureApePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel configureApePanel;
/// <summary>
/// lblHeliconApeVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblHeliconApeVersion;
/// <summary>
/// txtHeliconApeVersion control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label txtHeliconApeVersion;
/// <summary>
/// Label3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label Label3;
/// <summary>
/// lblHeliconRegistrationText control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblHeliconRegistrationText;
/// <summary>
/// Label4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label Label4;
/// <summary>
/// EditHeliconApeConfButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button EditHeliconApeConfButton;
/// <summary>
/// chkHeliconApeGlobalRegistration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkHeliconApeGlobalRegistration;
/// <summary>
/// secOther control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label secOther;
/// <summary>
/// lblSharedSslSites control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSharedSslSites;
/// <summary>
/// sharedSslSites control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.EditDomainsList sharedSslSites;
/// <summary>
/// IIS80SSLSettings control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl IIS80SSLSettings;
/// <summary>
/// lblUseSNI control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblUseSNI;
/// <summary>
/// cbUseSNI control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbUseSNI;
/// <summary>
/// lblUseCCS control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblUseCCS;
/// <summary>
/// cbUseCCS control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbUseCCS;
/// <summary>
/// lblCCSUNCPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblCCSUNCPath;
/// <summary>
/// txtCCSUNCPath control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtCCSUNCPath;
/// <summary>
/// lblCCSUNCCommonPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblCCSUNCCommonPassword;
/// <summary>
/// txtCCSCommonPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtCCSCommonPassword;
/// <summary>
/// lblADIntegration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblADIntegration;
/// <summary>
/// ActiveDirectoryIntegration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ProviderControls.Common_ActiveDirectoryIntegration ActiveDirectoryIntegration;
}
}
| |
using System;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using PrimerProForms;
using PrimerProObjects;
using GenLib;
namespace PrimerProSearch
{
/// <summary>
///
/// </summary>
public class VowelChartSearch : Search
{
//Search parameters
private bool m_Nasal;
private bool m_Long;
private bool m_Diphthong;
private bool m_Voiceless;
private string m_Title;
private Settings m_Settings;
private VowelChartTable m_Table;
//private const string kTitle = "Vowel Chart";
//Search definition tags
private const string kLong = "long";
private const string kNasal = "nasal";
private const string kVoiceless = "voiceless";
private const string kDipthong = "diphthong";
public VowelChartSearch(int number, Settings s) : base(number, SearchDefinition.kVowel)
{
m_Nasal = false;
m_Long = false;
m_Diphthong = false;
m_Voiceless = false;
m_Settings = s;
//m_Title = VowelChartSearch.kTitle;
m_Title = m_Settings.LocalizationTable.GetMessage("VowelChartSearchT");
if (m_Title == "")
m_Title = "Vowel Chart";
m_Table = new VowelChartTable();
}
public bool Nasal
{
get {return m_Nasal;}
set {m_Nasal = value;}
}
public bool Long
{
get {return m_Long;}
set {m_Long = value;}
}
public bool Voiceless
{
get { return m_Voiceless; }
set { m_Voiceless = value; }
}
public bool Diphthong
{
get { return m_Diphthong; }
set { m_Diphthong = value; }
}
public string Title
{
get {return m_Title;}
}
public VowelChartTable Table
{
get {return m_Table;}
set {m_Table = value;}
}
public bool SetupSearch()
{
bool flag = false;
string strType = "";
//FormVowelChart fpb = new FormVowelChart();
FormVowelChart form = new FormVowelChart(m_Settings.LocalizationTable);
DialogResult dr;
dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
this.Long = form.Long;
this.Nasal = form.Nasal;
this.Voiceless = form.Voiceless;
this.Diphthong = form.Diphthong;
SearchDefinition sd = new SearchDefinition(SearchDefinition.kVowel);
SearchDefinitionParm sdp;
this.SearchDefinition = sd;
if (this.Long)
{
strType += CapitalizeFirstChar(VowelChartSearch.kLong) + Constants.Space;
//strType += m_Settings.LocalizationTable.GetMessage("VowelChartSearch2") + Constants.Space;
sdp = new SearchDefinitionParm(VowelChartSearch.kLong, "");
sd.AddSearchParm(sdp);
}
if (form.Nasal)
{
strType += CapitalizeFirstChar(VowelChartSearch.kNasal) + Constants.Space;
//strType += m_Settings.LocalizationTable.GetMessage("VowelChartSearch3") + Constants.Space;
sdp = new SearchDefinitionParm(VowelChartSearch.kNasal, "");
sd.AddSearchParm(sdp);
}
if (form.Voiceless)
{
strType += CapitalizeFirstChar(VowelChartSearch.kVoiceless) + Constants.Space;
//strType += m_Settings.LocalizationTable.GetMessage("VowelChartSearch4") + Constants.Space;
sdp = new SearchDefinitionParm(VowelChartSearch.kVoiceless, "");
sd.AddSearchParm(sdp);
}
if (form.Diphthong)
{
strType += CapitalizeFirstChar(VowelChartSearch.kDipthong) + Constants.Space;
//strType += m_Settings.LocalizationTable.GetMessage("VowelChartSearch5") + Constants.Space;
sdp = new SearchDefinitionParm(VowelChartSearch.kDipthong, "");
sd.AddSearchParm(sdp);
}
this.SearchDefinition = sd;
if (strType != "")
m_Title = strType + m_Title;
flag = true;
}
return flag;
}
public bool SetupSearch(SearchDefinition sd)
{
bool flag = true;
string strTag = "";
for (int i = 0; i < sd.SearchParmsCount(); i++)
{
strTag = sd.GetSearchParmAt(i).GetTag();
m_Title = CapitalizeFirstChar(strTag) + Constants.Space + this.Title;
switch (strTag)
{
case VowelChartSearch.kLong:
this.Long = true;
break;
case VowelChartSearch.kNasal:
this.Nasal = true;
break;
case VowelChartSearch.kVoiceless:
this.Voiceless = true;
break;
case VowelChartSearch.kDipthong:
this.Diphthong = true;
break;
default:
break;
}
}
this.SearchDefinition = sd;
return flag;
}
public string BuildResults()
{
string strText = "";
string strSN = Search.TagSN + this.SearchNumber.ToString().Trim();
strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine;
strText += this.Title;
strText += Environment.NewLine + Environment.NewLine;
strText += this.SearchResults;
strText += Search.TagOpener + Search.TagForwardSlash + strSN
+ Search.TagCloser;
return strText;
}
public VowelChartSearch ExecuteVowelChart(GraphemeInventory gi)
{
this.SearchResults = "";
if (this.Diphthong)
{
DiphthongChartTable tbl = BuildDiphthongTable(gi);
if (tbl != null)
{
this.SearchResults += tbl.GetColumnHeaders();
this.SearchResults += tbl.GetRows();
}
}
else
{
VowelChartTable tbl = BuildVowelTable(gi);
if (tbl != null)
{
this.SearchResults += tbl.GetColumnHeaders();
this.SearchResults += tbl.GetRows();
}
}
return this;
}
private VowelChartTable BuildVowelTable(GraphemeInventory gi)
{
VowelChartTable tbl = null; ;
Vowel vwl = null;
bool fLong = this.Long;
bool fNasal = this.Nasal;
bool fDipthong = this.Diphthong;
bool fVoiceless = this.Voiceless;
for (int i = 0; i < gi.VowelCount(); i++)
{
vwl = gi.GetVowel(i);
if ((fLong == vwl.IsLong) &&
(fNasal == vwl.IsNasal) &&
(fDipthong == vwl.IsComplex) &&
(fVoiceless == vwl.IsVoiceless))
{
tbl = this.Table;
AddVowelToTable(gi, vwl, tbl);
}
vwl = null;
}
return tbl;
}
private void AddVowelToTable(GraphemeInventory gi, Vowel vwl, VowelChartTable tbl)
{
string strSymbol = "";
int nRow = -1;
int nCol = -1;
strSymbol = vwl.Symbol.PadLeft(gi.MaxGraphemeSize, Constants.Space);
if (vwl.IsFront && !vwl.IsRound)
nCol = tbl.GetColNumber("FU");
if (vwl.IsFront && vwl.IsRound)
nCol = tbl.GetColNumber("FR");
if (vwl.IsCentral && !vwl.IsRound)
nCol = tbl.GetColNumber("CU");
if (vwl.IsCentral && vwl.IsRound)
nCol = tbl.GetColNumber("CR");
if (vwl.IsBack && !vwl.IsRound)
nCol = tbl.GetColNumber("BU");
if (vwl.IsBack && vwl.IsRound)
nCol = tbl.GetColNumber("BR");
if (vwl.IsHigh)
{
if (vwl.IsPlusATR)
nRow = tbl.GetRowNumber("HP");
else nRow = tbl.GetRowNumber("HM");
}
if (vwl.IsMid)
{
if (vwl.IsPlusATR)
nRow = tbl.GetRowNumber("MP");
else nRow = tbl.GetRowNumber("MM");
}
if (vwl.IsLow)
{
if (vwl.IsPlusATR)
nRow = tbl.GetRowNumber("LP");
else nRow = tbl.GetRowNumber("LM");
}
if ((nRow >= 0) && (nCol >= 0))
{
tbl.UpdChartCell(strSymbol, nRow, nCol);
}
//else MessageBox.Show(strSymbol + " is not added to chart");
else
{
string strMsg = m_Settings.LocalizationTable.GetMessage("VowelChartSearch1");
if (strMsg == "")
strMsg = "is not added to chart";
MessageBox.Show(strSymbol + Constants.Space + strMsg);
}
}
private DiphthongChartTable BuildDiphthongTable(GraphemeInventory gi)
{
DiphthongChartTable tbl = new DiphthongChartTable();
Vowel vwl = null;
string strSym = "";
string strKey = "";
ArrayList alComponents = null;
string strComponent = "";
string strComponents = "";
for (int i = 0; i < gi.VowelCount(); i++)
{
vwl = gi.GetVowel(i);
strComponents = "";
if (vwl.IsComplex)
{
strSym = vwl.Symbol;
strKey = vwl.GetKey();
alComponents = vwl.ComplexComponents;
for (int j = 0; j < alComponents.Count; j++)
{
strComponent = alComponents[j].ToString().Trim();
if (!gi.IsInInventory(strComponent))
strComponent = Constants.kHCOn + strComponent + Constants.kHCOff;
strComponents += strComponent + Constants.Space.ToString();
}
tbl = tbl.AddRow(strSym, strKey, strComponents);
}
}
return tbl;
}
private string CapitalizeFirstChar(string str)
{
string strBegin = str.Substring(0, 1);
string strRest = str.Substring(1);
strBegin = strBegin.ToUpper();
str = strBegin + strRest;
return str;
}
}
}
| |
/*
* 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 sts-2011-06-15.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.SecurityToken.Model;
using Amazon.SecurityToken.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.SecurityToken
{
/// <summary>
/// Implementation for accessing SecurityTokenService
///
/// AWS Security Token Service
/// <para>
/// The AWS Security Token Service (STS) is a web service that enables you to request
/// temporary, limited-privilege credentials for AWS Identity and Access Management (IAM)
/// users or for users that you authenticate (federated users). This guide provides descriptions
/// of the STS API. For more detailed information about using this service, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html">Temporary
/// Security Credentials</a>.
/// </para>
/// <note> As an alternative to using the API, you can use one of the AWS SDKs, which
/// consist of libraries and sample code for various programming languages and platforms
/// (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create
/// programmatic access to STS. For example, the SDKs take care of cryptographically signing
/// requests, managing errors, and retrying requests automatically. For information about
/// the AWS SDKs, including how to download and install them, see the <a href="http://aws.amazon.com/tools/">Tools
/// for Amazon Web Services page</a>. </note>
/// <para>
/// For information about setting up signatures and authorization through the API, go
/// to <a href="http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html"
/// target="_blank">Signing AWS API Requests</a> in the <i>AWS General Reference</i>.
/// For general information about the Query API, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html"
/// target="_blank">Making Query Requests</a> in <i>Using IAM</i>. For information about
/// using security tokens with other AWS products, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html">AWS
/// Services That Work with IAM</a> in the <i>Using IAM</i>.
/// </para>
///
/// <para>
/// If you're new to AWS and need additional technical information about a specific AWS
/// product, you can find the product's technical documentation at <a href="http://aws.amazon.com/documentation/"
/// target="_blank">http://aws.amazon.com/documentation/</a>.
/// </para>
///
/// <para>
/// <b>Endpoints</b>
/// </para>
///
/// <para>
/// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com
/// that maps to the US East (N. Virginia) region. Additional regions are available, but
/// must first be activated in the AWS Management Console before you can use a different
/// region's endpoint. For more information about activating a region for STS see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html">Activating
/// STS in a New Region</a> in the <i>Using IAM</i>.
/// </para>
///
/// <para>
/// For information about STS endpoints, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region">Regions
/// and Endpoints</a> in the <i>AWS General Reference</i>.
/// </para>
///
/// <para>
/// <b>Recording API requests</b>
/// </para>
///
/// <para>
/// STS supports AWS CloudTrail, which is a service that records AWS calls for your AWS
/// account and delivers log files to an Amazon S3 bucket. By using information collected
/// by CloudTrail, you can determine what requests were successfully made to STS, who
/// made the request, when it was made, and so on. To learn more about CloudTrail, including
/// how to turn it on and find your log files, see the <a href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html">AWS
/// CloudTrail User Guide</a>.
/// </para>
/// </summary>
public partial class AmazonSecurityTokenServiceClient : AmazonServiceClient, IAmazonSecurityTokenService
{
#region Constructors
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonSecurityTokenServiceClient(AWSCredentials credentials)
: this(credentials, new AmazonSecurityTokenServiceConfig())
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonSecurityTokenServiceClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonSecurityTokenServiceConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Credentials and an
/// AmazonSecurityTokenServiceClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonSecurityTokenServiceClient Configuration Object</param>
public AmazonSecurityTokenServiceClient(AWSCredentials credentials, AmazonSecurityTokenServiceConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonSecurityTokenServiceConfig())
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonSecurityTokenServiceConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonSecurityTokenServiceClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonSecurityTokenServiceClient Configuration Object</param>
public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonSecurityTokenServiceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSecurityTokenServiceConfig())
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSecurityTokenServiceConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonSecurityTokenServiceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonSecurityTokenServiceClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonSecurityTokenServiceClient Configuration Object</param>
public AmazonSecurityTokenServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonSecurityTokenServiceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region AssumeRole
internal AssumeRoleResponse AssumeRole(AssumeRoleRequest request)
{
var marshaller = new AssumeRoleRequestMarshaller();
var unmarshaller = AssumeRoleResponseUnmarshaller.Instance;
return Invoke<AssumeRoleRequest,AssumeRoleResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the AssumeRole operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AssumeRole 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>
public Task<AssumeRoleResponse> AssumeRoleAsync(AssumeRoleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new AssumeRoleRequestMarshaller();
var unmarshaller = AssumeRoleResponseUnmarshaller.Instance;
return InvokeAsync<AssumeRoleRequest,AssumeRoleResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region AssumeRoleWithSAML
internal AssumeRoleWithSAMLResponse AssumeRoleWithSAML(AssumeRoleWithSAMLRequest request)
{
var marshaller = new AssumeRoleWithSAMLRequestMarshaller();
var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance;
return Invoke<AssumeRoleWithSAMLRequest,AssumeRoleWithSAMLResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the AssumeRoleWithSAML operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithSAML 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>
public Task<AssumeRoleWithSAMLResponse> AssumeRoleWithSAMLAsync(AssumeRoleWithSAMLRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new AssumeRoleWithSAMLRequestMarshaller();
var unmarshaller = AssumeRoleWithSAMLResponseUnmarshaller.Instance;
return InvokeAsync<AssumeRoleWithSAMLRequest,AssumeRoleWithSAMLResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region AssumeRoleWithWebIdentity
internal AssumeRoleWithWebIdentityResponse AssumeRoleWithWebIdentity(AssumeRoleWithWebIdentityRequest request)
{
var marshaller = new AssumeRoleWithWebIdentityRequestMarshaller();
var unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;
return Invoke<AssumeRoleWithWebIdentityRequest,AssumeRoleWithWebIdentityResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the AssumeRoleWithWebIdentity operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AssumeRoleWithWebIdentity 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>
public Task<AssumeRoleWithWebIdentityResponse> AssumeRoleWithWebIdentityAsync(AssumeRoleWithWebIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new AssumeRoleWithWebIdentityRequestMarshaller();
var unmarshaller = AssumeRoleWithWebIdentityResponseUnmarshaller.Instance;
return InvokeAsync<AssumeRoleWithWebIdentityRequest,AssumeRoleWithWebIdentityResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DecodeAuthorizationMessage
internal DecodeAuthorizationMessageResponse DecodeAuthorizationMessage(DecodeAuthorizationMessageRequest request)
{
var marshaller = new DecodeAuthorizationMessageRequestMarshaller();
var unmarshaller = DecodeAuthorizationMessageResponseUnmarshaller.Instance;
return Invoke<DecodeAuthorizationMessageRequest,DecodeAuthorizationMessageResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DecodeAuthorizationMessage operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DecodeAuthorizationMessage 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>
public Task<DecodeAuthorizationMessageResponse> DecodeAuthorizationMessageAsync(DecodeAuthorizationMessageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DecodeAuthorizationMessageRequestMarshaller();
var unmarshaller = DecodeAuthorizationMessageResponseUnmarshaller.Instance;
return InvokeAsync<DecodeAuthorizationMessageRequest,DecodeAuthorizationMessageResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetFederationToken
internal GetFederationTokenResponse GetFederationToken(GetFederationTokenRequest request)
{
var marshaller = new GetFederationTokenRequestMarshaller();
var unmarshaller = GetFederationTokenResponseUnmarshaller.Instance;
return Invoke<GetFederationTokenRequest,GetFederationTokenResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetFederationToken operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetFederationToken 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>
public Task<GetFederationTokenResponse> GetFederationTokenAsync(GetFederationTokenRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetFederationTokenRequestMarshaller();
var unmarshaller = GetFederationTokenResponseUnmarshaller.Instance;
return InvokeAsync<GetFederationTokenRequest,GetFederationTokenResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetSessionToken
internal GetSessionTokenResponse GetSessionToken()
{
return GetSessionToken(new GetSessionTokenRequest());
}
internal GetSessionTokenResponse GetSessionToken(GetSessionTokenRequest request)
{
var marshaller = new GetSessionTokenRequestMarshaller();
var unmarshaller = GetSessionTokenResponseUnmarshaller.Instance;
return Invoke<GetSessionTokenRequest,GetSessionTokenResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Returns a set of temporary credentials for an AWS account or IAM user. The credentials
/// consist of an access key ID, a secret access key, and a security token. Typically,
/// you use <code>GetSessionToken</code> if you want to use MFA to protect programmatic
/// calls to specific AWS APIs like Amazon EC2 <code>StopInstances</code>. MFA-enabled
/// IAM users would need to call <code>GetSessionToken</code> and submit an MFA code that
/// is associated with their MFA device. Using the temporary security credentials that
/// are returned from the call, IAM users can then make programmatic calls to APIs that
/// require MFA authentication. If you do not supply a correct MFA code, then the API
/// returns an access denied error.
///
///
/// <para>
/// The <code>GetSessionToken</code> action must be called by using the long-term AWS
/// security credentials of the AWS account or an IAM user. Credentials that are created
/// by IAM users are valid for the duration that you specify, between 900 seconds (15
/// minutes) and 129600 seconds (36 hours); credentials that are created by using account
/// credentials have a maximum duration of 3600 seconds (1 hour).
/// </para>
/// <note>
/// <para>
/// We recommend that you do not call <code>GetSessionToken</code> with root account credentials.
/// Instead, follow our <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users">best
/// practices</a> by creating one or more IAM users, giving them the necessary permissions,
/// and using IAM users for everyday interaction with AWS.
/// </para>
/// </note>
/// <para>
/// The permissions associated with the temporary security credentials returned by <code>GetSessionToken</code>
/// are based on the permissions associated with account or IAM user whose credentials
/// are used to call the action. If <code>GetSessionToken</code> is called using root
/// account credentials, the temporary credentials have root account permissions. Similarly,
/// if <code>GetSessionToken</code> is called using the credentials of an IAM user, the
/// temporary credentials have the same permissions as the IAM user.
/// </para>
///
/// <para>
/// For more information about using <code>GetSessionToken</code> to create temporary
/// credentials, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken">Temporary
/// Credentials for Users in Untrusted Environments</a> in the <i>Using IAM</i>.
/// </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 GetSessionToken service method, as returned by SecurityTokenService.</returns>
public Task<GetSessionTokenResponse> GetSessionTokenAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return GetSessionTokenAsync(new GetSessionTokenRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the GetSessionToken operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSessionToken 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>
public Task<GetSessionTokenResponse> GetSessionTokenAsync(GetSessionTokenRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetSessionTokenRequestMarshaller();
var unmarshaller = GetSessionTokenResponseUnmarshaller.Instance;
return InvokeAsync<GetSessionTokenRequest,GetSessionTokenResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
#region Using Directives
using System;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.RecipeFramework.Services;
using Microsoft.Practices.RecipeFramework.VisualStudio;
using Microsoft.Practices.RecipeFramework.VisualStudio.Templates;
using EnvDTE;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text.RegularExpressions;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.Win32;
using Microsoft.VisualStudio.Shell;
using Microsoft.Practices.Common.Services;
using System.Collections.Generic;
using Microsoft.Practices.RecipeFramework.VisualStudio.Library.Templates;
using System.CodeDom.Compiler;
using System.Text;
using System.Xml;
#endregion
namespace SPALM.SPSF.Library.Actions
{
/// <summary>
/// Renames a project
/// </summary>
[ServiceDependency(typeof(DTE))]
public class AnalyzeSelectedProjects : ConfigurableAction
{
private int ignored = 0;
private int solved = 0;
public override void Execute()
{
DTE service = (DTE)this.GetService(typeof(DTE));
try
{
Project selectedProject = Helpers.GetSelectedProject(service);
if (selectedProject != null)
{
Helpers.LogMessage(service, this, "*** Analyzing selected projects ***");
AnalyzeProject(service, selectedProject);
}
else
{
Helpers.LogMessage(service, this, "*** Analyzing contained projects ***");
foreach (Project project in Helpers.GetAllProjects(service))
{
AnalyzeProject(service, project);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void AnalyzeProject(DTE service, Project project)
{
Helpers.LogMessage(service, this, "*** Analyzing project '" + project.Name + "' ***");
try
{
SearchForHiddenFiles(service, project);
CheckThatTTOutputIsNotUnderSCC(service, project);
}
catch (Exception ex)
{
Helpers.LogMessage(service, this, "Error: Analyzing of project '" + project.Name + "' failed: " + ex.Message);
}
Helpers.LogMessage(service, this, "Analysis finished, " + solved.ToString() + " conflicts solved, " + ignored.ToString() + " conflicts ignored");
Helpers.LogMessage(service, this, " ");
}
private void CheckThatTTOutputIsNotUnderSCC(DTE service, Project project)
{
CheckThatTTOutputIsNotUnderSCC(service, project, project.ProjectItems);
}
private void CheckThatTTOutputIsNotUnderSCC(DTE service, Project project, ProjectItems projectItems)
{
foreach (ProjectItem childItem in projectItems)
{
if (childItem.Name.EndsWith(".tt"))
{
//ok, tt-File found, check, if the child is under source control
if (childItem.ProjectItems.Count > 0)
{
foreach (ProjectItem ttOutputItem in childItem.ProjectItems)
{
string itemname = Helpers.GetFullPathOfProjectItem(ttOutputItem); // ttOutputHelpers.GetFullPathOfProjectItem(item);
if(service.SourceControl.IsItemUnderSCC(itemname))
{
Helpers.LogMessage(service, this, "Warning: File " + itemname + " should not be under source control");
if (MessageBox.Show("Warning: File " + itemname + " should not be under source control. " + Environment.NewLine + Environment.NewLine + "Exclude file from source control?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Helpers.ExcludeItemFromSCC(service, project, ttOutputItem);
solved++;
}
else
{
ignored++;
}
}
}
}
}
CheckThatTTOutputIsNotUnderSCC(service, project, childItem.ProjectItems);
}
}
private void SearchForHiddenFiles(DTE service, Project project)
{
ProjectItem hiveItem = Helpers.GetProjectItemByName(project.ProjectItems, "SharePointRoot");
if (hiveItem == null)
{
hiveItem = Helpers.GetProjectItemByName(project.ProjectItems, "12");
if (hiveItem == null)
{
hiveItem = Helpers.GetProjectItemByName(project.ProjectItems, "14");
}
if (hiveItem == null)
{
hiveItem = Helpers.GetProjectItemByName(project.ProjectItems, "15");
}
}
if (hiveItem != null)
{
SearchHiddenFilesInFolder(service, project, hiveItem);
}
}
private void SearchHiddenFilesInFolder(DTE service, Project project, ProjectItem hiveItem)
{
Helpers.LogMessage(service, this, "Searching for hidden files in folder '" + hiveItem.Name + "'");
InternalSearchHiddenFilesInFolder(service, project, hiveItem);
}
private void InternalSearchHiddenFilesInFolder(DTE service, Project project, ProjectItem hiveItem)
{
string pathToProject = Helpers.GetFullPathOfProjectItem(project);
if (hiveItem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFolder)
{
string itemFolderPath = Helpers.GetFullPathOfProjectItem(hiveItem);
foreach (string childFile in Directory.GetFiles(itemFolderPath))
{
//check, if each file in that folder is in the project
ProjectItem foundItem = DteHelper.FindItemByPath(service.Solution, childFile);
if (foundItem == null)
{
string relativeFileName = childFile.Substring(pathToProject.Length);
Helpers.LogMessage(service, this, "Warning: File " + relativeFileName + " not found in project");
AnalyzeProjectForm form = new AnalyzeProjectForm(relativeFileName);
DialogResult result = form.ShowDialog();
if (result == DialogResult.No)
{
//deletefile
Helpers.LogMessage(service, this, "Deleted File " + relativeFileName);
File.Delete(childFile);
solved++;
}
else if (result == DialogResult.Yes)
{
//include in project
Helpers.LogMessage(service, this, "Included File " + relativeFileName + " in project");
Helpers.AddFile(hiveItem, childFile);
solved++;
}
else
{
ignored++;
}
}
}
}
foreach (ProjectItem childItem in hiveItem.ProjectItems)
{
InternalSearchHiddenFilesInFolder(service, project, childItem);
}
}
/// <summary>
/// Removes the previously added reference, if it was created
/// </summary>
public override void Undo()
{
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Licence...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using IO = System.IO;
namespace WixSharp
{
/// <summary>
/// Base class for all Wix# related types
/// </summary>
public class WixObject
{
/// <summary>
/// Collection of Attribute/Value pairs for WiX element attributes not supported directly by Wix# objects.
/// <para>You should use <c>Attributes</c> if you want to inject specific XML attributes
/// for a given WiX element.</para>
/// <para>For example <c>Hotkey</c> attribute is not supported by Wix# <see cref="T:WixSharp.Shortcut"/>
/// but if you want them to be set in the WiX source file you may achieve this be setting
/// <c>WixEntity.Attributes</c> member variable:
/// <para> <code>new Shortcut { Attributes= new { {"Hotkey", "0"} }</code> </para>
/// <remarks>
/// You can also inject attributes into WiX components "related" to the <see cref="WixEntity"/> but not directly
/// represented in the Wix# entities family. For example if you need to set a custom attribute for the WiX <c>Component</c>
/// XML element you can use corresponding <see cref="T:WixSharp.File"/> attributes. The only difference from
/// the <c>Hotkey</c> example is the composite (column separated) key name:
/// <para> <code>new File { Attributes= new { {"Component:SharedDllRefCount", "yes"} }</code> </para>
/// The code above will force the Wix# compiler to insert "SharedDllRefCount" attribute into <c>Component</c>
/// XML element, which is automatically generated for the <see cref="T:WixSharp.File"/>.
/// <para>Currently the only supported "related" attribute is <c>Component</c>.</para>
/// <para>Note the attribute key can include xml namespace prefix:
/// <code>
/// { "{dep}ProviderKey", "01234567-8901-2345-6789-012345678901" }
/// </code>
/// Though in this case the required namespace must be already added to the element/document.</para>
/// </remarks>
/// </para>
/// </summary>
public Dictionary<string, string> Attributes
{
get
{
ProcessAttributesDefinition();
return attributes;
}
set
{
attributes = value;
}
}
Dictionary<string, string> attributes = new Dictionary<string, string>();
/// <summary>
/// Optional attributes of the <c>WiX Element</c> (e.g. Secure:YesNoPath) expressed as a string KeyValue pairs (e.g. "StartOnInstall=Yes; Sequence=1").
/// <para>OptionalAttributes just redirects all access calls to the <see cref="T:WixEntity.Attributes"/> member.</para>
/// <para>You can also use <see cref="T:WixEntity.AttributesDefinition"/> to keep the code cleaner.</para>
/// <para>Note <c>name</c> can include xml namespace prefix:
/// <code>
/// AttributesDefinition = "{dep}ProviderKey=01234567-8901-2345-6789-012345678901"
/// </code>
/// Though in this case the required namespace must be already added to the element/document.</para>
/// </summary>
/// <example>
/// <code>
/// var webSite = new WebSite
/// {
/// Description = "MyWebSite",
/// Attributes = new Dictionary<string, string> { { "StartOnInstall", "Yes" }, { "Sequence", "1" } }
/// //or
/// AttributesDefinition = "StartOnInstall=Yes; Sequence=1"
/// ...
/// </code>
/// </example>
public string AttributesDefinition { get; set; }
internal string HiddenAttributesDefinition;
internal Dictionary<string, string> attributesBag = new Dictionary<string, string>();
void ProcessAttributesDefinition()
{
if (AttributesDefinition.IsNotEmpty() || HiddenAttributesDefinition.IsNotEmpty())
{
try
{
this.Attributes = (AttributesDefinition + ";" + HiddenAttributesDefinition).ToDictionary();
}
catch (Exception e)
{
throw new Exception("Invalid AttributesDefinition", e);
}
}
foreach (var item in attributesBag)
this.attributes[item.Key] = item.Value;
}
internal string GetAttributeDefinition(string name)
{
var preffix = name + "=";
return (HiddenAttributesDefinition ?? "").Trim()
.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.StartsWith(preffix))
.Select(x => x.Substring(preffix.Length))
.FirstOrDefault();
}
internal void SetAttributeDefinition(string name, string value, bool append = false)
{
var preffix = name + "=";
var allItems = (HiddenAttributesDefinition ?? "")
.Trim()
.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.ToList();
var items = allItems;
if (value.IsNotEmpty())
{
if (append)
{
//add index to the items with the same key
var similarNamedItems = allItems.Where(x => x.StartsWith(name)).ToArray();
items.Add(name + similarNamedItems.Count() + "=" + value);
}
else
{
//reset items with the same key
items.RemoveAll(x => x.StartsWith(preffix));
items.Add(name + "=" + value);
}
}
HiddenAttributesDefinition = string.Join(";", items.ToArray());
}
/// <summary>
/// <see cref="Feature"></see> the Wix object belongs to. This member is processed only for the
/// WiX objects/elements that can be associated with the features (e.g. WebSite, FirewallException, ODBCDataSource, User,
/// EnvironmentVariable, Merge, Dir, RegFile, RegValue, Shortcut, SqlDatabase, SqlScript).
/// <remarks>
/// <para>
/// Wix# makes an emphasis on the main stream scenarios when an entity (e.g. File) belongs to a single feature.
/// And this member is to serve these scenarios via constructors or initializers.
/// </para>
/// However MSI/WiX allows the same component to be included into multiple features. If it is what your deployment logic dictates
/// then you need to use <see cref="WixSharp.WixObject.Features"/>.
/// </remarks>
/// </summary>
public Feature Feature
{
set { feature = value; }
internal get { return feature; }
}
Feature feature;
/// <summary>
/// The collection of <see cref="Feature"></see>s the Wix object belongs to. This member is processed only for the
/// WiX objects/elements that can be associated with the features (e.g. WebSite, FirewallException, ODBCDataSource, User,
/// EnvironmentVariable, Merge, Dir, RegFile, RegValue, Shortcut, SqlDatabase).
/// <remarks>
/// Note, this member is convenient for scenarios where the same component is to be included into multiple features.
/// However, if the component is to be associated only with a single feature then <see cref="WixSharp.WixObject.Feature"/>
/// is a more convenient choice as it can be initialized either via constructors or object initializers.eature.
/// </remarks>
/// </summary>
public Feature[] Features = new Feature[0];
/// <summary>
/// Gets the actual list of features associated with the Wix object/element. It is a combined
/// collection of <see cref="WixSharp.WixObject.Features"/> and <see cref="WixSharp.WixObject.Feature"/>. union of the
/// </summary>
/// <value>
/// The actual features.
/// </value>
public Feature[] ActualFeatures
{
get
{
return Features.Concat(this.feature.ToItems())
.Where(x => x != null)
.Distinct()
.ToArray();
}
}
/// <summary>
/// Maps the component to features. If no features specified then the component is added to the default ("Complete") feature.
/// </summary>
/// <param name="componentId">The component identifier.</param>
/// <param name="features">The features.</param>
/// <param name="context">The context.</param>
public static void MapComponentToFeatures(string componentId, Feature[] features, ProcessingContext context)
{
var project = (Project)context.Project;
if (features.Any())
context.FeatureComponents.Map(features, componentId);
else if (context.FeatureComponents.ContainsKey(project.DefaultFeature))
context.FeatureComponents[project.DefaultFeature].Add(componentId);
else
context.FeatureComponents[project.DefaultFeature] = new List<string> { componentId };
}
}
/// <summary>
/// Alias for the <c>Dictionary<string, string> </c> type.
/// </summary>
public class Attributes : Dictionary<string, string>
{
}
/// <summary>
/// Generic <see cref="T:WixSharp.WixEntity"/> container for defining WiX <c>Package</c> element attributes.
/// <para>These attributes are the properties of the package to be placed in the Summary Information Stream. These are visible from COM through the IStream interface, and can be seen in Explorer.</para>
///<example>The following is an example of defining the <c>Package</c> attributes.
///<code>
/// var project =
/// new Project("My Product",
/// new Dir(@"%ProgramFiles%\My Company\My Product",
///
/// ...
///
/// project.Package.AttributesDefinition = @"AdminImage=Yes;
/// Comments=Release Candidate;
/// Description=Fantastic product...";
///
/// Compiler.BuildMsi(project);
/// </code>
/// </example>
/// </summary>
public class Package : WixEntity
{
}
/// <summary>
/// Base class for all Wix# types representing WiX XML elements (entities)
/// </summary>
public class WixEntity : WixObject
{
internal void MoveAttributesTo(WixEntity dest)
{
var attrs = this.Attributes;
var attrsDefinition = this.AttributesDefinition;
this.Attributes.Clear();
this.AttributesDefinition = null;
dest.Attributes = attrs;
dest.AttributesDefinition = attrsDefinition;
}
internal string GenerateComponentId(Project project, string suffix = "")
{
return this.GetExplicitComponentId() ??
project.ComponentId($"Component.{this.Id}{suffix}");
}
internal string GetExplicitComponentId()
{
var attrs = this.AttributesDefinition.ToDictionary();
if (attrs.ContainsKey("Component:Id"))
return attrs["Component:Id"];
else
return null;
}
/// <summary>
/// Gets or sets the id of the Component element that is to contain XML equivalent of the <see cref="WixEntity"/>.
/// </summary>
/// <value>
/// The component identifier.
/// </value>
public string ComponentId
{
get => GetAttributeDefinition("Component:Id");
set => SetAttributeDefinition("Component:Id", value);
}
/// <summary>
/// Gets or sets the Condition attribute of the Component element that is to contain XML equivalent of the
/// <see cref="WixEntity"/>.
/// <para>Note, some WiW elements may not be contained by Component elements (e.g. 'CloseApplication').
/// Thus attempt to set parent component Condition attribute will always fail.</para>
/// </summary>
/// <value>
/// The component condition.
/// </value>
public string ComponentCondition
{
// Component:element_Condition=base64_SU5TVEFMTF9PREJDID0gInllcyI=
get => (GetAttributeDefinition("Component:element_Condition") ?? "").Replace("base64_", "").Base64Decode();
set => SetAttributeDefinition("Component:element_Condition", "base64_" + value.Base64Encode());
}
// public string ComponentCondition;
// public Condition ComponentCondition;
internal void AddInclude(string xmlFile, string parentElement)
{
SetAttributeDefinition("WixSharpCustomAttributes:xml_include", parentElement + "|" + xmlFile, append: true);
}
/// <summary>
/// Name of the <see cref="WixEntity"/>.
/// <para>This value is used as a <c>Name</c> for the corresponding WiX XML element.</para>
/// </summary>
public string Name = "";
/// <summary>
/// Gets or sets the <c>Id</c> value of the <see cref="WixEntity"/>.
/// <para>This value is used as a <c>Id</c> for the corresponding WiX XML element.</para>
/// <para>If the <see cref="Id"/> value is not specified explicitly by the user the Wix# compiler
/// generates it automatically insuring its uniqueness.</para>
/// <remarks>
/// Note: The ID auto-generation is triggered on the first access (evaluation) and in order to make the id
/// allocation deterministic the compiler resets ID generator just before the build starts. However if you
/// accessing any auto-id before the Build*() is called you can it interferes with the ID auto generation and eventually
/// lead to the WiX ID duplications. To prevent this from happening either:
/// <para> - Avoid evaluating the auto-generated IDs values before the call to Build*()</para>
/// <para> - Set the IDs (to be evaluated) explicitly</para>
/// <para> - Prevent resetting auto-ID generator by setting WixEntity.DoNotResetIdGenerator to true";</para>
/// </remarks>
/// </summary>
/// <value>The id.</value>
public string Id
{
get
{
if (id.IsEmpty())
{
if (this is Feature)
{
// break point parking spot
}
id = Compiler.AutoGeneration.CustomIdAlgorithm?.Invoke(this) ?? IncrementalIdFor(this);
}
return id;
}
set
{
id = value;
isAutoId = false;
}
}
/// <summary>
/// Index based Id generation algorithm.
/// <para>It is the default algorithm, which generates the most human readable Id. Thus if the
/// project has two `index.html` files one will be assigned Id `index.html` and another one
/// `index.html.1`.</para>
/// <para> Limitations: If two files have the same name it is non-deterministic which one gets
/// clear Id and which one the indexed one.</para>
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns></returns>
public static string IncrementalIdFor(WixEntity entity)
{
lock (idMaps)
{
if (!idMaps.ContainsKey(entity.GetType()))
idMaps[entity.GetType()] = new Dictionary<string, int>();
var rawName = entity.Name.Expand();
if (rawName.IsEmpty())
rawName = entity.GetType().Name;
if (IO.Path.IsPathRooted(entity.Name))
rawName = IO.Path.GetFileName(entity.Name).Expand();
if (entity.GetType() != typeof(Dir) && entity.GetType().BaseType != typeof(Dir) && entity.Name.IsNotEmpty())
rawName = IO.Path.GetFileName(entity.Name).Expand();
//Maximum allowed length for a stream name is 62 characters long; In some cases more but to play it safe keep 62 limit
//
//Note: the total limit 62 needs to include in some cases MSI auto prefix (e.g. table name) ~15 chars
// our hash code (max 10 chars) and our decoration (separators). So 30 seems to be a safe call
//
int maxLength = 30;
if (rawName.Length > maxLength)
{
//some chars are illegal as star if the ID so work around this with '_' prefix
rawName = "_..." + rawName.Substring(rawName.Length - maxLength);
}
string rawNameKey = rawName.ToLower();
/*
"bin\Release\similarFiles.txt" and "bin\similarfiles.txt" will produce the following IDs
"Component.similarFiles.txt" and "Component.similariles.txt", which will be treated by Wix compiler as duplication
*/
if (!idMaps[entity.GetType()].ContainsSimilarKey(rawName)) //this Type has not been generated yet
{
idMaps[entity.GetType()][rawNameKey] = 0;
entity.id = rawName;
if (char.IsDigit(entity.id.Last()))
entity.id += "_"; // work around for https://wixsharp.codeplex.com/workitem/142
// to avoid potential collision between ids that end with digit
// and auto indexed (e.g. [rawName + "." + index])
}
else
{
//The Id has been already generated for this Type with this rawName
//so just increase the index
var index = idMaps[entity.GetType()][rawNameKey] + 1;
entity.id = rawName + "." + index;
idMaps[entity.GetType()][rawNameKey] = index;
}
//Trace.WriteLine(">>> " + GetType() + " >>> " + id);
if (rawName.IsNotEmpty() && char.IsDigit(rawName[0]))
entity.id = "_" + entity.id;
while (alreadyTakenIds.Contains(entity.id)) //last line of defense against duplication
entity.id += "_";
alreadyTakenIds.Add(entity.id);
return entity.id;
}
}
static readonly List<string> alreadyTakenIds = new List<string>();
internal bool isAutoId = true;
/// <summary>
/// Backing value of <see cref="Id"/>.
/// </summary>
protected string id;
internal string RawId { get { return id; } }
/// <summary>
/// The do not reset auto-ID generator before starting the build.
/// </summary>
static public bool DoNotResetIdGenerator = false;
static readonly Dictionary<Type, Dictionary<string, int>> idMaps = new Dictionary<Type, Dictionary<string, int>>();
/// <summary>
/// Resets the <see cref="Id"/> generator. This method is exercised by the Wix# compiler before any
/// <c>Build</c> operations to ensure reproducibility of the <see cref="Id"/> set between <c>Build()</c>
/// calls.
/// </summary>
static public void ResetIdGenerator()
{
idMaps.Clear();
alreadyTakenIds.Clear();
}
static internal void ResetIdGenerator(bool supressWarning)
{
if (!DoNotResetIdGenerator)
{
// ServiceInstaller and SvcEvent are the only types that are expected to be allocated before
// the BuildMsi calls. This is because they are triggered on setting `ServiceInstaller.StartOn`
// and other similar service actions.
bool anyAlreadyAllocatedIds = idMaps.Keys.Any(x => x != typeof(ServiceInstaller) && x != typeof(SvcEvent));
if (anyAlreadyAllocatedIds && !supressWarning)
{
var message = "----------------------------\n" +
"Warning: Wix# compiler detected that some IDs has been auto-generated before the build started. " +
"This can lead to the WiX ID duplications on consecutive 'Build*' calls.\n" +
"To prevent this from happening either:\n" +
" - Avoid evaluating the auto-generated IDs values before the call to Build*\n" +
" - Set the IDs (to be evaluated) explicitly\n" +
" - Prevent resetting auto-ID generator by setting WixEntity.DoNotResetIdGenerator to true\n" +
"----------------------------";
Compiler.OutputWriteLine(message);
}
ResetIdGenerator();
}
}
internal bool IsIdSet()
{
return !id.IsEmpty();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BindingSourceRefresh.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechinism for catching data</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using Gizmox.WebGUI.Forms;
// code from Bill McCarthy
// http://msmvps.com/bill/archive/2005/10/05/69012.aspx
// used with permission
namespace CslaContrib.WebGUI
{
/// <summary>
/// BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechinism for catching data
/// binding errors that occur in Host.
/// </summary>
/// <remarks>WebGUI extender control that resolves the
/// data refresh issue with data bound detail controls
/// as discussed in Chapter 5.</remarks>
[DesignerCategory("")]
[ProvideProperty("ReadValuesOnChange", typeof(BindingSource))]
public class BindingSourceRefresh : System.ComponentModel.Component, IExtenderProvider, ISupportInitialize
{
#region Fields
private readonly Dictionary<BindingSource, bool> _sources = new Dictionary<BindingSource, bool>();
#endregion
#region Events
/// <summary>
/// BindingError event is raised when a data binding error occurs due to a exception.
/// </summary>
public event BindingErrorEventHandler BindingError = null;
#endregion
#region Constructors
/// <summary>
/// Constructor creates a new BindingSourceRefresh component then initialises all the different sub components.
/// </summary>
public BindingSourceRefresh()
{
InitializeComponent();
}
/// <summary>
/// Constructor creates a new BindingSourceRefresh component, adds the component to the container supplied before initialising all the different sub components.
/// </summary>
/// <param name="container">The container the component is to be added to.</param>
public BindingSourceRefresh(IContainer container)
{
container.Add(this);
InitializeComponent();
}
#endregion
#region Designer Functionality
/// <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 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()
{
components = new System.ComponentModel.Container();
}
#endregion
#endregion
#region Public Methods
/// <summary>
/// CanExtend() returns true if extendee is a binding source.
/// </summary>
/// <param name="extendee">The control to be extended.</param>
/// <returns>True if the control is a binding source, else false.</returns>
public bool CanExtend(object extendee)
{
return (extendee is BindingSource);
}
/// <summary>
/// GetReadValuesOnChange() gets the value of the custom ReadValuesOnChange extender property added to extended controls.
/// property added to extended controls.
/// </summary>
/// <param name="source">Control being extended.</param>
[Category("Csla")]
public bool GetReadValuesOnChange(BindingSource source)
{
bool result;
if (_sources.TryGetValue(source, out result))
return result;
else
return false;
}
/// <summary>
/// SetReadValuesOnChange() sets the value of the custom ReadValuesOnChange extender
/// property added to extended controls.
/// </summary>
/// <param name="source">Control being extended.</param>
/// <param name="value">New value of property.</param>
/// <remarks></remarks>
[Category("Csla")]
public void SetReadValuesOnChange(
BindingSource source, bool value)
{
_sources[source] = value;
if (!_isInitialising)
{
RegisterControlEvents(source, value);
}
}
#endregion
#region Properties
/// <summary>
/// Not in use - kept for backward compatibility
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
public ContainerControl Host {get; set;}
/// <summary>
/// Forces the binding to re-read after an exception is thrown when changing the binding value
/// </summary>
[Browsable(true)]
[DefaultValue(false)]
public bool RefreshOnException { get; set; }
#endregion
#region Private Methods
/// <summary>
/// RegisterControlEvents() registers all the relevant events for the container control supplied and also to all child controls
/// in the oontainer control.
/// </summary>
/// <param name="container">The control (including child controls) to have the refresh events registered.</param>
/// <param name="register">True to register the events, false to unregister them.</param>
private void RegisterControlEvents(ICurrencyManagerProvider container, bool register)
{
var currencyManager = container.CurrencyManager;
// If we are to register the events the do so.
if (register)
{
currencyManager.Bindings.CollectionChanged += Bindings_CollectionChanged;
currencyManager.Bindings.CollectionChanging += Bindings_CollectionChanging;
}
// Else unregister them.
else
{
currencyManager.Bindings.CollectionChanged -= Bindings_CollectionChanged;
currencyManager.Bindings.CollectionChanging += Bindings_CollectionChanging;
}
// Reigster the binding complete events for the currencymanagers bindings.
RegisterBindingEvents(currencyManager.Bindings, register);
}
/// <summary>
/// Registers the control events.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="register">if set to <c>true</c> [register].</param>
private void RegisterBindingEvents(BindingsCollection source, bool register)
{
foreach (Binding binding in source)
{
RegisterBindingEvent(binding, register);
}
}
/// <summary>
/// Registers the binding event.
/// </summary>
/// <param name="register">if set to <c>true</c> [register].</param>
/// <param name="binding">The binding.</param>
private void RegisterBindingEvent(Binding binding, bool register)
{
if (register)
{
binding.BindingComplete += Control_BindingComplete;
}
else
{
binding.BindingComplete -= Control_BindingComplete;
}
}
#endregion
#region Event Methods
/// <summary>
/// Handles the CollectionChanging event of the Bindings control.
///
/// Remove event hooks for element or entire list depending on CollectionChangeAction.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param>
private void Bindings_CollectionChanging(object sender, CollectionChangeEventArgs e)
{
switch (e.Action)
{
case CollectionChangeAction.Refresh:
// remove events for entire list
RegisterBindingEvents((BindingsCollection)sender, false);
break;
case CollectionChangeAction.Add:
// adding new element - remove events for element
RegisterBindingEvent((Binding)e.Element, false);
break;
case CollectionChangeAction.Remove:
// removing element - remove events for element
RegisterBindingEvent((Binding)e.Element, false);
break;
}
}
/// <summary>
/// Handles the CollectionChanged event of the Bindings control.
///
/// Add event hooks for element or entire list depending on CollectionChangeAction.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param>
private void Bindings_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
switch (e.Action)
{
case CollectionChangeAction.Refresh:
// refresh entire list - add event to all items
RegisterBindingEvents((BindingsCollection)sender, true);
break;
case CollectionChangeAction.Add:
// new element added - add event to element
RegisterBindingEvent((Binding)e.Element, true);
break;
case CollectionChangeAction.Remove:
// element has been removed - do nothing
break;
}
}
/// <summary>
/// Control_BindingComplete() is a event driven routine triggered when one of the control's bindings has been completed.
/// Control_BindingComplete() simply validates the result where if the result was a exception then the BindingError
/// event is raised, else if the binding was a successful data source update and we are to re-read the value on changed then
/// the binding value is reread into the control.
/// </summary>
/// <param name="sender">The object that triggered the event.</param>
/// <param name="e">The event arguments.</param>
private void Control_BindingComplete(object sender, BindingCompleteEventArgs e)
{
switch (e.BindingCompleteState)
{
case BindingCompleteState.Exception:
if ((RefreshOnException)
&& e.Binding.DataSource is BindingSource
&& GetReadValuesOnChange((BindingSource)e.Binding.DataSource))
{
e.Binding.ReadValue();
}
if (BindingError != null)
{
BindingError(this, new BindingErrorEventArgs(e.Binding, e.Exception));
}
break;
default:
if ((e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate)
&& e.Binding.DataSource is BindingSource
&& GetReadValuesOnChange((BindingSource)e.Binding.DataSource))
{
e.Binding.ReadValue();
}
break;
}
}
#endregion
#region ISupportInitialize Interface
private bool _isInitialising = false;
/// <summary>
/// BeginInit() is called when the component is starting to be initialised. BeginInit() simply sets the initialisation flag to true.
/// </summary>
void ISupportInitialize.BeginInit()
{
_isInitialising = true;
}
/// <summary>
/// EndInit() is called when the component has finished being initialised. EndInt() sets the initialise flag to false then runs
/// through registering all the different events that the component needs to hook into in Host.
/// </summary>
void ISupportInitialize.EndInit()
{
_isInitialising = false;
foreach (var source in _sources)
{
if (source.Value)
RegisterControlEvents(source.Key, true);
}
}
#endregion
}
#region Delegates
/// <summary>
/// BindingErrorEventHandler delegates is the event handling definition for handling data binding errors that occurred due to exceptions.
/// </summary>
/// <param name="sender">The object that triggered the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void BindingErrorEventHandler(object sender, BindingErrorEventArgs e);
#endregion
#region BindingErrorEventArgs Class
/// <summary>
/// BindingErrorEventArgs defines the event arguments for reporting a data binding error due to a exception.
/// </summary>
public class BindingErrorEventArgs : EventArgs
{
#region Property Fields
private Exception _exception = null;
private Binding _binding = null;
#endregion
#region Properties
/// <summary>
/// Exception gets the exception that caused the binding error.
/// </summary>
public Exception Exception
{
get { return (_exception); }
}
/// <summary>
/// Binding gets the binding that caused the exception.
/// </summary>
public Binding Binding
{
get { return (_binding); }
}
#endregion
#region Constructors
/// <summary>
/// Constructor creates a new BindingErrorEventArgs object instance using the information specified.
/// </summary>
/// <param name="binding">The binding that caused th exception.</param>
/// <param name="exception">The exception that caused the error.</param>
public BindingErrorEventArgs(Binding binding, Exception exception)
{
_binding = binding;
_exception = exception;
}
#endregion
}
#endregion
}
| |
/******************************************************************************
* 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.LdapSchema.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.Collections;
using Novell.Directory.Ldap.Utilclass;
namespace Novell.Directory.Ldap
{
/// <summary>
/// Represents a schema entry that controls one or more entries held by a
/// Directory Server.
/// <code>LdapSchema</code> Contains methods to parse schema attributes into
/// individual schema definitions, represented by subclasses of
/// {@link LdapSchemaElement}. Schema may be retrieved from a Directory server
/// with the fetchSchema method of LdapConnection or by creating an LdapEntry
/// containing schema attributes. The following sample code demonstrates how to
/// retrieve schema elements from LdapSchema
/// <pre>
/// <code>
/// .
/// .
/// .
/// LdapSchema schema;
/// LdapSchemaElement element;
///
/// // connect to the server
/// lc.connect( ldapHost, ldapPort );
/// lc.bind( ldapVersion, loginDN, password );
///
/// // read the schema from the directory
/// schema = lc.fetchSchema( lc.getSchemaDN() );
///
/// // retrieve the definition of common name
/// element = schema.getAttributeSchema( "cn" );
/// System.out.println("The attribute cn has an oid of " + element.getID());
/// .
/// .
/// .
/// </code>
/// </pre>
/// </summary>
/// <seealso cref="LdapSchemaElement">
/// </seealso>
/// <seealso cref="LdapConnection.FetchSchema">
/// </seealso>
/// <seealso cref="LdapConnection.GetSchemaDN">
/// </seealso>
public class LdapSchema : LdapEntry
{
private void InitBlock()
{
nameTable = new Hashtable[8];
idTable = new Hashtable[8];
}
/// <summary>
/// Returns an enumeration of attribute definitions.
/// </summary>
/// <returns>
/// An enumeration of attribute definitions.
/// </returns>
public virtual IEnumerator AttributeSchemas
{
get { return new EnumeratedIterator(idTable[ATTRIBUTE].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of DIT content rule definitions.
/// </summary>
/// <returns>
/// An enumeration of DIT content rule definitions.
/// </returns>
public virtual IEnumerator DITContentRuleSchemas
{
get { return new EnumeratedIterator(idTable[DITCONTENT].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of DIT structure rule definitions.
/// </summary>
/// <returns>
/// An enumeration of DIT structure rule definitions.
/// </returns>
public virtual IEnumerator DITStructureRuleSchemas
{
get { return new EnumeratedIterator(idTable[DITSTRUCTURE].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of matching rule definitions.
/// </summary>
/// <returns>
/// An enumeration of matching rule definitions.
/// </returns>
public virtual IEnumerator MatchingRuleSchemas
{
get { return new EnumeratedIterator(idTable[MATCHING].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of matching rule use definitions.
/// </summary>
/// <returns>
/// An enumeration of matching rule use definitions.
/// </returns>
public virtual IEnumerator MatchingRuleUseSchemas
{
get { return new EnumeratedIterator(idTable[MATCHING_USE].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of name form definitions.
/// </summary>
/// <returns>
/// An enumeration of name form definitions.
/// </returns>
public virtual IEnumerator NameFormSchemas
{
get { return new EnumeratedIterator(idTable[NAME_FORM].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of object class definitions.
/// </summary>
/// <returns>
/// An enumeration of object class definitions.
/// </returns>
public virtual IEnumerator ObjectClassSchemas
{
get { return new EnumeratedIterator(idTable[OBJECT_CLASS].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of syntax definitions.
/// </summary>
/// <returns>
/// An enumeration of syntax definitions.
/// </returns>
public virtual IEnumerator SyntaxSchemas
{
get { return new EnumeratedIterator(idTable[SYNTAX].Values.GetEnumerator()); }
}
/// <summary>
/// Returns an enumeration of attribute names.
/// </summary>
/// <returns>
/// An enumeration of attribute names.
/// </returns>
public virtual IEnumerator AttributeNames
{
get
{
return new EnumeratedIterator(new SupportClass.SetSupport(nameTable[ATTRIBUTE].Keys).GetEnumerator());
}
}
/// <summary>
/// Returns an enumeration of DIT content rule names.
/// </summary>
/// <returns>
/// An enumeration of DIT content rule names.
/// </returns>
public virtual IEnumerator DITContentRuleNames
{
get
{
return new EnumeratedIterator(new SupportClass.SetSupport(nameTable[DITCONTENT].Keys).GetEnumerator());
}
}
/// <summary>
/// Returns an enumeration of DIT structure rule names.
/// </summary>
/// <returns>
/// An enumeration of DIT structure rule names.
/// </returns>
public virtual IEnumerator DITStructureRuleNames
{
get
{
return new EnumeratedIterator(new SupportClass.SetSupport(nameTable[DITSTRUCTURE].Keys).GetEnumerator());
}
}
/// <summary>
/// Returns an enumeration of matching rule names.
/// </summary>
/// <returns>
/// An enumeration of matching rule names.
/// </returns>
public virtual IEnumerator MatchingRuleNames
{
get
{
return new EnumeratedIterator(new SupportClass.SetSupport(nameTable[MATCHING].Keys).GetEnumerator());
}
}
/// <summary>
/// Returns an enumeration of matching rule use names.
/// </summary>
/// <returns>
/// An enumeration of matching rule use names.
/// </returns>
public virtual IEnumerator MatchingRuleUseNames
{
get
{
return new EnumeratedIterator(new SupportClass.SetSupport(nameTable[MATCHING_USE].Keys).GetEnumerator());
}
}
/// <summary>
/// Returns an enumeration of name form names.
/// </summary>
/// <returns>
/// An enumeration of name form names.
/// </returns>
public virtual IEnumerator NameFormNames
{
get
{
return new EnumeratedIterator(new SupportClass.SetSupport(nameTable[NAME_FORM].Keys).GetEnumerator());
}
}
/// <summary>
/// Returns an enumeration of object class names.
/// </summary>
/// <returns>
/// An enumeration of object class names.
/// </returns>
public virtual IEnumerator ObjectClassNames
{
get
{
return new EnumeratedIterator(new SupportClass.SetSupport(nameTable[OBJECT_CLASS].Keys).GetEnumerator());
}
}
/// <summary>
/// The idTable hash on the oid (or integer ID for DITStructureRule) and
/// is used for retrieving enumerations
/// </summary>
private Hashtable[] idTable;
/// <summary>
/// The nameTable will hash on the names (if available). To insure
/// case-insensibility, the Keys for this table will be a String cast to
/// Uppercase.
/// </summary>
private Hashtable[] nameTable;
/*package*/
/// <summary>
/// The following lists the Ldap names of subschema attributes for
/// schema elements (definitions):
/// </summary>
internal static readonly string[] schemaTypeNames =
{
"attributeTypes", "objectClasses", "ldapSyntaxes",
"nameForms", "dITContentRules", "dITStructureRules", "matchingRules", "matchingRuleUse"
};
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int ATTRIBUTE = 0;
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int OBJECT_CLASS = 1;
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int SYNTAX = 2;
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int NAME_FORM = 3;
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int DITCONTENT = 4;
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int DITSTRUCTURE = 5;
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int MATCHING = 6;
/// <summary>An index into the the arrays schemaTypeNames, idTable, and nameTable </summary>
/*package*/
internal const int MATCHING_USE = 7;
/// <summary>
/// Constructs an LdapSchema object from attributes of an LdapEntry.
/// The object is empty if the entry parameter contains no schema
/// attributes. The recognized schema attributes are the following:
/// <pre>
/// <code>
/// "attributeTypes", "objectClasses", "ldapSyntaxes",
/// "nameForms", "dITContentRules", "dITStructureRules",
/// "matchingRules","matchingRuleUse"
/// </code>
/// </pre>
/// </summary>
/// <param name="ent">
/// An LdapEntry containing schema information.
/// </param>
public LdapSchema(LdapEntry ent) : base(ent.DN, ent.getAttributeSet())
{
InitBlock();
//reset all definitions
for (var i = 0; i < schemaTypeNames.Length; i++)
{
idTable[i] = new Hashtable();
nameTable[i] = new Hashtable();
}
var itr = getAttributeSet().GetEnumerator();
while (itr.MoveNext())
{
var attr = (LdapAttribute) itr.Current;
string value_Renamed, attrName = attr.Name;
var enumString = attr.StringValues;
if (attrName.ToUpper().Equals(schemaTypeNames[OBJECT_CLASS].ToUpper()))
{
LdapObjectClassSchema classSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
try
{
classSchema = new LdapObjectClassSchema(value_Renamed);
}
catch (Exception e)
{
Logger.Log.LogWarning("Exception swallowed", e);
continue; //Error parsing: do not add this definition
}
addElement(OBJECT_CLASS, classSchema);
}
}
else if (attrName.ToUpper().Equals(schemaTypeNames[ATTRIBUTE].ToUpper()))
{
LdapAttributeSchema attrSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
try
{
attrSchema = new LdapAttributeSchema(value_Renamed);
}
catch (Exception e)
{
Logger.Log.LogWarning("Exception swallowed", e);
continue; //Error parsing: do not add this definition
}
addElement(ATTRIBUTE, attrSchema);
}
}
else if (attrName.ToUpper().Equals(schemaTypeNames[SYNTAX].ToUpper()))
{
LdapSyntaxSchema syntaxSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
syntaxSchema = new LdapSyntaxSchema(value_Renamed);
addElement(SYNTAX, syntaxSchema);
}
}
else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING].ToUpper()))
{
LdapMatchingRuleSchema matchingRuleSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
matchingRuleSchema = new LdapMatchingRuleSchema(value_Renamed, null);
addElement(MATCHING, matchingRuleSchema);
}
}
else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING_USE].ToUpper()))
{
LdapMatchingRuleUseSchema matchingRuleUseSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
matchingRuleUseSchema = new LdapMatchingRuleUseSchema(value_Renamed);
addElement(MATCHING_USE, matchingRuleUseSchema);
}
}
else if (attrName.ToUpper().Equals(schemaTypeNames[DITCONTENT].ToUpper()))
{
LdapDITContentRuleSchema dITContentRuleSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
dITContentRuleSchema = new LdapDITContentRuleSchema(value_Renamed);
addElement(DITCONTENT, dITContentRuleSchema);
}
}
else if (attrName.ToUpper().Equals(schemaTypeNames[DITSTRUCTURE].ToUpper()))
{
LdapDITStructureRuleSchema dITStructureRuleSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
dITStructureRuleSchema = new LdapDITStructureRuleSchema(value_Renamed);
addElement(DITSTRUCTURE, dITStructureRuleSchema);
}
}
else if (attrName.ToUpper().Equals(schemaTypeNames[NAME_FORM].ToUpper()))
{
LdapNameFormSchema nameFormSchema;
while (enumString.MoveNext())
{
value_Renamed = (string) enumString.Current;
nameFormSchema = new LdapNameFormSchema(value_Renamed);
addElement(NAME_FORM, nameFormSchema);
}
}
//All non schema attributes are ignored.
}
}
/// <summary>
/// Adds the schema definition to the idList and nameList HashMaps.
/// This method is used by the methods fetchSchema and add.
/// Note that the nameTable has all keys cast to Upper-case. This is so we
/// can have a case-insensitive HashMap. The getXXX (String key) methods
/// will also cast to uppercase.
/// </summary>
/// <param name="schemaType">
/// Type of schema definition, use one of the final
/// integers defined at the top of this class:
/// ATTRIBUTE, OBJECT_CLASS, SYNTAX, NAME_FORM,
/// DITCONTENT, DITSTRUCTURE, MATCHING, MATCHING_USE
/// </param>
/// <param name="element">
/// Schema element definition.
/// </param>
private void addElement(int schemaType, LdapSchemaElement element)
{
SupportClass.PutElement(idTable[schemaType], element.ID, element);
var names = element.Names;
for (var i = 0; i < names.Length; i++)
{
SupportClass.PutElement(nameTable[schemaType], names[i].ToUpper(), element);
}
}
// #######################################################################
// The following methods retrieve a SchemaElement given a Key name:
// #######################################################################
/// <summary>
/// This function abstracts retrieving LdapSchemaElements from the local
/// copy of schema in this LdapSchema class. This is used by
/// <code>getXXX(String name)</code> functions.
/// Note that the nameTable has all keys cast to Upper-case. This is so
/// we can have a case-insensitive HashMap. The getXXX (String key)
/// methods will also cast to uppercase.
/// The first character of a NAME string can only be an alpha character
/// (see section 4.1 of rfc2252) Thus if the first character is a digit we
/// can conclude it is an OID. Note that this digit is ASCII only.
/// </summary>
/// <param name="schemaType">
/// Specifies which list is to be used in schema
/// lookup.
/// </param>
/// <param name="key">
/// The key can be either an OID or a name string.
/// </param>
private LdapSchemaElement getSchemaElement(int schemaType, string key)
{
if ((object) key == null || key.ToUpper().Equals("".ToUpper()))
return null;
var c = key[0];
if (c >= '0' && c <= '9')
{
//oid lookup
return (LdapSchemaElement) idTable[schemaType][key];
}
//name lookup
return (LdapSchemaElement) nameTable[schemaType][key.ToUpper()];
}
/// <summary>
/// Returns a particular attribute definition, or null if not found.
/// </summary>
/// <param name="name">
/// Name or OID of the attribute for which a definition is
/// to be returned.
/// </param>
/// <returns>
/// The attribute definition, or null if not found.
/// </returns>
public virtual LdapAttributeSchema getAttributeSchema(string name)
{
return (LdapAttributeSchema) getSchemaElement(ATTRIBUTE, name);
}
/// <summary>
/// Returns a particular DIT content rule definition, or null if not found.
/// </summary>
/// <param name="name">
/// The name of the DIT content rule use for which a
/// definition is to be returned.
/// </param>
/// <returns>
/// The DIT content rule definition, or null if not found.
/// </returns>
public virtual LdapDITContentRuleSchema getDITContentRuleSchema(string name)
{
return (LdapDITContentRuleSchema) getSchemaElement(DITCONTENT, name);
}
/// <summary>
/// Returns a particular DIT structure rule definition, or null if not found.
/// </summary>
/// <param name="name">
/// The name of the DIT structure rule use for which a
/// definition is to be returned.
/// </param>
/// <returns>
/// The DIT structure rule definition, or null if not found.
/// </returns>
public virtual LdapDITStructureRuleSchema getDITStructureRuleSchema(string name)
{
return (LdapDITStructureRuleSchema) getSchemaElement(DITSTRUCTURE, name);
}
/// <summary>
/// Returns a particular DIT structure rule definition, or null if not found.
/// </summary>
/// <param name="ID">
/// The ID of the DIT structure rule use for which a
/// definition is to be returned.
/// </param>
/// <returns>
/// The DIT structure rule definition, or null if not found.
/// </returns>
public virtual LdapDITStructureRuleSchema getDITStructureRuleSchema(int ID)
{
var IDKey = ID;
return (LdapDITStructureRuleSchema) idTable[DITSTRUCTURE][IDKey];
}
/// <summary>
/// Returns a particular matching rule definition, or null if not found.
/// </summary>
/// <param name="name">
/// The name of the matching rule for which a definition
/// is to be returned.
/// </param>
/// <returns>
/// The matching rule definition, or null if not found.
/// </returns>
public virtual LdapMatchingRuleSchema getMatchingRuleSchema(string name)
{
return (LdapMatchingRuleSchema) getSchemaElement(MATCHING, name);
}
/// <summary>
/// Returns a particular matching rule use definition, or null if not found.
/// </summary>
/// <param name="name">
/// The name of the matching rule use for which a definition
/// is to be returned.
/// </param>
/// <returns>
/// The matching rule use definition, or null if not found.
/// </returns>
public virtual LdapMatchingRuleUseSchema getMatchingRuleUseSchema(string name)
{
return (LdapMatchingRuleUseSchema) getSchemaElement(MATCHING_USE, name);
}
/// <summary>
/// Returns a particular name form definition, or null if not found.
/// </summary>
/// <param name="name">
/// The name of the name form for which a definition
/// is to be returned.
/// </param>
/// <returns>
/// The name form definition, or null if not found.
/// </returns>
public virtual LdapNameFormSchema getNameFormSchema(string name)
{
return (LdapNameFormSchema) getSchemaElement(NAME_FORM, name);
}
/// <summary>
/// Returns a particular object class definition, or null if not found.
/// </summary>
/// <param name="name">
/// The name or OID of the object class for which a
/// definition is to be returned.
/// </param>
/// <returns>
/// The object class definition, or null if not found.
/// </returns>
public virtual LdapObjectClassSchema getObjectClassSchema(string name)
{
return (LdapObjectClassSchema) getSchemaElement(OBJECT_CLASS, name);
}
/// <summary>
/// Returns a particular syntax definition, or null if not found.
/// </summary>
/// <param name="oid">
/// The oid of the syntax for which a definition
/// is to be returned.
/// </param>
/// <returns>
/// The syntax definition, or null if not found.
/// </returns>
public virtual LdapSyntaxSchema getSyntaxSchema(string oid)
{
return (LdapSyntaxSchema) getSchemaElement(SYNTAX, oid);
}
// ########################################################################
// The following methods return an Enumeration of SchemaElements by schema type
// ########################################################################
// #######################################################################
// The following methods retrieve an Enumeration of Names of a schema type
// #######################################################################
/// <summary>
/// This helper function returns a number that represents the type of schema
/// definition the element represents. The top of this file enumerates
/// these types.
/// </summary>
/// <param name="element">
/// A class extending LdapSchemaElement.
/// </param>
/// <returns>
/// a Number that identifies the type of schema element and
/// will be one of the following:
/// ATTRIBUTE, OBJECT_CLASS, SYNTAX, NAME_FORM,
/// DITCONTENT, DITSTRUCTURE, MATCHING, MATCHING_USE
/// </returns>
private int getType(LdapSchemaElement element)
{
if (element is LdapAttributeSchema)
return ATTRIBUTE;
if (element is LdapObjectClassSchema)
return OBJECT_CLASS;
if (element is LdapSyntaxSchema)
return SYNTAX;
if (element is LdapNameFormSchema)
return NAME_FORM;
if (element is LdapMatchingRuleSchema)
return MATCHING;
if (element is LdapMatchingRuleUseSchema)
return MATCHING_USE;
if (element is LdapDITContentRuleSchema)
return DITCONTENT;
if (element is LdapDITStructureRuleSchema)
return DITSTRUCTURE;
throw new ArgumentException("The specified schema element type is not recognized");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
namespace System.Security.Cryptography.Encryption.Tests.Symmetric
{
public static class TrivialTests
{
[Fact]
public static void TestKey()
{
using (Trivial s = new Trivial())
{
Assert.Equal(0, s.KeySize);
Assert.Throws<ArgumentNullException>(() => s.Key = null);
{
// Testing automatic generation of Key.
Trivial t = new Trivial();
byte[] generatedKey = t.Key;
Assert.Equal(generatedKey, Trivial.GeneratedKey);
Assert.False(Object.ReferenceEquals(generatedKey, Trivial.GeneratedKey));
}
// Testing KeySize and Key setter.
int[] validKeySizes = { 40, 104, 152, 808, 816, 824, 832 };
for (int keySize = -10; keySize < 200 * 8; keySize++)
{
if (validKeySizes.Contains(keySize))
{
s.KeySize = keySize;
Assert.Equal(keySize, s.KeySize);
}
else
{
Assert.Throws<CryptographicException>(() => s.KeySize = keySize);
}
if (keySize >= 0)
{
int keySizeInBytes = keySize / 8;
byte[] key = GenerateRandom(keySizeInBytes);
if (validKeySizes.Contains(keySizeInBytes * 8))
{
s.Key = key;
byte[] copyOfKey = s.Key;
Assert.Equal(key, copyOfKey);
Assert.False(Object.ReferenceEquals(key, copyOfKey));
}
else
{
Assert.Throws<CryptographicException>(() => s.Key = key);
}
}
}
// Test overflow
try
{
byte[] hugeKey = new byte[536870917]; // value chosen so that when multiplied by 8 (bits) it overflows to the value 40
Assert.Throws<CryptographicException>(() => s.Key = hugeKey);
}
catch (OutOfMemoryException) { } // in case there isn't enough memory at test-time to allocate the large array
}
}
[Fact]
public static void TestIv()
{
using (Trivial s = new Trivial())
{
Assert.Throws<ArgumentNullException>(() => s.IV = null);
{
// Testing automatic generation of Iv.
Trivial t = new Trivial();
t.BlockSize = 5 * 8;
byte[] generatedIv = t.IV;
Assert.Equal(generatedIv, Trivial.GeneratedIV);
Assert.False(Object.ReferenceEquals(generatedIv, Trivial.GeneratedIV));
}
// Testing IV property setter
{
s.BlockSize = 5 * 8;
{
byte[] iv = GenerateRandom(5);
s.IV = iv;
byte[] copyOfIv = s.IV;
Assert.Equal(iv, copyOfIv);
Assert.False(Object.ReferenceEquals(iv, copyOfIv));
}
{
byte[] iv = GenerateRandom(6);
Assert.Throws<CryptographicException>(() => s.IV = iv);
}
}
}
return;
}
[Fact]
public static void TestBlockSize()
{
using (Trivial s = new Trivial())
{
Assert.Equal(0, s.BlockSize);
// Testing BlockSizeSetter.
int[] validBlockSizes = { 40, 104, 152, 808, 816, 824, 832 };
for (int blockSize = -10; blockSize < 200 * 8; blockSize++)
{
if (validBlockSizes.Contains(blockSize))
{
s.BlockSize = blockSize;
Assert.Equal(blockSize, s.BlockSize);
}
else
{
Assert.Throws<CryptographicException>(() => s.BlockSize = blockSize);
}
}
}
return;
}
private static byte[] GenerateRandom(int size)
{
byte[] data = new byte[size];
Random r = new Random();
for (int i = 0; i < size; i++)
{
data[i] = unchecked((byte)(r.Next()));
}
return data;
}
private class Trivial : SymmetricAlgorithm
{
public Trivial()
{
//
// Although the desktop CLR allows overriding the LegalKeySizes property,
// the BlockSize setter does not invoke the overriding method when validating
// the blockSize. Instead, it accesses the underlying field (LegalKeySizesValue) directly.
//
// We've since removed this field from the public surface area (and fixed the BlockSize property
// to call LegalKeySizes rather than the underlying field.) To make this test also run on the desktop, however,
// we will also set the LegalKeySizesValue field if present.
//
FieldInfo legalBlockSizesValue = typeof(SymmetricAlgorithm).GetTypeInfo().GetDeclaredField("LegalBlockSizesValue");
if (legalBlockSizesValue != null && legalBlockSizesValue.IsFamily)
{
legalBlockSizesValue.SetValue(this, LegalBlockSizes);
}
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
{
throw new CreateDecryptorNotImplementedException();
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
{
throw new CreateEncryptorNotImplementedException();
}
public override void GenerateIV()
{
IV = GeneratedIV;
}
public override void GenerateKey()
{
Key = GeneratedKey;
}
public override KeySizes[] LegalBlockSizes
{
get
{
return new KeySizes[]
{
new KeySizes(5*8, -99*8, 0*8),
new KeySizes(13*8, 22*8, 6*8),
new KeySizes(101*8, 104*8, 1*8),
};
}
}
public override KeySizes[] LegalKeySizes
{
get
{
return new KeySizes[]
{
new KeySizes(5*8, -99*8, 0*8),
new KeySizes(13*8, 22*8, 6*8),
new KeySizes(101*8, 104*8, 1*8),
};
}
}
public static readonly byte[] GeneratedKey = GenerateRandom(13);
public static readonly byte[] GeneratedIV = GenerateRandom(5);
}
private class GenerateIvNotImplementedException : Exception { }
private class GenerateKeyNotImplementedException : Exception { }
private class CreateDecryptorNotImplementedException : Exception { }
private class CreateEncryptorNotImplementedException : Exception { }
}
}
| |
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Providers.Streams.AzureQueue;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.Streaming;
using UnitTests.StreamingTests;
using Xunit;
namespace Tester.AzureUtils.Streaming
{
[TestCategory("Streaming"), TestCategory("Azure"), TestCategory("AzureQueue")]
public class AQStreamingTests : TestClusterPerTest
{
public const string AzureQueueStreamProviderName = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
public const string SmsStreamProviderName = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
private readonly SingleStreamTestRunner runner;
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
TestUtils.CheckForAzureStorage();
builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>();
builder.AddClientBuilderConfigurator<MyClientBuilderConfigurator>();
}
private class MyClientBuilderConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder
.AddSimpleMessageStreamProvider(SmsStreamProviderName)
.AddAzureQueueStreams<AzureQueueDataAdapterV2>(AzureQueueStreamProviderName,
options =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
});
}
}
private class SiloBuilderConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder
.AddSimpleMessageStreamProvider(SmsStreamProviderName)
.AddAzureTableGrainStorage("AzureStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.ServiceId = silo.Value.ServiceId.ToString();
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.DeleteStateOnClear = true;
}))
.AddAzureTableGrainStorage("PubSubStore", builder => builder.Configure<IOptions<ClusterOptions>>((options, silo) =>
{
options.ServiceId = silo.Value.ServiceId.ToString();
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
options.DeleteStateOnClear = true;
}))
.AddAzureQueueStreams<AzureQueueDataAdapterV2>(AzureQueueStreamProviderName,
options =>
{
options.ConnectionString = TestDefaultConfiguration.DataConnectionString;
})
.AddMemoryGrainStorage("MemoryStore");
}
}
public AQStreamingTests()
{
runner = new SingleStreamTestRunner(this.InternalClient, SingleStreamTestRunner.AQ_STREAM_PROVIDER_NAME);
}
public override void Dispose()
{
var clusterId = HostedCluster.Options.ClusterId;
base.Dispose();
AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(NullLoggerFactory.Instance, SingleStreamTestRunner.AQ_STREAM_PROVIDER_NAME, clusterId, TestDefaultConfiguration.DataConnectionString).Wait();
}
////------------------------ One to One ----------------------//
[SkippableFact, TestCategory("Functional")]
public async Task AQ_01_OneProducerGrainOneConsumerGrain()
{
await runner.StreamTest_01_OneProducerGrainOneConsumerGrain();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_02_OneProducerGrainOneConsumerClient()
{
await runner.StreamTest_02_OneProducerGrainOneConsumerClient();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_03_OneProducerClientOneConsumerGrain()
{
await runner.StreamTest_03_OneProducerClientOneConsumerGrain();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_04_OneProducerClientOneConsumerClient()
{
await runner.StreamTest_04_OneProducerClientOneConsumerClient();
}
//------------------------ MANY to Many different grains ----------------------//
[SkippableFact, TestCategory("Functional")]
public async Task AQ_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains()
{
await runner.StreamTest_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_06_ManyDifferent_ManyProducerGrainManyConsumerClients()
{
await runner.StreamTest_06_ManyDifferent_ManyProducerGrainManyConsumerClients();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_07_ManyDifferent_ManyProducerClientsManyConsumerGrains()
{
await runner.StreamTest_07_ManyDifferent_ManyProducerClientsManyConsumerGrains();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_08_ManyDifferent_ManyProducerClientsManyConsumerClients()
{
await runner.StreamTest_08_ManyDifferent_ManyProducerClientsManyConsumerClients();
}
//------------------------ MANY to Many Same grains ----------------------//
[SkippableFact, TestCategory("Functional")]
public async Task AQ_09_ManySame_ManyProducerGrainsManyConsumerGrains()
{
await runner.StreamTest_09_ManySame_ManyProducerGrainsManyConsumerGrains();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_10_ManySame_ManyConsumerGrainsManyProducerGrains()
{
await runner.StreamTest_10_ManySame_ManyConsumerGrainsManyProducerGrains();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_11_ManySame_ManyProducerGrainsManyConsumerClients()
{
await runner.StreamTest_11_ManySame_ManyProducerGrainsManyConsumerClients();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_12_ManySame_ManyProducerClientsManyConsumerGrains()
{
await runner.StreamTest_12_ManySame_ManyProducerClientsManyConsumerGrains();
}
//------------------------ MANY to Many producer consumer same grain ----------------------//
[SkippableFact, TestCategory("Functional")]
public async Task AQ_13_SameGrain_ConsumerFirstProducerLater()
{
await runner.StreamTest_13_SameGrain_ConsumerFirstProducerLater(false);
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_14_SameGrain_ProducerFirstConsumerLater()
{
await runner.StreamTest_14_SameGrain_ProducerFirstConsumerLater(false);
}
//----------------------------------------------//
[SkippableFact, TestCategory("Functional")]
public async Task AQ_15_ConsumeAtProducersRequest()
{
await runner.StreamTest_15_ConsumeAtProducersRequest();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_16_MultipleStreams_ManyDifferent_ManyProducerGrainsManyConsumerGrains()
{
var multiRunner = new MultipleStreamsTestRunner(this.InternalClient, SingleStreamTestRunner.AQ_STREAM_PROVIDER_NAME, 16, false);
await multiRunner.StreamTest_MultipleStreams_ManyDifferent_ManyProducerGrainsManyConsumerGrains();
}
[SkippableFact, TestCategory("Functional")]
public async Task AQ_17_MultipleStreams_1J_ManyProducerGrainsManyConsumerGrains()
{
var multiRunner = new MultipleStreamsTestRunner(this.InternalClient, SingleStreamTestRunner.AQ_STREAM_PROVIDER_NAME, 17, false);
await multiRunner.StreamTest_MultipleStreams_ManyDifferent_ManyProducerGrainsManyConsumerGrains(
this.HostedCluster.StartAdditionalSilo);
}
//[SkippableFact, TestCategory("BVT"), TestCategory("Functional")]
/*public async Task AQ_18_MultipleStreams_1J_1F_ManyProducerGrainsManyConsumerGrains()
{
var multiRunner = new MultipleStreamsTestRunner(this.InternalClient, SingleStreamTestRunner.AQ_STREAM_PROVIDER_NAME, 18, false);
await multiRunner.StreamTest_MultipleStreams_ManyDifferent_ManyProducerGrainsManyConsumerGrains(
this.HostedCluster.StartAdditionalSilo,
this.HostedCluster.StopSilo);
}*/
[SkippableFact]
public async Task AQ_19_ConsumerImplicitlySubscribedToProducerClient()
{
// todo: currently, the Azure queue queue adaptor doesn't support namespaces, so this test will fail.
await runner.StreamTest_19_ConsumerImplicitlySubscribedToProducerClient();
}
[SkippableFact]
public async Task AQ_20_ConsumerImplicitlySubscribedToProducerGrain()
{
// todo: currently, the Azure queue queue adaptor doesn't support namespaces, so this test will fail.
await runner.StreamTest_20_ConsumerImplicitlySubscribedToProducerGrain();
}
[SkippableFact(Skip = "Ignored"), TestCategory("Failures")]
public async Task AQ_21_GenericConsumerImplicitlySubscribedToProducerGrain()
{
// todo: currently, the Azure queue queue adaptor doesn't support namespaces, so this test will fail.
await runner.StreamTest_21_GenericConsumerImplicitlySubscribedToProducerGrain();
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Kinect.VisualGestureBuilder;
using Windows.Kinect;
using System.IO;
/// <summary>
/// This interface needs to be implemented by all visual gesture listeners
/// </summary>
public interface VisualGestureListenerInterface
{
/// <summary>
/// Invoked when a continuous gesture reports progress >= 0.1f
/// </summary>
/// <param name="userId">User ID</param>
/// <param name="userIndex">User index</param>
/// <param name="gesture">Gesture name</param>
/// <param name="progress">Gesture progress [0..1]</param>
void GestureInProgress(long userId, int userIndex, string gesture, float progress);
/// <summary>
/// Invoked when a discrete gesture is completed.
/// </summary>
/// <returns><c>true</c>, if the gesture detection must be restarted, <c>false</c> otherwise.</returns>
/// <param name="userId">User ID</param>
/// <param name="userIndex">User index</param>
/// <param name="gesture">Gesture name</param>
/// <param name="confidence">Gesture confidence [0..1]</param>
bool GestureCompleted(long userId, int userIndex, string gesture, float confidence);
}
/// <summary>
/// Visual gesture data structure.
/// </summary>
public struct VisualGestureData
{
public long userId;
public float timestamp;
public string gestureName;
public bool isDiscrete;
public bool isContinuous;
public bool isComplete;
public bool isResetting;
public float confidence;
public float progress;
}
/// <summary>
/// Visual gesture manager is the component dealing with VGB gestures.
/// </summary>
public class VisualGestureManager : MonoBehaviour
{
[Tooltip("Index of the player, tracked by this component. 0 means the 1st player, 1 - the 2nd one, 2 - the 3rd one, etc.")]
public int playerIndex = 0;
[Tooltip("File name of the VG database, used by the visual gesture recognizer. The file will be copied from Resources, if does not exist.")]
public string gestureDatabase = string.Empty;
[Tooltip("List of the tracked visual gestures. If the list is empty, all gestures found in the database will be tracked.")]
public List<string> gestureNames = new List<string>();
[Tooltip("Minimum confidence required, to consider discrete gestures as completed. Confidence varies between 0.0 and 1.0.")]
public float minConfidence = 0.1f;
[Tooltip("List of the utilized visual gesture listeners. They must implement VisualGestureListenerInterface. If the list is empty, the available gesture listeners will be detected at start up.")]
public List<MonoBehaviour> visualGestureListeners;
[Tooltip("GUI-Text to display the VG-manager debug messages.")]
public GUIText debugText;
// primary user ID, as reported by KinectManager
private long primaryUserID = 0;
// gesture data holders for each tracked gesture
private Dictionary<string, VisualGestureData> gestureData = new Dictionary<string, VisualGestureData>();
// gesture frame source which should be tied to a body tracking ID
private VisualGestureBuilderFrameSource vgbFrameSource = null;
// gesture frame reader which will handle gesture events
private VisualGestureBuilderFrameReader vgbFrameReader = null;
// primary sensor data structure
//private KinectInterop.SensorData sensorData = null;
// Bool to keep track of whether visual-gesture system has been initialized
private bool isVisualGestureInitialized = false;
// The single instance of VisualGestureManager
private static VisualGestureManager instance;
/// <summary>
/// Gets the single VisualGestureManager instance.
/// </summary>
/// <value>The VisualGestureManager instance.</value>
public static VisualGestureManager Instance
{
get
{
return instance;
}
}
/// <summary>
/// Determines whether the visual-gesture manager was successfully initialized.
/// </summary>
/// <returns><c>true</c> if visual-gesture manager was successfully initialized; otherwise, <c>false</c>.</returns>
public bool IsVisualGestureInitialized()
{
return isVisualGestureInitialized;
}
/// <summary>
/// Gets the skeleton ID of the tracked user, or 0 if no user was associated with the gestures.
/// </summary>
/// <returns>The skeleton ID of the tracked user.</returns>
public long GetTrackedUserID()
{
return primaryUserID;
}
/// <summary>
/// Gets the list of detected gestures.
/// </summary>
/// <returns>The list of detected gestures.</returns>
public List<string> GetGesturesList()
{
return gestureNames;
}
/// <summary>
/// Gets the count of detected gestures.
/// </summary>
/// <returns>The count of detected gestures.</returns>
public int GetGesturesCount()
{
return gestureNames.Count;
}
/// <summary>
/// Gets the gesture name at specified index, or empty string if the index is out of range.
/// </summary>
/// <returns>The gesture name at specified index.</returns>
/// <param name="i">The index</param>
public string GetGestureAtIndex(int i)
{
if(i >= 0 && i < gestureNames.Count)
{
return gestureNames[i];
}
return string.Empty;
}
/// <summary>
/// Determines whether the given gesture is in the list of detected gestures.
/// </summary>
/// <returns><c>true</c> if the given gesture is in the list of detected gestures; otherwise, <c>false</c>.</returns>
/// <param name="gestureName">Gesture name.</param>
public bool IsTrackingGesture(string gestureName)
{
return gestureNames.Contains(gestureName);
}
/// <summary>
/// Determines whether the specified discrete gesture is completed.
/// </summary>
/// <returns><c>true</c> if the specified discrete gesture is completed; otherwise, <c>false</c>.</returns>
/// <param name="gestureName">Gesture name</param>
/// <param name="bResetOnComplete">If set to <c>true</c>, resets the gesture state.</param>
public bool IsGestureCompleted(string gestureName, bool bResetOnComplete)
{
if(gestureNames.Contains(gestureName))
{
VisualGestureData data = gestureData[gestureName];
if(data.isDiscrete && data.isComplete && !data.isResetting && data.confidence >= minConfidence)
{
if(bResetOnComplete)
{
data.isResetting = true;
gestureData[gestureName] = data;
}
return true;
}
}
return false;
}
/// <summary>
/// Gets the confidence of the specified discrete gesture, in range [0, 1].
/// </summary>
/// <returns>The gesture confidence.</returns>
/// <param name="gestureName">Gesture name</param>
public float GetGestureConfidence(string gestureName)
{
if(gestureNames.Contains(gestureName))
{
VisualGestureData data = gestureData[gestureName];
if(data.isDiscrete)
{
return data.confidence;
}
}
return 0f;
}
/// <summary>
/// Gets the progress of the specified continuous gesture, in range [0, 1].
/// </summary>
/// <returns>The gesture progress.</returns>
/// <param name="gestureName">Gesture name</param>
public float GetGestureProgress(string gestureName)
{
if(gestureNames.Contains(gestureName))
{
VisualGestureData data = gestureData[gestureName];
if(data.isContinuous)
{
return data.progress;
}
}
return 0f;
}
//----------------------------------- end of public functions --------------------------------------//
void Start()
{
try
{
// get sensor data
KinectManager kinectManager = KinectManager.Instance;
KinectInterop.SensorData sensorData = kinectManager != null ? kinectManager.GetSensorData() : null;
if(sensorData == null || sensorData.sensorInterface == null)
{
throw new Exception("Visual gesture tracking cannot be started, because the KinectManager is missing or not initialized.");
}
if(sensorData.sensorInterface.GetSensorPlatform() != KinectInterop.DepthSensorPlatform.KinectSDKv2)
{
throw new Exception("Visual gesture tracking is only supported by Kinect SDK v2");
}
// ensure the needed dlls are in place and face tracking is available for this interface
bool bNeedRestart = false;
if(IsVisualGesturesAvailable(ref bNeedRestart))
{
if(bNeedRestart)
{
KinectInterop.RestartLevel(gameObject, "VG");
return;
}
}
else
{
throw new Exception("Visual gesture tracking is not supported!");
}
// initialize visual gesture tracker
if (!InitVisualGestures())
{
throw new Exception("Visual gesture tracking could not be initialized.");
}
// try to automatically detect the available gesture listeners in the scene
if(visualGestureListeners.Count == 0)
{
MonoBehaviour[] monoScripts = FindObjectsOfType(typeof(MonoBehaviour)) as MonoBehaviour[];
foreach(MonoBehaviour monoScript in monoScripts)
{
if(typeof(VisualGestureListenerInterface).IsAssignableFrom(monoScript.GetType()))
{
visualGestureListeners.Add(monoScript);
}
}
}
// all set
instance = this;
isVisualGestureInitialized = true;
}
catch(DllNotFoundException ex)
{
Debug.LogError(ex.ToString());
if(debugText != null)
debugText.GetComponent<GUIText>().text = "Please check the Kinect and FT-Library installations.";
}
catch (Exception ex)
{
Debug.LogError(ex.ToString());
if(debugText != null)
debugText.GetComponent<GUIText>().text = ex.Message;
}
}
void OnDestroy()
{
if(isVisualGestureInitialized)
{
// finish visual gesture tracking
FinishVisualGestures();
}
isVisualGestureInitialized = false;
instance = null;
}
void Update()
{
if(isVisualGestureInitialized)
{
KinectManager kinectManager = KinectManager.Instance;
if(kinectManager && kinectManager.IsInitialized())
{
primaryUserID = kinectManager.GetUserIdByIndex(playerIndex);
}
// update visual gesture tracking
if(UpdateVisualGestures(primaryUserID))
{
// process the gestures
foreach(string gestureName in gestureNames)
{
if(gestureData.ContainsKey(gestureName))
{
VisualGestureData data = gestureData[gestureName];
if(data.isComplete && !data.isResetting && data.confidence >= minConfidence)
{
Debug.Log(gestureName + " detected.");
int userIndex = kinectManager ? kinectManager.GetUserIndexById(data.userId) : 0;
foreach(VisualGestureListenerInterface listener in visualGestureListeners)
{
if(listener.GestureCompleted(data.userId, userIndex, data.gestureName, data.confidence))
{
data.isResetting = true;
gestureData[gestureName] = data;
}
}
}
else if(data.progress >= 0.1f)
{
int userIndex = kinectManager ? kinectManager.GetUserIndexById(data.userId) : 0;
foreach(VisualGestureListenerInterface listener in visualGestureListeners)
{
listener.GestureInProgress(data.userId, userIndex, data.gestureName, data.progress);
}
}
}
}
}
}
}
private bool IsVisualGesturesAvailable(ref bool bNeedRestart)
{
bool bOneCopied = false, bAllCopied = true;
string sTargetPath = ".";
if(!KinectInterop.Is64bitArchitecture())
{
// 32 bit
sTargetPath = KinectInterop.GetTargetDllPath(".", false) + "/";
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["Kinect20.VisualGestureBuilder.dll"] = sTargetPath + "Kinect20.VisualGestureBuilder.dll";
dictFilesToUnzip["KinectVisualGestureBuilderUnityAddin.dll"] = sTargetPath + "KinectVisualGestureBuilderUnityAddin.dll";
dictFilesToUnzip["vgbtechs/AdaBoostTech.dll"] = sTargetPath + "vgbtechs/AdaBoostTech.dll";
dictFilesToUnzip["vgbtechs/RFRProgressTech.dll"] = sTargetPath + "vgbtechs/RFRProgressTech.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x86.zip", ref bOneCopied, ref bAllCopied);
}
else
{
//Debug.Log("Face - x64-architecture.");
sTargetPath = KinectInterop.GetTargetDllPath(".", true) + "/";
Dictionary<string, string> dictFilesToUnzip = new Dictionary<string, string>();
dictFilesToUnzip["Kinect20.VisualGestureBuilder.dll"] = sTargetPath + "Kinect20.VisualGestureBuilder.dll";
dictFilesToUnzip["KinectVisualGestureBuilderUnityAddin.dll"] = sTargetPath + "KinectVisualGestureBuilderUnityAddin.dll";
dictFilesToUnzip["vgbtechs/AdaBoostTech.dll"] = sTargetPath + "vgbtechs/AdaBoostTech.dll";
dictFilesToUnzip["vgbtechs/RFRProgressTech.dll"] = sTargetPath + "vgbtechs/RFRProgressTech.dll";
dictFilesToUnzip["msvcp110.dll"] = sTargetPath + "msvcp110.dll";
dictFilesToUnzip["msvcr110.dll"] = sTargetPath + "msvcr110.dll";
KinectInterop.UnzipResourceFiles(dictFilesToUnzip, "KinectV2UnityAddin.x64.zip", ref bOneCopied, ref bAllCopied);
}
bNeedRestart = (bOneCopied && bAllCopied);
return true;
}
private bool InitVisualGestures()
{
KinectManager kinectManager = KinectManager.Instance;
KinectInterop.SensorData sensorData = kinectManager != null ? kinectManager.GetSensorData() : null;
Kinect2Interface kinectInterface = sensorData.sensorInterface as Kinect2Interface;
KinectSensor kinectSensor = kinectInterface != null ? kinectInterface.kinectSensor : null;
if(kinectSensor == null)
return false;
if(gestureDatabase == string.Empty)
{
Debug.LogError("Please specify gesture database file!");
return false;
}
// copy the gesture database file from Resources, if available
if(!File.Exists(gestureDatabase))
{
TextAsset textRes = Resources.Load(gestureDatabase, typeof(TextAsset)) as TextAsset;
if(textRes != null && textRes.bytes.Length != 0)
{
File.WriteAllBytes(gestureDatabase, textRes.bytes);
}
}
// create the vgb source
vgbFrameSource = VisualGestureBuilderFrameSource.Create(kinectSensor, 0);
// open the reader
vgbFrameReader = vgbFrameSource != null ? vgbFrameSource.OpenReader() : null;
if(vgbFrameReader != null)
{
vgbFrameReader.IsPaused = true;
}
using (VisualGestureBuilderDatabase database = VisualGestureBuilderDatabase.Create(gestureDatabase))
{
if(database == null)
{
Debug.LogError("Gesture database not found: " + gestureDatabase);
return false;
}
// check if we need to load all gestures
bool bAllGestures = (gestureNames.Count == 0);
foreach (Gesture gesture in database.AvailableGestures)
{
bool bAddGesture = bAllGestures || gestureNames.Contains(gesture.Name);
if(bAddGesture)
{
string sGestureName = gesture.Name;
vgbFrameSource.AddGesture(gesture);
if(!gestureNames.Contains(sGestureName))
{
gestureNames.Add(sGestureName);
}
if(!gestureData.ContainsKey(sGestureName))
{
VisualGestureData data = new VisualGestureData();
data.gestureName = sGestureName;
data.isDiscrete = (gesture.GestureType == GestureType.Discrete);
data.isContinuous = (gesture.GestureType == GestureType.Continuous);
data.timestamp = Time.realtimeSinceStartup;
gestureData.Add(sGestureName, data);
}
}
}
}
return true;
}
private void FinishVisualGestures()
{
if (vgbFrameReader != null)
{
vgbFrameReader.Dispose();
vgbFrameReader = null;
}
if (vgbFrameSource != null)
{
vgbFrameSource.Dispose();
vgbFrameSource = null;
}
if(gestureData != null)
{
gestureData.Clear();
}
}
private bool UpdateVisualGestures(long userId)
{
if(vgbFrameSource == null || vgbFrameReader == null)
return false;
bool wasPaused = vgbFrameReader.IsPaused;
vgbFrameSource.TrackingId = (ulong)userId;
vgbFrameReader.IsPaused = (userId == 0);
if(vgbFrameReader.IsPaused)
{
if(!wasPaused)
{
// clear the gesture states
foreach (Gesture gesture in vgbFrameSource.Gestures)
{
if(gestureData.ContainsKey(gesture.Name))
{
VisualGestureData data = gestureData[gesture.Name];
data.userId = 0;
data.isComplete = false;
data.isResetting = false;
data.confidence = 0f;
data.progress = 0f;
data.timestamp = Time.realtimeSinceStartup;
gestureData[gesture.Name] = data;
}
}
}
return false;
}
VisualGestureBuilderFrame frame = vgbFrameReader.CalculateAndAcquireLatestFrame();
if(frame != null)
{
Dictionary<Gesture, DiscreteGestureResult> discreteResults = frame.DiscreteGestureResults;
Dictionary<Gesture, ContinuousGestureResult> continuousResults = frame.ContinuousGestureResults;
if (discreteResults != null)
{
foreach (Gesture gesture in discreteResults.Keys)
{
if(gesture.GestureType == GestureType.Discrete && gestureData.ContainsKey(gesture.Name))
{
DiscreteGestureResult result = discreteResults[gesture];
VisualGestureData data = gestureData[gesture.Name];
data.userId = vgbFrameSource.IsTrackingIdValid ? (long)vgbFrameSource.TrackingId : 0;
data.isComplete = result.Detected;
data.confidence = result.Confidence;
data.timestamp = Time.realtimeSinceStartup;
//Debug.Log(string.Format ("{0} - {1}, confidence: {2:F0}%", data.gestureName, data.isComplete ? "Yes" : "No", data.confidence * 100f));
if(data.isResetting && !data.isComplete)
{
data.isResetting = false;
}
gestureData[gesture.Name] = data;
}
}
}
if (continuousResults != null)
{
foreach (Gesture gesture in continuousResults.Keys)
{
if(gesture.GestureType == GestureType.Continuous && gestureData.ContainsKey(gesture.Name))
{
ContinuousGestureResult result = continuousResults[gesture];
VisualGestureData data = gestureData[gesture.Name];
data.userId = vgbFrameSource.IsTrackingIdValid ? (long)vgbFrameSource.TrackingId : 0;
data.progress = result.Progress;
data.timestamp = Time.realtimeSinceStartup;
gestureData[gesture.Name] = data;
}
}
}
frame.Dispose();
frame = null;
}
return true;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ExcelImporter.Areas.HelpPage.ModelDescriptions;
using ExcelImporter.Areas.HelpPage.Models;
namespace ExcelImporter.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
#region File Information
//-----------------------------------------------------------------------------
// ScaledAnimation.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace HoneycombRush
{
/// <summary>
/// Supports animation playback.
/// </summary>
public class ScaledAnimation
{
#region Fields
Texture2D animatedCharacter;
Point sheetSize;
public Point currentFrame;
public Point frameSize;
private TimeSpan lastestChangeTime;
private TimeSpan timeInterval = TimeSpan.Zero;
private int startFrame;
private int endFrame;
private int lastSubFrame = -1;
bool drawWasAlreadyCalledOnce = false;
public int FrameCount
{
get
{
return sheetSize.X * sheetSize.Y;
}
}
public Vector2 Offset { get; set; }
public int FrameIndex
{
get
{
return sheetSize.X * currentFrame.Y + currentFrame.X;
}
set
{
if (value >= sheetSize.X * sheetSize.Y + 1)
{
throw new InvalidOperationException("Specified frame index exceeds available frames");
}
currentFrame.Y = value / sheetSize.X;
currentFrame.X = value % sheetSize.X;
}
}
public bool IsActive { get; private set; }
#endregion
#region Initialization
/// <summary>
/// Creates a new instance of the animation class
/// </summary>
/// <param name="frameSheet">Texture which is a sheet containing
/// the animation frames.</param>
/// <param name="size">The size of a single frame.</param>
/// <param name="frameSheetSize">The size of the entire animation sheet.</param>
public ScaledAnimation(Texture2D frameSheet, Point size, Point frameSheetSize)
{
animatedCharacter = frameSheet;
frameSize = size;
sheetSize = frameSheetSize;
Offset = Vector2.Zero;
}
#endregion
#region Update and Render
/// <summary>
/// Updates the animation's progress.
/// </summary>
/// <param name="gameTime">Game time information.</param>
/// <param name="isInMotion">Whether or not the animation element itself is
/// currently in motion.</param>
public void Update(GameTime gameTime, bool isInMotion)
{
Update(gameTime, isInMotion, false);
}
/// <summary>
/// Updates the animation's progress.
/// </summary>
/// <param name="gameTime">Game time information.</param>
/// <param name="isInMotion">Whether or not the animation element itself is
/// currently in motion.</param>
/// <param name="runSubAnimation"></param>
public void Update(GameTime gameTime, bool isInMotion, bool runSubAnimation)
{
if (IsActive && gameTime.TotalGameTime != lastestChangeTime)
{
// See if a time interval between frames is defined
if (timeInterval != TimeSpan.Zero)
{
// Do nothing until an interval passes
if (lastestChangeTime + timeInterval > gameTime.TotalGameTime)
{
return;
}
}
lastestChangeTime = gameTime.TotalGameTime;
if (FrameIndex >= FrameCount)
{
FrameIndex = 0; // Reset the animation
}
else
{
// Only advance the animation if the animation element is moving
if (isInMotion)
{
if (runSubAnimation)
{
// Initialize the animation
if (lastSubFrame == -1)
{
lastSubFrame = startFrame;
}
// Calculate the currentFrame, which depends on the current
// frame in the parent animation
currentFrame.Y = lastSubFrame / sheetSize.X;
currentFrame.X = lastSubFrame % sheetSize.X;
// Move to the next Frame
lastSubFrame += 1;
// Loop the animation
if (lastSubFrame > endFrame)
{
lastSubFrame = startFrame;
}
}
else
{
// Do not advance frames before the first draw operation
if (drawWasAlreadyCalledOnce)
{
currentFrame.X++;
if (currentFrame.X >= sheetSize.X)
{
currentFrame.X = 0;
currentFrame.Y++;
}
if (currentFrame.Y >= sheetSize.Y)
currentFrame.Y = 0;
if (lastSubFrame != -1)
{
lastSubFrame = -1;
}
}
}
}
}
}
}
/// <summary>
/// Render the animation.
/// </summary>
/// <param name="ScaledSpriteBatch">ScaledSpriteBatch with which the current
/// frame will be rendered.</param>
/// <param name="position">The position to draw the current frame.</param>
/// <param name="spriteEffect">SpriteEffect to apply to the
/// current frame.</param>
public void Draw(ScaledSpriteBatch ScaledSpriteBatch, Vector2 position, SpriteEffects spriteEffect)
{
Draw(ScaledSpriteBatch, position, 1.0f, spriteEffect);
}
/// <summary>
/// Render the animation.
/// </summary>
/// <param name="ScaledSpriteBatch">ScaledSpriteBatch with which the current frame
/// will be rendered.</param>
/// <param name="position">The position to draw the current frame.</param>
/// <param name="scale">Scale factor to apply to the current frame.</param>
/// <param name="spriteEffect">SpriteEffect to apply to the
/// current frame.</param>
public void Draw(ScaledSpriteBatch ScaledSpriteBatch, Vector2 position, float scale, SpriteEffects spriteEffect)
{
drawWasAlreadyCalledOnce = true;
ScaledSpriteBatch.Draw(animatedCharacter, position + Offset,
new Rectangle(frameSize.X * currentFrame.X, frameSize.Y * currentFrame.Y, frameSize.X, frameSize.Y),
Color.White, 0f, Vector2.Zero, scale, spriteEffect, 0);
}
/// <summary>
/// Causes the animation to start playing from a specified frame index.
/// </summary>
/// <param name="frameIndex">Frame index to play the animation from.</param>
public void PlayFromFrameIndex(int frameIndex)
{
FrameIndex = frameIndex;
IsActive = true;
drawWasAlreadyCalledOnce = false;
}
/// <summary>
/// Sets the range of frames which serves as the sub animation.
/// </summary>
/// <param name="startFrame">Start frame for the sub-animation.</param>
/// <param name="endFrame">End frame for the sub-animation.</param>
public void SetSubAnimation(int startFrame, int endFrame)
{
this.startFrame = startFrame;
this.endFrame = endFrame;
}
/// <summary>
/// Used to set the interval between frames.
/// </summary>
/// <param name="interval">The interval between frames.</param>
public void SetFrameInterval(TimeSpan interval)
{
timeInterval = interval;
}
#endregion
}
}
| |
// 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 Microsoft.Data.OData.Query
{
#region Namespaces
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Spatial;
using System.Text;
using System.Xml;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.OData.Metadata;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// Parser which consumes the URI format of primitive types and converts it to primitive types.
/// </summary>
internal static class UriPrimitiveTypeParser
{
/// <summary>Whitespace characters to trim around literals.</summary>
private static char[] WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' };
/// <summary>Determines whether the specified character is a valid hexadecimal digit.</summary>
/// <param name="c">Character to check.</param>
/// <returns>true if <paramref name="c"/> is a valid hex digit; false otherwise.</returns>
internal static bool IsCharHexDigit(char c)
{
DebugUtils.CheckNoExternalCallers();
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
/// <summary>Converts a string to a primitive value.</summary>
/// <param name="text">String text to convert.</param>
/// <param name="targetType">Type to convert string to.</param>
/// <param name="targetValue">After invocation, converted value.</param>
/// <returns>true if the value was converted; false otherwise.</returns>
/// <remarks>Copy of the WebConvert.TryKeyStringToPrimitive</remarks>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Complexity is not too high; handling all the cases in one method is preferable to refactoring.")]
internal static bool TryUriStringToPrimitive(string text, IEdmTypeReference targetType, out object targetValue)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(text != null, "text != null");
Debug.Assert(targetType != null, "targetType != null");
if (targetType.IsNullable)
{
if (text == ExpressionConstants.KeywordNull)
{
targetValue = null;
return true;
}
}
IEdmPrimitiveTypeReference primitiveTargetType = targetType.AsPrimitiveOrNull();
if (primitiveTargetType == null)
{
targetValue = null;
return false;
}
EdmPrimitiveTypeKind targetTypeKind = primitiveTargetType.PrimitiveKind();
byte[] byteArrayValue;
bool binaryResult = TryUriStringToByteArray(text, out byteArrayValue);
if (targetTypeKind == EdmPrimitiveTypeKind.Binary)
{
targetValue = (object)byteArrayValue;
return binaryResult;
}
else if (binaryResult)
{
string keyValue = Encoding.UTF8.GetString(byteArrayValue, 0, byteArrayValue.Length);
return TryUriStringToPrimitive(keyValue, targetType, out targetValue);
}
else if (targetTypeKind == EdmPrimitiveTypeKind.Guid)
{
Guid guidValue;
bool result = TryUriStringToGuid(text, out guidValue);
targetValue = guidValue;
return result;
}
else if (targetTypeKind == EdmPrimitiveTypeKind.DateTime)
{
DateTime dateTimeValue;
bool result = TryUriStringToDateTime(text, out dateTimeValue);
targetValue = dateTimeValue;
return result;
}
else if (targetTypeKind == EdmPrimitiveTypeKind.DateTimeOffset)
{
DateTimeOffset dateTimeOffsetValue;
bool result = TryUriStringToDateTimeOffset(text, out dateTimeOffsetValue);
targetValue = dateTimeOffsetValue;
return result;
}
else if (targetTypeKind == EdmPrimitiveTypeKind.Time)
{
TimeSpan timespanValue;
bool result = TryUriStringToTime(text, out timespanValue);
targetValue = timespanValue;
return result;
}
else if (targetTypeKind == EdmPrimitiveTypeKind.Geography)
{
Geography geographyValue;
bool result = TryUriStringToGeography(text, out geographyValue);
targetValue = geographyValue;
return result;
}
else if (targetTypeKind == EdmPrimitiveTypeKind.Geometry)
{
Geometry geometryValue;
bool result = TryUriStringToGeometry(text, out geometryValue);
targetValue = geometryValue;
return result;
}
bool quoted = targetTypeKind == EdmPrimitiveTypeKind.String;
if (quoted != IsUriValueQuoted(text))
{
targetValue = null;
return false;
}
if (quoted)
{
text = RemoveQuotes(text);
}
try
{
switch (targetTypeKind)
{
case EdmPrimitiveTypeKind.String:
targetValue = text;
break;
case EdmPrimitiveTypeKind.Boolean:
targetValue = XmlConvert.ToBoolean(text);
break;
case EdmPrimitiveTypeKind.Byte:
targetValue = XmlConvert.ToByte(text);
break;
case EdmPrimitiveTypeKind.SByte:
targetValue = XmlConvert.ToSByte(text);
break;
case EdmPrimitiveTypeKind.Int16:
targetValue = XmlConvert.ToInt16(text);
break;
case EdmPrimitiveTypeKind.Int32:
targetValue = XmlConvert.ToInt32(text);
break;
case EdmPrimitiveTypeKind.Int64:
if (TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixInt64, ref text))
{
targetValue = XmlConvert.ToInt64(text);
}
else
{
targetValue = default(Int64);
return false;
}
break;
case EdmPrimitiveTypeKind.Single:
if (TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixSingle, ref text))
{
targetValue = XmlConvert.ToSingle(text);
}
else
{
targetValue = default(Single);
return false;
}
break;
case EdmPrimitiveTypeKind.Double:
TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixDouble, ref text);
targetValue = XmlConvert.ToDouble(text);
break;
case EdmPrimitiveTypeKind.Decimal:
if (TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixDecimal, ref text))
{
try
{
targetValue = XmlConvert.ToDecimal(text);
}
catch (FormatException)
{
// we need to support exponential format for decimals since we used to support them in V1
decimal result;
if (Decimal.TryParse(text, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out result))
{
targetValue = result;
}
else
{
targetValue = default(Decimal);
return false;
}
}
}
else
{
targetValue = default(Decimal);
return false;
}
break;
default:
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.UriPrimitiveTypeParser_TryUriStringToPrimitive));
}
return true;
}
catch (FormatException)
{
targetValue = null;
return false;
}
catch (OverflowException)
{
targetValue = null;
return false;
}
}
/// <summary>
/// Try to parse a string value into a non-negative integer.
/// </summary>
/// <param name="text">The string value to parse.</param>
/// <param name="nonNegativeInteger">The non-negative integer value parsed from the <paramref name="text"/>.</param>
/// <returns>True if <paramref name="text"/> could successfully be parsed into a non-negative integer; otherwise returns false.</returns>
internal static bool TryUriStringToNonNegativeInteger(string text, out int nonNegativeInteger)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(text != null, "text != null");
object valueAsObject;
if (!UriPrimitiveTypeParser.TryUriStringToPrimitive(text, EdmCoreModel.Instance.GetInt32(false), out valueAsObject))
{
nonNegativeInteger = -1;
return false;
}
nonNegativeInteger = (int)valueAsObject;
if (nonNegativeInteger < 0)
{
return false;
}
return true;
}
/// <summary>
/// Converts a string to a byte[] value.
/// </summary>
/// <param name="text">String text to convert.</param>
/// <param name="targetValue">After invocation, converted value.</param>
/// <returns>true if the value was converted; false otherwise.</returns>
/// <remarks>Copy of WebConvert.TryKeyStringToByteArray.</remarks>
private static bool TryUriStringToByteArray(string text, out byte[] targetValue)
{
Debug.Assert(text != null, "text != null");
if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixBinary, ref text) &&
!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixShortBinary, ref text))
{
targetValue = null;
return false;
}
if (!TryRemoveQuotes(ref text))
{
targetValue = null;
return false;
}
if ((text.Length % 2) != 0)
{
targetValue = null;
return false;
}
byte[] result = new byte[text.Length / 2];
int resultIndex = 0;
int textIndex = 0;
while (resultIndex < result.Length)
{
char ch0 = text[textIndex];
char ch1 = text[textIndex + 1];
if (!IsCharHexDigit(ch0) || !IsCharHexDigit(ch1))
{
targetValue = null;
return false;
}
result[resultIndex] = (byte)((byte)(HexCharToNibble(ch0) << 4) + HexCharToNibble(ch1));
textIndex += 2;
resultIndex++;
}
targetValue = result;
return true;
}
/// <summary>
/// Converts a string to a GUID value.
/// </summary>
/// <param name="text">String text to convert.</param>
/// <param name="targetValue">After invocation, converted value.</param>
/// <returns>true if the value was converted; false otherwise.</returns>
/// <remarks>Copy of WebConvert.TryKeyStringToGuid.</remarks>
private static bool TryUriStringToGuid(string text, out Guid targetValue)
{
if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixGuid, ref text))
{
targetValue = default(Guid);
return false;
}
if (!TryRemoveQuotes(ref text))
{
targetValue = default(Guid);
return false;
}
try
{
targetValue = XmlConvert.ToGuid(text);
return true;
}
catch (FormatException)
{
targetValue = default(Guid);
return false;
}
}
/// <summary>
/// Converts a string to a DateTime value.
/// </summary>
/// <param name="text">String text to convert.</param>
/// <param name="targetValue">After invocation, converted value.</param>
/// <returns>true if the value was converted; false otherwise.</returns>
/// <remarks>Copy of WebConvert.TryKeyStringToDateTime.</remarks>
private static bool TryUriStringToDateTime(string text, out DateTime targetValue)
{
targetValue = default(DateTime);
if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixDateTime, ref text))
{
return false;
}
if (!TryRemoveQuotes(ref text))
{
return false;
}
try
{
targetValue = o.PlatformHelper.ConvertStringToDateTime(text);
return true;
}
catch (FormatException)
{
return false;
}
}
/// <summary>
/// Converts a string to a DateTimeOffset value.
/// </summary>
/// <param name="text">String text to convert.</param>
/// <param name="targetValue">After invocation, converted value.</param>
/// <returns>true if the value was converted; false otherwise.</returns>
/// <remarks>Copy of WebConvert.TryKeyStringToDateTimeOffset.</remarks>
private static bool TryUriStringToDateTimeOffset(string text, out DateTimeOffset targetValue)
{
targetValue = default(DateTimeOffset);
if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixDateTimeOffset, ref text))
{
return false;
}
if (!TryRemoveQuotes(ref text))
{
return false;
}
try
{
targetValue = XmlConvert.ToDateTimeOffset(text);
return true;
}
catch (FormatException)
{
return false;
}
}
/// <summary>
/// Converts a string to a Time value.
/// </summary>
/// <param name="text">String text to convert.</param>
/// <param name="targetValue">After invocation, converted value.</param>
/// <returns>true if the value was converted; false otherwise.</returns>
/// <remarks>Copy of WebConvert.TryKeyStringToTime.</remarks>
private static bool TryUriStringToTime(string text, out TimeSpan targetValue)
{
if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixTime, ref text))
{
targetValue = default(TimeSpan);
return false;
}
if (!TryRemoveQuotes(ref text))
{
targetValue = default(TimeSpan);
return false;
}
try
{
targetValue = XmlConvert.ToTimeSpan(text);
return true;
}
catch (FormatException)
{
targetValue = default(TimeSpan);
return false;
}
}
/// <summary>
/// Try to parse the given text to a Geography object.
/// </summary>
/// <param name="text">Text to parse.</param>
/// <param name="targetValue">Geography to return.</param>
/// <returns>True if succeeds, false if not.</returns>
private static bool TryUriStringToGeography(string text, out Geography targetValue)
{
if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixGeography, ref text))
{
targetValue = default(Geography);
return false;
}
if (!TryRemoveQuotes(ref text))
{
targetValue = default(Geography);
return false;
}
try
{
targetValue = LiteralUtils.ParseGeography(text);
return true;
}
catch (ParseErrorException)
{
targetValue = default(Geography);
return false;
}
}
/// <summary>
/// Try to parse the given text to a Geometry object.
/// </summary>
/// <param name="text">Text to parse.</param>
/// <param name="targetValue">Geometry to return.</param>
/// <returns>True if succeeds, false if not.</returns>
private static bool TryUriStringToGeometry(string text, out Geometry targetValue)
{
if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixGeometry, ref text))
{
targetValue = default(Geometry);
return false;
}
if (!TryRemoveQuotes(ref text))
{
targetValue = default(Geometry);
return false;
}
try
{
targetValue = LiteralUtils.ParseGeometry(text);
return true;
}
catch (ParseErrorException)
{
targetValue = default(Geometry);
return false;
}
}
/// <summary>
/// Removes quotes from the single-quotes text.
/// </summary>
/// <param name="text">Text to remove quotes from.</param>
/// <returns>Whether quotes were successfully removed.</returns>
/// <remarks>Copy of WebConvert.TryRemoveQuotes.</remarks>
private static bool TryRemoveQuotes(ref string text)
{
Debug.Assert(text != null, "text != null");
if (text.Length < 2)
{
return false;
}
char quote = text[0];
if (quote != '\'' || text[text.Length - 1] != quote)
{
return false;
}
string s = text.Substring(1, text.Length - 2);
int start = 0;
while (true)
{
int i = s.IndexOf(quote, start);
if (i < 0)
{
break;
}
s = s.Remove(i, 1);
if (s.Length < i + 1 || s[i] != quote)
{
return false;
}
start = i + 1;
}
text = s;
return true;
}
/// <summary>
/// Check and strip the input <paramref name="text"/> for literal <paramref name="suffix"/>
/// </summary>
/// <param name="suffix">The suffix value</param>
/// <param name="text">The string to check</param>
/// <returns>A string that has been striped of the suffix</returns>
/// <remarks>Copy of WebConvert.TryRemoveLiteralSuffix.</remarks>
private static bool TryRemoveLiteralSuffix(string suffix, ref string text)
{
Debug.Assert(text != null, "text != null");
Debug.Assert(suffix != null, "suffix != null");
text = text.Trim(WhitespaceChars);
if (text.Length <= suffix.Length || !text.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
else
{
text = text.Substring(0, text.Length - suffix.Length);
return true;
}
}
/// <summary>
/// Tries to remove a literal <paramref name="prefix"/> from the specified <paramref name="text"/>.
/// </summary>
/// <param name="prefix">Prefix to remove; one-letter prefixes are case-sensitive, others insensitive.</param>
/// <param name="text">Text to attempt to remove prefix from.</param>
/// <returns>true if the prefix was found and removed; false otherwise.</returns>
/// <remarks>Copy of WebConvert.TryRemoveLiteralPrefix.</remarks>
private static bool TryRemoveLiteralPrefix(string prefix, ref string text)
{
Debug.Assert(prefix != null, "prefix != null");
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
text = text.Remove(0, prefix.Length);
return true;
}
else
{
return false;
}
}
/// <summary>
/// Checks whether the specified text is a correctly formatted quoted value.
/// </summary>
/// <param name='text'>Text to check.</param>
/// <returns>true if the text is correctly formatted, false otherwise.</returns>
/// <remarks>Copy of WebConvert.IsKeyValueQuoted.</remarks>
private static bool IsUriValueQuoted(string text)
{
Debug.Assert(text != null, "text != null");
if (text.Length < 2 || text[0] != '\'' || text[text.Length - 1] != '\'')
{
return false;
}
else
{
int startIndex = 1;
while (startIndex < text.Length - 1)
{
int match = text.IndexOf('\'', startIndex, text.Length - startIndex - 1);
if (match == -1)
{
break;
}
else if (match == text.Length - 2 || text[match + 1] != '\'')
{
return false;
}
else
{
startIndex = match + 2;
}
}
return true;
}
}
/// <summary>
/// Removes quotes from the single-quotes text.
/// </summary>
/// <param name="text">Text to remove quotes from.</param>
/// <returns>The specified <paramref name="text"/> with single quotes removed.</returns>
/// <remarks>Copy of WebConvert.RemoveQuotes.</remarks>
private static string RemoveQuotes(string text)
{
Debug.Assert(!String.IsNullOrEmpty(text), "!String.IsNullOrEmpty(text)");
char quote = text[0];
Debug.Assert(quote == '\'', "quote == '\''");
Debug.Assert(text[text.Length - 1] == '\'', "text should end with '\''.");
string s = text.Substring(1, text.Length - 2);
int start = 0;
while (true)
{
int i = s.IndexOf(quote, start);
if (i < 0)
{
break;
}
Debug.Assert(i + 1 < s.Length && s[i + 1] == '\'', @"Each single quote should be propertly escaped with double single quotes.");
s = s.Remove(i, 1);
start = i + 1;
}
return s;
}
/// <summary>
/// Returns the 4 bits that correspond to the specified character.
/// </summary>
/// <param name="c">Character in the 0-F range to be converted.</param>
/// <returns>The 4 bits that correspond to the specified character.</returns>
/// <exception cref="FormatException">Thrown when 'c' is not in the '0'-'9','a'-'f' range.</exception>
/// <remarks>This is a copy of WebConvert.HexCharToNibble.</remarks>
private static byte HexCharToNibble(char c)
{
Debug.Assert(IsCharHexDigit(c), string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} is not a hex digit.", c));
switch (c)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.UriPrimitiveTypeParser_HexCharToNibble));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestAllZerosUInt64()
{
var test = new BooleanBinaryOpTest__TestAllZerosUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestAllZerosUInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int Op2ElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private BooleanBinaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static BooleanBinaryOpTest__TestAllZerosUInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
}
public BooleanBinaryOpTest__TestAllZerosUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new BooleanBinaryOpTest__DataTable<UInt64, UInt64>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestAllZeros(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestAllZeros(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestAllZeros(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestAllZeros(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse41.TestAllZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestAllZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestAllZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanBinaryOpTest__TestAllZerosUInt64();
var result = Sse41.TestAllZeros(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestAllZeros(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((left[i] & right[i]) == 0);
}
if (expectedResult != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestAllZeros)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections;
using System.Runtime.InteropServices;
using WbemClient_v1;
namespace System.Management
{
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Represents the set of methods available in the collection.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates enumerate all methods in a ManagementClass object.
/// class Sample_MethodDataCollection
/// {
/// public static int Main(string[] args) {
/// ManagementClass diskClass = new ManagementClass("win32_logicaldisk");
/// MethodDataCollection diskMethods = diskClass.Methods;
/// foreach (MethodData method in diskMethods) {
/// Console.WriteLine("Method = " + method.Name);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates enumerate all methods in a ManagementClass object.
/// Class Sample_MethodDataCollection
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("win32_logicaldisk")
/// Dim diskMethods As MethodDataCollection = diskClass.Methods
/// Dim method As MethodData
/// For Each method In diskMethods
/// Console.WriteLine("Method = " & method.Name)
/// Next method
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class MethodDataCollection : ICollection, IEnumerable
{
private ManagementObject parent;
private class enumLock
{
} //used to lock usage of BeginMethodEnum/NextMethod
internal MethodDataCollection(ManagementObject parent) : base()
{
this.parent = parent;
}
//
//ICollection
//
/// <summary>
/// <para>Represents the number of objects in the <see cref='System.Management.MethodDataCollection'/>.</para>
/// </summary>
/// <value>
/// <para> The number of objects in the <see cref='System.Management.MethodDataCollection'/>. </para>
/// </value>
public int Count
{
get
{
int i = 0;
IWbemClassObjectFreeThreaded inParameters = null, outParameters = null;
string methodName;
int status = (int)ManagementStatus.Failed;
lock(typeof(enumLock))
{
try
{
status = parent.wbemObject.BeginMethodEnumeration_(0);
if (status >= 0)
{
methodName = ""; // Condition primer to branch into the while loop.
while (methodName != null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA)
{
methodName = null; inParameters = null; outParameters = null;
status = parent.wbemObject.NextMethod_(0, out methodName, out inParameters, out outParameters);
if (status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA)
i++;
}
parent.wbemObject.EndMethodEnumeration_(); // Ignore status.
}
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
} // lock
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status);
}
return i;
}
}
/// <summary>
/// <para>Indicates whether the object is synchronized.</para>
/// </summary>
/// <value>
/// <para><see langword='true'/> if the object is synchronized;
/// otherwise, <see langword='false'/>.</para>
/// </value>
public bool IsSynchronized { get { return false; }
}
/// <summary>
/// <para>Represents the object to be used for synchronization.</para>
/// </summary>
/// <value>
/// <para>The object to be used for synchronization.</para>
/// </value>
public object SyncRoot { get { return this; }
}
/// <overload>
/// <para>Copies the <see cref='System.Management.MethodDataCollection'/> into an array.</para>
/// </overload>
/// <summary>
/// <para> Copies the <see cref='System.Management.MethodDataCollection'/> into an array.</para>
/// </summary>
/// <param name='array'>The array to which to copy the collection. </param>
/// <param name='index'>The index from which to start. </param>
public void CopyTo(Array array, int index)
{
//Use an enumerator to get the MethodData objects and attach them into the target array
foreach (MethodData m in this)
array.SetValue(m, index++);
}
/// <summary>
/// <para>Copies the <see cref='System.Management.MethodDataCollection'/> to a specialized <see cref='System.Management.MethodData'/>
/// array.</para>
/// </summary>
/// <param name='methodArray'>The destination array to which to copy the <see cref='System.Management.MethodData'/> objects.</param>
/// <param name=' index'>The index in the destination array from which to start the copy.</param>
public void CopyTo(MethodData[] methodArray, int index)
{
CopyTo((Array)methodArray, index);
}
//
// IEnumerable
//
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(new MethodDataEnumerator(parent));
}
/// <summary>
/// <para>Returns an enumerator for the <see cref='System.Management.MethodDataCollection'/>.</para>
/// </summary>
/// <remarks>
/// <para> Each call to this method
/// returns a new enumerator on the collection. Multiple enumerators can be obtained
/// for the same method collection. However, each enumerator takes a snapshot
/// of the collection, so changes made to the collection after the enumerator was
/// obtained are not reflected.</para>
/// </remarks>
/// <returns>An <see cref="System.Collections.IEnumerator"/> to enumerate through the collection.</returns>
public MethodDataEnumerator GetEnumerator()
{
return new MethodDataEnumerator(parent);
}
//Enumerator class
/// <summary>
/// <para>Represents the enumerator for <see cref='System.Management.MethodData'/>
/// objects in the <see cref='System.Management.MethodDataCollection'/>.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to enumerate all methods in
/// // Win32_LogicalDisk class using MethodDataEnumerator object.
///
/// class Sample_MethodDataEnumerator
/// {
/// public static int Main(string[] args)
/// {
/// ManagementClass diskClass = new ManagementClass("win32_logicaldisk");
/// MethodDataCollection.MethodDataEnumerator diskEnumerator =
/// diskClass.Methods.GetEnumerator();
/// while(diskEnumerator.MoveNext())
/// {
/// MethodData method = diskEnumerator.Current;
/// Console.WriteLine("Method = " + method.Name);
/// }
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates how to enumerate all methods in
/// ' Win32_LogicalDisk class using MethodDataEnumerator object.
///
/// Class Sample_MethodDataEnumerator
/// Overloads Public Shared Function Main(args() As String) As Integer
/// Dim diskClass As New ManagementClass("win32_logicaldisk")
/// Dim diskEnumerator As _
/// MethodDataCollection.MethodDataEnumerator = _
/// diskClass.Methods.GetEnumerator()
/// While diskEnumerator.MoveNext()
/// Dim method As MethodData = diskEnumerator.Current
/// Console.WriteLine("Method = " & method.Name)
/// End While
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
public class MethodDataEnumerator : IEnumerator
{
private ManagementObject parent;
private ArrayList methodNames; //can't use simple array because we don't know the size...
private IEnumerator en;
//Internal constructor
//Because WMI doesn't provide a "GetMethodNames" for methods similar to "GetNames" for properties,
//We have to walk the methods list and cache the names here.
//We lock to ensure that another thread doesn't interfere in the Begin/Next sequence.
internal MethodDataEnumerator(ManagementObject parent)
{
this.parent = parent;
methodNames = new ArrayList();
IWbemClassObjectFreeThreaded inP = null, outP = null;
string tempMethodName;
int status = (int)ManagementStatus.Failed;
lock(typeof(enumLock))
{
try
{
status = parent.wbemObject.BeginMethodEnumeration_(0);
if (status >= 0)
{
tempMethodName = ""; // Condition primer to branch into the while loop.
while (tempMethodName != null && status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA)
{
tempMethodName = null;
status = parent.wbemObject.NextMethod_(0, out tempMethodName, out inP, out outP);
if (status >= 0 && status != (int)tag_WBEMSTATUS.WBEM_S_NO_MORE_DATA)
methodNames.Add(tempMethodName);
}
parent.wbemObject.EndMethodEnumeration_(); // Ignore status.
}
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
en = methodNames.GetEnumerator();
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status);
}
}
/// <internalonly/>
object IEnumerator.Current { get { return (object)this.Current; } }
/// <summary>
/// <para>Returns the current <see cref='System.Management.MethodData'/> in the <see cref='System.Management.MethodDataCollection'/>
/// enumeration.</para>
/// </summary>
/// <value>The current <see cref='System.Management.MethodData'/> item in the collection.</value>
public MethodData Current
{
get
{
return new MethodData(parent, (string)en.Current);
}
}
/// <summary>
/// <para>Moves to the next element in the <see cref='System.Management.MethodDataCollection'/> enumeration.</para>
/// </summary>
/// <returns><see langword='true'/> if the enumerator was successfully advanced to the next method; <see langword='false'/> if the enumerator has passed the end of the collection.</returns>
public bool MoveNext ()
{
return en.MoveNext();
}
/// <summary>
/// <para>Resets the enumerator to the beginning of the <see cref='System.Management.MethodDataCollection'/> enumeration.</para>
/// </summary>
public void Reset()
{
en.Reset();
}
}//MethodDataEnumerator
//
//Methods
//
/// <summary>
/// <para>Returns the specified <see cref='System.Management.MethodData'/> from the <see cref='System.Management.MethodDataCollection'/>.</para>
/// </summary>
/// <param name='methodName'>The name of the method requested.</param>
/// <value>A <see cref='System.Management.MethodData'/> instance containing all information about the specified method.</value>
public virtual MethodData this[string methodName]
{
get
{
if (null == methodName)
throw new ArgumentNullException ("methodName");
return new MethodData(parent, methodName);
}
}
/// <summary>
/// <para>Removes a <see cref='System.Management.MethodData'/> from the <see cref='System.Management.MethodDataCollection'/>.</para>
/// </summary>
/// <param name='methodName'>The name of the method to remove from the collection.</param>
/// <remarks>
/// <para>
/// Removing <see cref='System.Management.MethodData'/> objects from the <see cref='System.Management.MethodDataCollection'/>
/// can only be done when the class has no
/// instances. Any other case will result in an exception.</para>
/// </remarks>
public virtual void Remove(string methodName)
{
if (parent.GetType() == typeof(ManagementObject)) //can't remove methods from instance
throw new InvalidOperationException();
int status = (int)ManagementStatus.Failed;
try
{
status = parent.wbemObject.DeleteMethod_(methodName);
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status);
}
}
//This variant takes only a method name and assumes a void method with no in/out parameters
/// <overload>
/// <para>Adds a <see cref='System.Management.MethodData'/> to the <see cref='System.Management.MethodDataCollection'/>.</para>
/// </overload>
/// <summary>
/// <para>Adds a <see cref='System.Management.MethodData'/> to the <see cref='System.Management.MethodDataCollection'/>. This overload will
/// add a new method with no parameters to the collection.</para>
/// </summary>
/// <param name='methodName'>The name of the method to add.</param>
/// <remarks>
/// <para> Adding <see cref='System.Management.MethodData'/> objects to the <see cref='System.Management.MethodDataCollection'/> can only
/// be done when the class has no instances. Any other case will result in an
/// exception.</para>
/// </remarks>
public virtual void Add(string methodName)
{
Add(methodName, null, null);
}
//This variant takes the full information, i.e. the method name and in & out param objects
/// <summary>
/// <para>Adds a <see cref='System.Management.MethodData'/> to the <see cref='System.Management.MethodDataCollection'/>. This overload will add a new method with the
/// specified parameter objects to the collection.</para>
/// </summary>
/// <param name='methodName'>The name of the method to add.</param>
/// <param name=' inParameters'>The <see cref='System.Management.ManagementBaseObject'/> holding the input parameters to the method.</param>
/// <param name=' outParameters'>The <see cref='System.Management.ManagementBaseObject'/> holding the output parameters to the method.</param>
/// <remarks>
/// <para> Adding <see cref='System.Management.MethodData'/> objects to the <see cref='System.Management.MethodDataCollection'/> can only be
/// done when the class has no instances. Any other case will result in an
/// exception.</para>
/// </remarks>
public virtual void Add(string methodName, ManagementBaseObject inParameters, ManagementBaseObject outParameters)
{
IWbemClassObjectFreeThreaded wbemIn = null, wbemOut = null;
if (parent.GetType() == typeof(ManagementObject)) //can't add methods to instance
throw new InvalidOperationException();
if (inParameters != null)
wbemIn = inParameters.wbemObject;
if (outParameters != null)
wbemOut = outParameters.wbemObject;
int status = (int)ManagementStatus.Failed;
try
{
status = parent.wbemObject.PutMethod_(methodName, 0, wbemIn, wbemOut);
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status);
}
}
}//MethodDataCollection
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.InlineDeclaration;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration
{
public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariable1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineInNestedCall()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (Foo(int.TryParse(v, out i)))
{
}
}
}",
@"class C
{
void M()
{
if (Foo(int.TryParse(v, out int i)))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableWithConstructor1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (new C1(v, out i))
{
}
}
}",
@"class C
{
void M()
{
if (new C1(v, out int i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableMissingWithIndexer1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (this[out i])
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableIntoFirstOut1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableIntoFirstOut2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInCSharp6()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariablePreferVar1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(string v)
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M(string v)
{
if (int.TryParse(v, out var i))
{
}
}
}", options: new UseImplicitTypeTests().ImplicitTypeEverywhere());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariablePreferVarExceptForPredefinedTypes1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(string v)
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M(string v)
{
if (int.TryParse(v, out int i))
{
}
}
}", options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableWhenWrittenAfter1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
i = 0;
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
i = 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWhenWrittenBetween1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
i = 0;
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWhenReadBetween1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
M1(i);
if (int.TryParse(v, out i))
{
}
}
void M1(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWithComplexInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = M1();
if (int.TryParse(v, out i))
{
}
}
int M1()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableInOuterScopeIfNotWrittenOutside()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
if (int.TryParse(v, out i))
{
}
i = 1;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfWrittenAfterInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
if (int.TryParse(v, out i))
{
}
}
i = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfWrittenBetweenInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
i = 1;
if (int.TryParse(v, out i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInNonOut()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInField()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[|int|] i;
void M()
{
if (int.TryParse(v, out this.i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInField2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[|int|] i;
void M()
{
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInNonLocalStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
foreach ([|int|] i in e)
{
if (int.TryParse(v, out i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInEmbeddedStatementWithWriteAfterwards()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
while (true)
if (int.TryParse(v, out i))
{
}
i = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInEmbeddedStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
while (true)
if (int.TryParse(v, out i))
{
i = 1;
}
}
}",
@"class C
{
void M()
{
while (true)
if (int.TryParse(v, out int i))
{
i = 1;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableInNestedBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
while (true)
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
while (true)
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestOverloadResolutionDoNotUseVar1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (M2(out i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}", options: new UseImplicitTypeTests().ImplicitTypeEverywhere());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestOverloadResolutionDoNotUseVar2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|var|] i = 0;
if (M2(out i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}", options: new UseImplicitTypeTests().ImplicitTypeEverywhere());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestGenericInferenceDoNotUseVar3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (M2(out i))
{
}
}
void M2<T>(out T i)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2<T>(out T i)
{
}
}", options: new UseImplicitTypeTests().ImplicitTypeEverywhere());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// prefix comment
[|int|] i;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i; // suffix comment
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// suffix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// prefix comment
[|int|] i; // suffix comment
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix comment
// suffix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments4()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
int [|i|] /*suffix*/, j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int i /*suffix*/))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments5()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
int /*prefix*/ [|i|], j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments6()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
int /*prefix*/ [|i|] /*suffix*/, j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments7()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
int j, /*prefix*/ [|i|] /*suffix*/;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments8()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// prefix
int j, [|i|]; // suffix
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix
int j; // suffix
{
if (int.TryParse(v, out int i))
{
}
}
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments9()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
int /*int comment*/
/*prefix*/ [|i|] /*suffix*/,
j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int /*int comment*/
j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}", ignoreTrivia: false);
}
[WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestCommentsTrivia1()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Foo"");
int [|result|];
if (int.TryParse(""12"", out result))
{
}
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Foo"");
if (int.TryParse(""12"", out int result))
{
}
}
}", ignoreTrivia: false);
}
[WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestCommentsTrivia2()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Foo"");
// Foo
int [|result|];
if (int.TryParse(""12"", out result))
{
}
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Foo"");
// Foo
if (int.TryParse(""12"", out int result))
{
}
}
}", ignoreTrivia: false);
}
[WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards()
{
await TestInRegularAndScriptAsync(
@"
using System;
class C
{
void M()
{
string [|s|];
Bar(() => Baz(out s));
}
void Baz(out string s) { }
void Bar(Action a) { }
}",
@"
using System;
class C
{
void M()
{
Bar(() => Baz(out string s));
}
void Baz(out string s) { }
void Bar(Action a) { }
}");
}
[WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void M()
{
string [|s|];
Bar(() => Baz(out s));
Console.WriteLine(s);
}
void Baz(out string s) { }
void Bar(Action a) { }
}");
}
[WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDataFlow1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void Foo(string x)
{
object [|s|] = null;
if (x != null || TryBaz(out s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDataFlow2()
{
await TestInRegularAndScriptAsync(
@"
using System;
class C
{
void Foo(string x)
{
object [|s|] = null;
if (x != null && TryBaz(out s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
void Foo(string x)
{
if (x != null && TryBaz(out object s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(16028, "https://github.com/dotnet/roslyn/issues/16028")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestExpressionTree1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
int [|result|];
Method(() => GetValue(out result));
}
public static void GetValue(out int result)
{
result = 0;
}
public static void Method(Expression<Action> expression)
{
}
}");
}
[WorkItem(16198, "https://github.com/dotnet/roslyn/issues/16198")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestIndentation1()
{
await TestInRegularAndScriptAsync(
@"
using System;
class C
{
private int Bar()
{
IProjectRuleSnapshot [|unresolvedReferenceSnapshot|] = null;
var itemType = GetUnresolvedReferenceItemType(originalItemSpec,
updatedUnresolvedSnapshots,
catalogs,
out unresolvedReferenceSnapshot);
}
}",
@"
using System;
class C
{
private int Bar()
{
var itemType = GetUnresolvedReferenceItemType(originalItemSpec,
updatedUnresolvedSnapshots,
catalogs,
out IProjectRuleSnapshot unresolvedReferenceSnapshot);
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops1()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
do
{
}
while (!TryExtractTokenFromEmail(out token));
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops2()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
while (!TryExtractTokenFromEmail(out token))
{
}
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops3()
{
await TestMissingAsync(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
foreach (var v in TryExtractTokenFromEmail(out token))
{
}
Console.WriteLine(token == ""Test"");
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops4()
{
await TestMissingAsync(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
for ( ; TryExtractTokenFromEmail(out token); )
{
}
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInUsing()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
using (GetDisposableAndValue(out token))
{
}
Console.WriteLine(token);
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInExceptionFilter()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
try
{
}
catch when (GetValue(out token))
{
}
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInShortCircuitExpression1()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|] = null;
bool condition = false && GetValue(out token);
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInShortCircuitExpression2()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
bool condition = false && GetValue(out token);
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInFixed()
{
await TestMissingAsync(
@"
using System;
class C
{
static unsafe void Main(string[] args)
{
string [|token|];
fixed (int* p = GetValue(out token))
{
}
Console.WriteLine(token);
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
do
{
}
while (!TryExtractTokenFromEmail(out token));
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
do
{
}
while (!TryExtractTokenFromEmail(out string token));
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
while (!TryExtractTokenFromEmail(out token))
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
while (!TryExtractTokenFromEmail(out string token))
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/17635"),
Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops3()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
foreach (var v in TryExtractTokenFromEmail(out token))
{
}
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
foreach (var v in TryExtractTokenFromEmail(out string token))
{
}
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops4()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
for ( ; TryExtractTokenFromEmail(out token); )
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
for ( ; TryExtractTokenFromEmail(out string token); )
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInUsing()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
using (GetDisposableAndValue(out token))
{
}
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
using (GetDisposableAndValue(out string token))
{
}
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInExceptionFilter()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
try
{
}
catch when (GetValue(out token))
{
}
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
try
{
}
catch when (GetValue(out string token))
{
}
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInShortCircuitExpression1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|] = null;
bool condition = false && GetValue(out token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
bool condition = false && GetValue(out string token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInShortCircuitExpression2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
bool condition = false && GetValue(out token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
bool condition = false && GetValue(out string token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInFixed()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
fixed (int* p = GetValue(out token))
{
}
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
fixed (int* p = GetValue(out string token))
{
}
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17743, "https://github.com/dotnet/roslyn/issues/17743")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLocalFunction()
{
// Note: this currently works, but it should be missing.
// This test validates that we don't crash in this case though.
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
int [|x|] = 0;
dict?.TryGetValue(0, out x);
Console.WriteLine(x);
};
}
}
}",
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
dict?.TryGetValue(0, out int x);
Console.WriteLine(x);
};
}
}
}");
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine1()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Foo()
{
string a; string [|b|];
Method(out a, out b);
}
}",
@"
class C
{
void Foo()
{
string a;
Method(out a, out string b);
}
}", ignoreTrivia: false);
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine2()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Foo()
{
string a; /*leading*/ string [|b|]; // trailing
Method(out a, out b);
}
}",
@"
class C
{
void Foo()
{
string a; /*leading*/ // trailing
Method(out a, out string b);
}
}", ignoreTrivia: false);
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine3()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Foo()
{
string a;
/*leading*/ string [|b|]; // trailing
Method(out a, out b);
}
}",
@"
class C
{
void Foo()
{
string a;
/*leading*/ // trailing
Method(out a, out string b);
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnUnderscore()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void M()
{
[|int|] _;
if (N(out _)
{
Console.WriteLine(_);
}
}
}");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace l2pvp
{
class LoginCryptServer
{
private static byte[] STATIC_BLOWFISH_KEY =
{
(byte) 0x6b, (byte) 0x60, (byte) 0xcb, (byte) 0x5b,
(byte) 0x82, (byte) 0xce, (byte) 0x90, (byte) 0xb1,
(byte) 0xcc, (byte) 0x2b, (byte) 0x6c, (byte) 0x55,
(byte) 0x6c, (byte) 0x6c, (byte) 0x6c, (byte) 0x6c
};
private NewCrypt _staticCrypt = new NewCrypt(STATIC_BLOWFISH_KEY);
private NewCrypt _crypt;
public Boolean _static = true;
protected int _key;
Random x;
public void setKey(byte[] key)
{
_crypt = new NewCrypt(key);
x = new Random();
_key = x.Next();
}
public Boolean decrypt(byte[] raw, int offset, int size)
{
_crypt.decrypt(raw, offset, size);
return NewCrypt.verifyChecksum(raw, offset, size);
}
public int encrypt(byte[] raw, int offset, int size)
{
// reserve checksum
size += 4;
if (_static)
{
// reserve for XOR "key"
size += 4;
// padding
size += 8 - size % 8;
NewCrypt.encXORPass(raw, offset, size, _key);
_staticCrypt.crypt(raw, offset, size);
_static = false;
}
else
{
// padding
size += 8 - size % 8;
NewCrypt.appendChecksum(raw, offset, size);
_crypt.crypt(raw, offset, size);
}
return size;
}
}
class LoginCryptClient
{
private static byte[] STATIC_BLOWFISH_KEY =
{
(byte) 0x6b, (byte) 0x60, (byte) 0xcb, (byte) 0x5b,
(byte) 0x82, (byte) 0xce, (byte) 0x90, (byte) 0xb1,
(byte) 0xcc, (byte) 0x2b, (byte) 0x6c, (byte) 0x55,
(byte) 0x6c, (byte) 0x6c, (byte) 0x6c, (byte) 0x6c
};
private NewCrypt _staticCrypt = new NewCrypt(STATIC_BLOWFISH_KEY);
private NewCrypt _crypt;
private Boolean _static = true;
public void setKey(byte[] key)
{
_crypt = new NewCrypt(key);
}
public Boolean decrypt(byte[] raw, int offset, int size)
{
if (_static)
{
_staticCrypt.decrypt(raw, offset, size);
NewCrypt.decXORPass(raw, offset, size);
_static = false;
return true;
}
else
{
_crypt.decrypt(raw, offset, size);
return NewCrypt.verifyChecksum(raw, offset, size);
}
}
public int encrypt(byte[] raw, int offset, int size)
{
NewCrypt.appendChecksum(raw, offset, size);
_crypt.crypt(raw, offset, size);
return size;
}
}
public class NewCrypt
{
BlowfishEngine _crypt;
BlowfishEngine _decrypt;
/**
* @param blowfishKey
*/
public NewCrypt(byte[] blowfishKey)
{
_crypt = new BlowfishEngine();
_crypt.init(true, blowfishKey);
_decrypt = new BlowfishEngine();
_decrypt.init(false, blowfishKey);
}
//public NewCrypt(String key)
//{
// this(key.getBytes());
//}
public static Boolean verifyChecksum(byte[] raw)
{
return NewCrypt.verifyChecksum(raw, 0, raw.Length);
}
public static Boolean verifyChecksum(byte[] raw, int offset, int size)
{
// check if size is multiple of 4 and if there is more then only the checksum
if ((size & 3) != 0 || size <= 4)
{
return false;
}
long chksum = 0;
int count = size - 4;
long check = -1;
int i;
for (i = offset; i < count; i += 4)
{
check = raw[i] & 0xff;
check |= raw[i + 1] << 8 & 0xff00;
check |= raw[i + 2] << 0x10 & 0xff0000;
check |= raw[i + 3] << 0x18 & 0xff000000;
chksum ^= check;
}
check = raw[i] & 0xff;
check |= raw[i + 1] << 8 & 0xff00;
check |= raw[i + 2] << 0x10 & 0xff0000;
check |= raw[i + 3] << 0x18 & 0xff000000;
return check == chksum;
}
public static void appendChecksum(byte[] raw)
{
NewCrypt.appendChecksum(raw, 0, raw.Length);
}
public static void appendChecksum(byte[] raw, int offset, int size)
{
long chksum = 0;
int count = size - 4;
long ecx;
int i;
for (i = offset; i < count; i += 4)
{
ecx = raw[i] & 0xff;
ecx |= raw[i + 1] << 8 & 0xff00;
ecx |= raw[i + 2] << 0x10 & 0xff0000;
ecx |= raw[i + 3] << 0x18 & 0xff000000;
chksum ^= ecx;
}
ecx = raw[i] & 0xff;
ecx |= raw[i + 1] << 8 & 0xff00;
ecx |= raw[i + 2] << 0x10 & 0xff0000;
ecx |= raw[i + 3] << 0x18 & 0xff000000;
raw[i] = (byte)(chksum & 0xff);
raw[i + 1] = (byte)(chksum >> 0x08 & 0xff);
raw[i + 2] = (byte)(chksum >> 0x10 & 0xff);
raw[i + 3] = (byte)(chksum >> 0x18 & 0xff);
}
/**
* Packet is first XOR encoded with <code>key</code>
* Then, the last 4 bytes are overwritten with the the XOR "key".
* Thus this assume that there is enough room for the key to fit without overwriting data.
* @param raw The raw bytes to be encrypted
* @param key The 4 bytes (int) XOR key
*/
public static void encXORPass(byte[] raw, int key)
{
NewCrypt.encXORPass(raw, 0, raw.Length, key);
}
public static void decXORPass(byte[] raw, int offset, int size)
{
int keystart = size - 8;
int edx;
int ecx = raw[keystart] & 0xFF;
ecx |= (raw[keystart + 1] & 0xFF) << 8;
ecx |= (raw[keystart + 2] & 0xFF) << 16;
ecx |= (raw[keystart + 3] & 0xFF) << 24;
int pos = keystart;
while (pos > 4 + offset)
{
edx = raw[pos - 4] & 0xFF;
edx |= (raw[pos - 3] & 0xFF) << 8;
edx |= (raw[pos - 2] & 0xFF) << 16;
edx |= (raw[pos - 1] & 0xFF) << 24;
edx ^= ecx;
ecx -= edx;
raw[pos - 4] = (byte)(edx & 0xFF);
raw[pos - 3] = (byte)(edx >> 8 & 0xFF);
raw[pos - 2] = (byte)(edx >> 16 & 0xFF);
raw[pos - 1] = (byte)(edx >> 24 & 0xFF);
pos -= 4;
}
}
/**
* Packet is first XOR encoded with <code>key</code>
* Then, the last 4 bytes are overwritten with the the XOR "key".
* Thus this assume that there is enough room for the key to fit without overwriting data.
* @param raw The raw bytes to be encrypted
* @param offset The begining of the data to be encrypted
* @param size Length of the data to be encrypted
* @param key The 4 bytes (int) XOR key
*/
public static void encXORPass(byte[] raw, int offset, int size, int key)
{
int stop = size - 8;
int pos = 4 + offset;
int edx;
int ecx = key; // Initial xor key
while (pos < stop)
{
edx = (raw[pos] & 0xFF);
edx |= (raw[pos + 1] & 0xFF) << 8;
edx |= (raw[pos + 2] & 0xFF) << 16;
edx |= (raw[pos + 3] & 0xFF) << 24;
ecx += edx;
edx ^= ecx;
raw[pos++] = (byte)(edx & 0xFF);
raw[pos++] = (byte)(edx >> 8 & 0xFF);
raw[pos++] = (byte)(edx >> 16 & 0xFF);
raw[pos++] = (byte)(edx >> 24 & 0xFF);
}
raw[pos++] = (byte)(ecx & 0xFF);
raw[pos++] = (byte)(ecx >> 8 & 0xFF);
raw[pos++] = (byte)(ecx >> 16 & 0xFF);
raw[pos++] = (byte)(ecx >> 24 & 0xFF);
}
public byte[] decrypt(byte[] raw)
{
byte[] result = new byte[raw.Length];
uint count = (uint)raw.Length / 8;
for (uint i = 0; i < count; i++)
{
_decrypt.processBlock(raw, i * 8, result, i * 8);
}
return result;
}
public void decrypt(byte[] raw, int offset, int size)
{
byte[] result = new byte[size];
uint count = (uint)size / 8;
for (uint i = 0; i < count; i++)
{
_decrypt.processBlock(raw, (uint)offset + i * 8, result, i * 8);
}
// TODO can the crypt and decrypt go direct to the array
Array.Copy(result, 0, raw, offset, size);
}
public byte[] crypt(byte[] raw)
{
uint count = (uint)raw.Length / 8;
byte[] result = new byte[raw.Length];
for (uint i = 0; i < count; i++)
{
_crypt.processBlock(raw, i * 8, result, i * 8);
}
return result;
}
public void crypt(byte[] raw, int offset, int size)
{
uint count = (uint)size / 8;
byte[] result = new byte[size];
for (uint i = 0; i < count; i++)
{
_crypt.processBlock(raw, (uint)offset + i * 8, result, i * 8);
}
// TODO can the crypt and decrypt go direct to the array
Array.Copy(result, 0, raw, offset, size);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
namespace l2pvp
{
public partial class Skills : Form
{
Client c;
GameServer gs;
public Skills(Client _c, GameServer _gs)
{
InitializeComponent();
c = _c;
gs = _gs;
condition.Items.Add("Always");
condition.Items.Add("HP");
condition.Items.Add("Distance");
compare.Items.Add("=");
compare.Items.Add(">");
compare.Items.Add("<");
condition.SelectedIndex = 0;
compare.SelectedIndex = 0;
value.Text = "0";
//skill s = new skill();
//s.name = "fuck";
//s.id = 12203;
//skill s1 = new skill();
//s1.name = "suck";
//s1.id = 12205;
//skill s2 = new skill();
//s2.name = "duck";
//s2.id = 12204;
//sl.Items.Add(s1);
//sl.Items.Add(s2);
//sl.Items.Add(s);
}
public void populateskilllist_d(List<uint> skilllist)
{
if (this.InvokeRequired)
Invoke(new poplist(populateskilllist), new object[] { skilllist });
else
populateskilllist(skilllist);
}
public delegate void poplist(List<uint> skilllist);
public void populateskilllist(List<uint> skilllist)
{
sl.Items.Clear();
string skillname;
foreach (uint i in skilllist)
{
if (gs.skills.ContainsKey(i))
{
skillname = gs.skills[i];
if (skillname != null)
{
//found skill
skill s = new skill();
s.name = skillname;
s.id = i;
sl.Items.Add(s);
}
}
}
}
private void Skills_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//add to listview
AttackSkills askill = new AttackSkills();
askill.comparison = compare.SelectedIndex;
askill.condition = condition.SelectedIndex;
int index = sl.SelectedIndex;
if (index != -1)
{
askill.skillname = sl.Items[sl.SelectedIndex].ToString();
askill.skillid = ((skill)sl.Items[sl.SelectedIndex]).id;
}
else
return;
try
{
askill.value = Convert.ToInt32(value.Text);
}
catch
{
askill.value = 0;
}
ListViewItem item = new ListViewItem(askill.skillname);
item.SubItems.Add(condition.Items[askill.condition].ToString());
item.SubItems.Add(compare.Items[askill.comparison].ToString());
item.SubItems.Add(askill.value.ToString());
item.Tag = askill;
listView1.Items.Add(item);
}
private void button3_Click(object sender, EventArgs e)
{
lock (c.aslock)
{
c.askills.Clear();
foreach (ListViewItem item in listView1.Items)
{
c.askills.Add((AttackSkills)item.Tag);
}
}
this.Hide();
}
private void button4_Click(object sender, EventArgs e)
{
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection ic = listView1.SelectedItems;
foreach (ListViewItem i in ic)
{
listView1.Items.Remove(i);
}
}
private void button5_Click(object sender, EventArgs e)
{
string fname = textBox2.Text;
fname = "skills-" + fname;
StreamReader readfile;
try
{
readfile = new StreamReader(new FileStream(fname, FileMode.Open), Encoding.UTF8);
if (readfile == null)
return;
}
catch
{
MessageBox.Show("couldn't open file {0} for reading", fname);
return;
}
string line;
int count;
line = readfile.ReadLine();
try
{
count = Convert.ToInt32(line);
}
catch
{
count = 0;
}
listView1.Items.Clear();
for (int i = 0; i < count; i++)
{
try
{
line = readfile.ReadLine();
string[] items = line.Split(',');
AttackSkills askill = new AttackSkills();
askill.skillid = Convert.ToUInt32(items[0]);
askill.condition = Convert.ToInt32(items[1]);
askill.comparison = Convert.ToInt32(items[2]);
askill.value = Convert.ToInt32(items[3]);
askill.skillname = gs.skills[askill.skillid];
ListViewItem item = new ListViewItem(askill.skillname);
item.SubItems.Add(condition.Items[askill.condition].ToString());
item.SubItems.Add(compare.Items[askill.comparison].ToString());
item.SubItems.Add(askill.value.ToString());
item.Tag = askill;
listView1.Items.Add(item);
}
catch
{
}
}
}
private void button6_Click(object sender, EventArgs e)
{
//file format
//Count
//<skill id> <condition id> <comparison id> <value>
string fname = textBox2.Text;
fname = "skills-"+fname;
StreamWriter writefile = new StreamWriter(new FileStream(fname, FileMode.Create), Encoding.UTF8);
int count = listView1.Items.Count;
writefile.WriteLine(count.ToString());
foreach(ListViewItem i in listView1.Items)
{
AttackSkills a = (AttackSkills)i.Tag;
writefile.WriteLine("{0},{1},{2},{3}",
a.skillid, a.condition, a.comparison, a.value);
}
writefile.Flush();
writefile.Close();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.IO;
using MediaServer.Utility;
namespace MediaServer.Media.Nodes
{
public class iTunesFolderNode : FolderNode
{
private readonly string _source;
private readonly FileSystemWatcher _watcher = new FileSystemWatcher();
private readonly Configuration.RemapConfiguration _remap;
public iTunesFolderNode(FolderNode parentNode, string title, string source, Configuration.RemapConfiguration remap)
: base(parentNode, title)
{
_source = source;
_remap = remap;
//_watcher.IncludeSubdirectories = false;
//_watcher.Path = Path.GetDirectoryName(_source);
//_watcher.Filter = Path.GetFileName(_source);
//_watcher.EnableRaisingEvents = false;
//_watcher.NotifyFilter = NotifyFilters.LastWrite;
//_watcher.Changed += OnChanged;
ProcessFileInBackground(_source);
}
private void ProcessFileInBackground(string path)
{
var parseCommand = new Action<string>(ParseiTunesFile);
parseCommand.BeginInvoke(path, parseCommand.EndInvoke, null);
}
//private void OnChanged(object sender, FileSystemEventArgs args)
//{
// _watcher.EnableRaisingEvents = false;
// foreach(var item in this)
// {
// item.RemoveFromIndexes();
// }
// Clear();
// ProcessFileInBackground(_source);
//}
private static IEnumerable<IGrouping<string,XElement>> GetGroupings(XContainer source, string type)
{
var query =
from item in source.Descendants("Track")
let elem = item.Element(type)
where elem != null
group item by elem.Value
into g
orderby g.Key
select g;
return query;
}
private static object MergeTrees(string value, IDictionary<string,XElement> songs)
{
if (!value.StartsWith("Track ID"))
{
return value;
}
return value.Replace("Track ID", " ").Trim().Split(' ')
.Where(songs.ContainsKey)
.Select(item => songs[item])
.OrderBy(item => (string)item.Element("Album"))
.ThenBy(item => (string)item.Element("TrackNumber"));
}
private void AddSubFolder(FolderNode root, XContainer source, string type)
{
var name = type + "s";
var newFolder = new FolderNode(root, name);
root.Add(newFolder);
var group = GetGroupings(source, type);
foreach(var item in group)
{
AddMedia(newFolder, item.Key, item);
}
}
private void AddMedia(FolderNode root, string newFolderName, IEnumerable<XElement> source)
{
var newFolder = new FolderNode(root, newFolderName);
root.Add(newFolder);
foreach(var track in source)
{
var loc = (string)track.Element("Location");
if (!String.IsNullOrEmpty(loc))
{
var uri = new Uri(loc);
var path = uri.LocalPath;
if (String.IsNullOrEmpty(UpnpTypeLookup.GetUpnpType(path))) continue;
var title = (string)track.Element("Name");
var file = !String.IsNullOrEmpty(title) ? FileNode.Create(newFolder, title, path.Replace(_remap.Source, _remap.Destination)) :
FileNode.Create(newFolder, Path.GetFileNameWithoutExtension(path), path.Replace(_remap.Source, _remap.Destination));
newFolder.Add(file);
var avfile = file as AvFileNode;
if (avfile != null)
{
var dur = (string)track.Element("TotalTime");
if (!String.IsNullOrEmpty(dur))
{
avfile.Duration = TimeSpan.FromMilliseconds(int.Parse(dur));
}
var br = (string)track.Element("BitRate");
if (!String.IsNullOrEmpty(br))
{
avfile.Bitrate = uint.Parse(br) * 1000;
}
}
var mfile = file as MusicNode;
if (mfile != null)
{
var sr = (string)track.Element("SampleRate");
if (!String.IsNullOrEmpty(sr))
{
mfile.SampleFrequencyHz = uint.Parse(sr);
}
}
var vfile = file as MovieNode;
if (vfile != null)
{
var w = (string)track.Element("VideoWidth");
if (!String.IsNullOrEmpty(w))
{
vfile.Width = uint.Parse(w);
}
var h = (string)track.Element("VideoHeight");
if (!String.IsNullOrEmpty(h))
{
vfile.Height = uint.Parse(h);
}
}
}
}
}
private void ParseiTunesFile(string location)
{
//Logger.Instance.Debug("parsing itunes");
try
{
if (!File.Exists(location)) return;
var doc = XElement.Load(location);
var songs = new Dictionary<string,XElement>();
var root = doc.Element("dict");
if (root == null) return;
var nextroot = root.Element("dict");
if (nextroot == null) return;
var rawTracks =
from track in nextroot.Elements("dict")
select new XElement(
"Track",
from key in track.Elements("key")
let name = ((string) key).Replace(" ", "")
let value = (string) (XElement) key.NextNode
select new XElement(name, value));
var useableElements =
from item in rawTracks
where (string)item.Element("Kind") != "MPEG audio stream" &&
item.Element("Protected") == null
select item;
foreach(var item in useableElements)
{
var id = (string)item.Element("TrackID");
if (!String.IsNullOrEmpty(id))
{
songs[id] = item;
}
}
var thirdroot = root.Element("array");
if (thirdroot == null) return;
var rawPlaylists =
(from playlist in thirdroot.Elements("dict")
select new XElement(
"Playlist",
from key in playlist.Elements("key")
let name = ((string) key).Replace(" ", "")
let nextnode = (XElement) key.NextNode
where name == "Name" || name == "PlaylistItems"
select new XElement(name, MergeTrees((string) nextnode, songs)))
).ToList();
var musicPlaylist =
(from item in rawPlaylists
let name = (string)item.Element("Name")
where name == "Music"
select item).First();
var musicFolder = new FolderNode(this, "Music");
Add(musicFolder);
AddSubFolder(musicFolder, musicPlaylist, "Artist");
AddSubFolder(musicFolder, musicPlaylist, "Album");
AddSubFolder(musicFolder, musicPlaylist, "Composer");
AddSubFolder(musicFolder, musicPlaylist, "Genre");
AddMedia(musicFolder, "Songs", musicPlaylist.Descendants("Track"));
var playlistFolder = new FolderNode(musicFolder, "Playlists");
Add(playlistFolder);
var ignoredPlaylists = new []{"Music", "Library", "Audiobooks", "Genius", "iTunes DJ", "Purchased"};
var filteredPlaylists =
from item in rawPlaylists
let name = (string)item.Element("Name")
where !String.IsNullOrEmpty(name) && !ignoredPlaylists.Contains(name)
orderby name
select item;
foreach(var item in filteredPlaylists)
{
var name = (string)item.Element("Name");
var tracks = item.Descendants("Track");
switch(name)
{
case "Movies":
case "TV Shows":
case "Podcasts":
case "iTunes U":
AddMedia(this, name, tracks);
break;
default:
AddMedia(playlistFolder, name, tracks);
break;
}
}
}
catch (Exception ex)
{
Logger.Instance.Exception("Error parsing itunes xml", ex);
throw;
}
finally
{
_watcher.EnableRaisingEvents = true;
//Logger.Instance.Debug("done parsing itunes");
}
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Licence...
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;
using WixSharp;
using WixSharp.Controls;
using IO = System.IO;
namespace WixSharp.CommonTasks
{
/// <summary>
///
/// </summary>
public static partial class Tasks
{
/// <summary>
/// Builds the bootstrapper.
/// </summary>
/// <param name="prerequisiteFile">The prerequisite file.</param>
/// <param name="primaryFile">The primary setup file.</param>
/// <param name="outputFile">The output (bootsrtapper) file.</param>
/// <param name="prerequisiteRegKeyValue">The prerequisite registry key value.
/// <para>This value is used to determine if the <c>PrerequisiteFile</c> should be launched.</para>
/// <para>This value must comply with the following pattern: <RegistryHive>:<KeyPath>:<ValueName>.</para>
/// <code>PrerequisiteRegKeyValue = @"HKLM:Software\My Company\My Product:Installed";</code>
/// Existence of the specified registry value at runtime is interpreted as an indication of the <c>PrerequisiteFile</c> has been alreday installed.
/// Thus bootstrapper will execute <c>PrimaryFile</c> without launching <c>PrerequisiteFile</c> first.</param>
/// <param name="doNotPostVerifyPrerequisite">The flag which allows you to disable verification of <c>PrerequisiteRegKeyValue</c> after the prerequisite setup is completed.
/// <para>Normally if <c>bootstrapper</c> checks if <c>PrerequisiteRegKeyValue</c>/> exists straight after the prerequisite installation and starts
/// the primary setup only if it does.</para>
/// <para>It is possible to instruct bootstrapper to continue with the primary setup regardless of the prerequisite installation outcome. This can be done
/// by setting DoNotPostVerifyPrerequisite to <c>true</c> (default is <c>false</c>)</para>
///</param>
/// <param name="optionalArguments">The optional arguments for the bootstrapper compiler.</param>
/// <returns>Path to the built bootstrapper file. Returns <c>null</c> if bootstrapper cannot be built.</returns>
///
/// <example>The following is an example of building bootstrapper <c>Setup.msi</c> for deploying .NET along with the <c>MyProduct.msi</c> file.
/// <code>
/// WixSharp.CommonTasks.Tasks.BuildBootstrapper(
/// @"C:\downloads\dotnetfx.exe",
/// "MainProduct.msi",
/// "setup.exe",
/// @"HKLM:Software\My Company\My Product:Installed"
/// false,
/// "");
/// </code>
/// </example>
static public string BuildBootstrapper(string prerequisiteFile, string primaryFile, string outputFile, string prerequisiteRegKeyValue, bool doNotPostVerifyPrerequisite, string optionalArguments)
{
var nbs = new NativeBootstrapper
{
PrerequisiteFile = prerequisiteFile,
PrimaryFile = primaryFile,
OutputFile = outputFile,
PrerequisiteRegKeyValue = prerequisiteRegKeyValue
};
nbs.DoNotPostVerifyPrerequisite = doNotPostVerifyPrerequisite;
if (!optionalArguments.IsEmpty())
nbs.OptionalArguments = optionalArguments;
return nbs.Build();
}
/// <summary>
/// Builds the bootstrapper.
/// </summary>
/// <param name="prerequisiteFile">The prerequisite file.</param>
/// <param name="primaryFile">The primary setup file.</param>
/// <param name="outputFile">The output (bootsrtapper) file.</param>
/// <param name="prerequisiteRegKeyValue">The prerequisite registry key value.
/// <para>This value is used to determine if the <c>PrerequisiteFile</c> should be launched.</para>
/// <para>This value must comply with the following pattern: <RegistryHive>:<KeyPath>:<ValueName>.</para>
/// <code>PrerequisiteRegKeyValue = @"HKLM:Software\My Company\My Product:Installed";</code>
/// Existence of the specified registry value at runtime is interpreted as an indication of the <c>PrerequisiteFile</c> has been already installed.
/// Thus bootstrapper will execute <c>PrimaryFile</c> without launching <c>PrerequisiteFile</c> first.</param>
/// <param name="doNotPostVerifyPrerequisite">The flag which allows you to disable verification of <c>PrerequisiteRegKeyValue</c> after the prerequisite setup is completed.
/// <para>Normally if <c>bootstrapper</c> checkers if <c>PrerequisiteRegKeyValue</c>/> exists straight after the prerequisite installation and starts
/// the primary setup only if it does.</para>
/// <para>It is possible to instruct bootstrapper to continue with the primary setup regardless of the prerequisite installation outcome. This can be done
/// by setting DoNotPostVerifyPrerequisite to <c>true</c> (default is <c>false</c>)</para>
///</param>
/// <returns>Path to the built bootstrapper file. Returns <c>null</c> if bootstrapper cannot be built.</returns>
///
/// <example>The following is an example of building bootstrapper <c>Setup.msi</c> for deploying .NET along with the <c>MyProduct.msi</c> file.
/// <code>
/// WixSharp.CommonTasks.Tasks.BuildBootstrapper(
/// @"C:\downloads\dotnetfx.exe",
/// "MainProduct.msi",
/// "setup.exe",
/// @"HKLM:Software\My Company\My Product:Installed"
/// false);
/// </code>
/// </example>
static public string BuildBootstrapper(string prerequisiteFile, string primaryFile, string outputFile, string prerequisiteRegKeyValue, bool doNotPostVerifyPrerequisite)
{
return BuildBootstrapper(prerequisiteFile, primaryFile, outputFile, prerequisiteRegKeyValue, doNotPostVerifyPrerequisite, null);
}
/// <summary>
/// Builds the bootstrapper.
/// </summary>
/// <param name="prerequisiteFile">The prerequisite file.</param>
/// <param name="primaryFile">The primary setup file.</param>
/// <param name="outputFile">The output (bootsrtapper) file.</param>
/// <param name="prerequisiteRegKeyValue">The prerequisite registry key value.
/// <para>This value is used to determine if the <c>PrerequisiteFile</c> should be launched.</para>
/// <para>This value must comply with the following pattern: <RegistryHive>:<KeyPath>:<ValueName>.</para>
/// <code>PrerequisiteRegKeyValue = @"HKLM:Software\My Company\My Product:Installed";</code>
/// Existence of the specified registry value at runtime is interpreted as an indication of the <c>PrerequisiteFile</c> has been already installed.
/// Thus bootstrapper will execute <c>PrimaryFile</c> without launching <c>PrerequisiteFile</c> first.</param>
/// <returns>Path to the built bootstrapper file. Returns <c>null</c> if bootstrapper cannot be built.</returns>
static public string BuildBootstrapper(string prerequisiteFile, string primaryFile, string outputFile, string prerequisiteRegKeyValue)
{
return BuildBootstrapper(prerequisiteFile, primaryFile, outputFile, prerequisiteRegKeyValue, false, null);
}
/// <summary>
/// Applies digital signature to a file (e.g. msi, exe, dll) with MS <c>SignTool.exe</c> utility.
/// </summary>
/// <param name="fileToSign">The file to sign.</param>
/// <param name="pfxFile">Specify the signing certificate in a file. If this file is a PFX with a password, the password may be supplied
/// with the <c>password</c> parameter.</param>
/// <param name="timeURL">The timestamp server's URL. If this option is not present (pass to null), the signed file will not be timestamped.
/// A warning is generated if timestamping fails.</param>
/// <param name="password">The password to use when opening the PFX file. Should be <c>null</c> if no password required.</param>
/// <param name="optionalArguments">Extra arguments to pass to the <c>SignTool.exe</c> utility.</param>
/// <param name="wellKnownLocations">The optional ';' separated list of directories where SignTool.exe can be located.
/// If this parameter is not specified WixSharp will try to locate the SignTool in the built-in well-known locations (system PATH)</param>
/// <returns>Exit code of the <c>SignTool.exe</c> process.</returns>
///
/// <example>The following is an example of signing <c>Setup.msi</c> file.
/// <code>
/// WixSharp.CommonTasks.Tasks.DigitalySign(
/// "Setup.msi",
/// "MyCert.pfx",
/// "http://timestamp.verisign.com/scripts/timstamp.dll",
/// "MyPassword",
/// null);
/// </code>
/// </example>
static public int DigitalySign(string fileToSign, string pfxFile, string timeURL, string password, string optionalArguments = null, string wellKnownLocations = null)
{
//"C:\Program Files\\Microsoft SDKs\Windows\v6.0A\bin\signtool.exe" sign /f "pfxFile" /p password /v "fileToSign" /t timeURL
//string args = "sign /v /f \"" + pfxFile + "\" \"" + fileToSign + "\"";
string args = "sign /v /f \"" + pfxFile + "\"";
if (timeURL != null)
args += " /t \"" + timeURL + "\"";
if (password != null)
args += " /p \"" + password + "\"";
if (!optionalArguments.IsEmpty())
args += " " + optionalArguments;
args += " \"" + fileToSign + "\"";
var tool = new ExternalTool
{
WellKnownLocations = wellKnownLocations ?? @"C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin",
ExePath = "signtool.exe",
Arguments = args
};
return tool.ConsoleRun();
}
/// <summary>
/// Applies digital signature to a file (e.g. msi, exe, dll) with MS <c>SignTool.exe</c> utility.
/// <para>If you need to specify extra SignTool.exe parameters or the location of the tool use the overloaded <c>DigitalySign</c> signature </para>
/// </summary>
/// <param name="fileToSign">The file to sign.</param>
/// <param name="pfxFile">Specify the signing certificate in a file. If this file is a PFX with a password, the password may be supplied
/// with the <c>password</c> parameter.</param>
/// <param name="timeURL">The timestamp server's URL. If this option is not present, the signed file will not be timestamped.
/// A warning is generated if timestamping fails.</param>
/// <param name="password">The password to use when opening the PFX file.</param>
/// <returns>Exit code of the <c>SignTool.exe</c> process.</returns>
///
/// <example>The following is an example of signing <c>Setup.msi</c> file.
/// <code>
/// WixSharp.CommonTasks.Tasks.DigitalySign(
/// "Setup.msi",
/// "MyCert.pfx",
/// "http://timestamp.verisign.com/scripts/timstamp.dll",
/// "MyPassword");
/// </code>
/// </example>
static public int DigitalySign(string fileToSign, string pfxFile, string timeURL, string password)
{
return DigitalySign(fileToSign, pfxFile, timeURL, password, null);
}
/// <summary>
/// Imports the reg file.
/// </summary>
/// <param name="regFile">The reg file.</param>
/// <returns></returns>
/// <example>The following is an example of importing registry entries from the *.reg file.
/// <code>
/// var project =
/// new Project("MyProduct",
/// new Dir(@"%ProgramFiles%\My Company\My Product",
/// new File(@"readme.txt")),
/// ...
///
/// project.RegValues = CommonTasks.Tasks.ImportRegFile("app_settings.reg");
///
/// Compiler.BuildMsi(project);
/// </code>
/// </example>
static public RegValue[] ImportRegFile(string regFile)
{
return RegFileImporter.ImportFrom(regFile);
}
/// <summary>
/// Imports the reg file. It is nothing else but an extension method version of the 'plain' <see cref="T:WixSharp.CommonTasks.Tasks.ImportRegFile"/>.
/// </summary>
/// <param name="project">The project object.</param>
/// <param name="regFile">The reg file.</param>
/// <returns></returns>
/// <example>The following is an example of importing registry entries from the *.reg file.
/// <code>
/// var project =
/// new Project("MyProduct",
/// new Dir(@"%ProgramFiles%\My Company\My Product",
/// new File(@"readme.txt")),
/// ...
///
/// project.ImportRegFile("app_settings.reg");
///
/// Compiler.BuildMsi(project);
/// </code>
/// </example>
static public Project ImportRegFile(this Project project, string regFile)
{
project.RegValues = ImportRegFile(regFile);
return project;
}
/// <summary>
/// Adds the property.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Project AddProperty(this Project project, params Property[] items)
{
project.Properties = project.Properties.AddRange(items);
return project;
}
/// <summary>
/// Adds the action.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Project AddAction(this Project project, params Action[] items)
{
project.Actions = project.Actions.AddRange(items);
return project;
}
/// <summary>
/// Adds the dir.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Project AddDir(this Project project, params Dir[] items)
{
project.Dirs = project.Dirs.AddRange(items);
return project;
}
/// <summary>
/// Adds the registry value.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Project AddRegValue(this Project project, params RegValue[] items)
{
project.RegValues = project.RegValues.AddRange(items);
return project;
}
/// <summary>
/// Adds the binary.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Project AddBinary(this Project project, params Binary[] items)
{
project.Binaries = project.Binaries.AddRange(items);
return project;
}
/// <summary>
/// Adds the environment variable.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
[Obsolete("AddEnvironmentVariabl is obsolete as the name has a typo. Please use AddEnvironmentVariable instead.", false)]
static public Project AddEnvironmentVariabl(this Project project, params EnvironmentVariable[] items)
{
return AddEnvironmentVariable(project, items);
}
/// <summary>
/// Adds the environment variable.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Project AddEnvironmentVariable(this Project project, params EnvironmentVariable[] items)
{
project.EnvironmentVariables = project.EnvironmentVariables.AddRange(items);
return project;
}
/// <summary>
/// Adds the assembly reference.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="files">The files.</param>
/// <returns></returns>
static public ManagedAction AddRefAssembly(this ManagedAction action, params string[] files)
{
action.RefAssemblies = action.RefAssemblies.AddRange(files);
return action;
}
//////////////////////////////////////////////////////////////////
/// <summary>
/// Adds the file association.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public File AddAssociation(this File file, params FileAssociation[] items)
{
file.Associations = file.Associations.AddRange(items);
return file;
}
/// <summary>
/// Adds the shortcut.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public File AddShortcut(this File file, params FileShortcut[] items)
{
file.Shortcuts = file.Shortcuts.AddRange(items);
return file;
}
//////////////////////////////////////////////////////////////////
/// <summary>
/// Adds the dir.
/// </summary>
/// <param name="dir">The dir.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Dir AddDir(this Dir dir, params Dir[] items)
{
dir.Dirs = dir.Dirs.AddRange(items);
return dir;
}
/// <summary>
/// Adds the file.
/// </summary>
/// <param name="dir">The dir.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Dir AddFile(this Dir dir, params File[] items)
{
dir.Files = dir.Files.AddRange(items);
return dir;
}
/// <summary>
/// Adds the shortcut.
/// </summary>
/// <param name="dir">The dir.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Dir AddShortcut(this Dir dir, params ExeFileShortcut[] items)
{
dir.Shortcuts = dir.Shortcuts.AddRange(items);
return dir;
}
/// <summary>
/// Adds the merge module.
/// </summary>
/// <param name="dir">The dir.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Dir AddMergeModule(this Dir dir, params Merge[] items)
{
dir.MergeModules = dir.MergeModules.AddRange(items);
return dir;
}
/// <summary>
/// Adds the file collection.
/// </summary>
/// <param name="dir">The dir.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Dir AddFileCollection(this Dir dir, params Files[] items)
{
dir.FileCollections = dir.FileCollections.AddRange(items);
return dir;
}
/// <summary>
/// Adds the dir file collection.
/// </summary>
/// <param name="dir">The dir.</param>
/// <param name="items">The items.</param>
/// <returns></returns>
static public Dir AddDirFileCollection(this Dir dir, params DirFiles[] items)
{
dir.DirFileCollections = dir.DirFileCollections.AddRange(items);
return dir;
}
/// <summary>
/// Removes the dialogs between specified two dialogs. It simply connects 'next' button of the start dialog with the
/// 'NewDialog' action associated with the end dialog. And vise versa for the 'back' button.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <returns></returns>
/// <example>The following is an example of the setup that skips License dialog.
/// <code>
/// project.UI = WUI.WixUI_InstallDir;
/// project.RemoveDialogsBetween(Dialogs.WelcomeDlg, Dialogs.InstallDirDlg);
/// ...
/// Compiler.BuildMsi(project);
/// </code>
/// </example>
static public Project RemoveDialogsBetween(this Project project, string start, string end)
{
if (project.CustomUI == null)
project.CustomUI = new Controls.DialogSequence();
project.CustomUI.On(start, Controls.Buttons.Next, new Controls.ShowDialog(end) { Order = Controls.DialogSequence.DefaultOrder });
project.CustomUI.On(end, Controls.Buttons.Back, new Controls.ShowDialog(start) { Order = Controls.DialogSequence.DefaultOrder });
return project;
}
/// <summary>
/// Sets the Project version from the file version of the file specified by it's ID.
/// <para>This method sets project WixSourceGenerated event handler and injects
/// "!(bind.FileVersion.<file ID>" into the XML Product's Version attribute.</para>
/// </summary>
/// <param name="project">The project.</param>
/// <param name="fileId">The file identifier.</param>
/// <returns></returns>
static public Project SetVersionFrom(this Project project, string fileId)
{
project.WixSourceGenerated += document =>
document.FindSingle("Product")
.AddAttributes("Version=!(bind.FileVersion." + fileId + ")");
return project;
}
/// <summary>
/// Injects CLR dialog between MSI dialogs 'prevDialog' and 'nextDialog'.
/// Passes custom action CLR method name (showDialogMethod) for instantiating and popping up the CLR dialog.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="showDialogMethod">The show dialog method.</param>
/// <param name="prevDialog">The previous dialog.</param>
/// <param name="nextDialog">The next dialog.</param>
/// <returns></returns>
/// <example>The following is an example of inserting CustomDialog dialog into the UI sequence between MSI dialogs InsallDirDlg and VerifyReadyDlg.
/// <code>
/// public class static Script
/// {
/// public static void Main()
/// {
/// var project = new Project("CustomDialogTest");
///
/// project.InjectClrDialog("ShowCustomDialog", Dialogs.InstallDirDlg, Dialogs.VerifyReadyDlg);
/// Compiler.BuildMsi(project);
/// }
///
/// [CustomAction]
/// public static ActionResult ShowCustomDialog(Session session)
/// {
/// return WixCLRDialog.ShowAsMsiDialog(new CustomDialog(session));
/// }
///}
/// </code>
/// </example>
static public Project InjectClrDialog(this Project project, string showDialogMethod, string prevDialog, string nextDialog)
{
string wixSharpAsm = typeof(Project).Assembly.Location;
string wixSharpUIAsm = IO.Path.ChangeExtension(wixSharpAsm, ".UI.dll");
var showClrDialog = new ManagedAction(showDialogMethod)
{
Sequence = Sequence.NotInSequence,
};
project.DefaultRefAssemblies.Add(wixSharpAsm);
project.DefaultRefAssemblies.Add(wixSharpUIAsm);
//Must use WixUI_Common as other UI type has predefined dialogs already linked between each other and WiX does not allow overriding events
//http://stackoverflow.com/questions/16961493/override-publish-within-uiref-in-wix
project.UI = WUI.WixUI_Common;
if (project.CustomUI != null)
throw new ApplicationException("Project.CustomUI is already initialized. Ensure InjectClrDialog is invoked before any adjustments made to CustomUI.");
project.CustomUI = new CommomDialogsUI();
project.Actions = project.Actions.Add(showClrDialog);
//disconnect prev and next dialogs
project.CustomUI.UISequence.ForEach(x =>
{
if ((x.Dialog == prevDialog && x.Control == Buttons.Next) || (x.Dialog == nextDialog && x.Control == Buttons.Back))
x.Actions.RemoveAll(a => a is ShowDialog);
});
project.CustomUI.UISequence.RemoveAll(x => x.Actions.Count == 0);
//create new dialogs connection with showAction in between
project.CustomUI.On(prevDialog, Buttons.Next, new ExecuteCustomAction(showClrDialog))
.On(prevDialog, Buttons.Next, new ShowDialog(nextDialog, Condition.ClrDialog_NextPressed))
.On(prevDialog, Buttons.Next, new CloseDialog("Exit", Condition.ClrDialog_CancelPressed) { Order = 2 })
.On(nextDialog, Buttons.Back, new ExecuteCustomAction(showClrDialog))
.On(nextDialog, Buttons.Back, new ShowDialog(prevDialog, Condition.ClrDialog_BackPressed));
var installDir = project.AllDirs.FirstOrDefault(d => d.HastemsToInstall());
if (installDir != null && project.CustomUI.Properties.ContainsKey("WIXUI_INSTALLDIR"))
project.CustomUI.Properties["WIXUI_INSTALLDIR"] = installDir.RawId ?? Compiler.AutoGeneration.InstallDirDefaultId;
return project;
}
//not ready yet. Investigation is in progress
static internal Project InjectClrDialogInFeatureTreeUI(this Project project, string showDialogMethod, string prevDialog, string nextDialog)
{
string wixSharpAsm = typeof(Project).Assembly.Location;
string wixSharpUIAsm = IO.Path.ChangeExtension(wixSharpAsm, ".UI.dll");
var showClrDialog = new ManagedAction(showDialogMethod)
{
Sequence = Sequence.NotInSequence,
RefAssemblies = new[] { wixSharpAsm, wixSharpUIAsm }
};
project.UI = WUI.WixUI_FeatureTree;
if (project.CustomUI != null)
throw new ApplicationException("Project.CustomUI is already initialized. Ensure InjectClrDialog is invoked before any adjustments made to CustomUI.");
project.CustomUI = new DialogSequence();
project.Actions = project.Actions.Add(showClrDialog);
//disconnect prev and next dialogs
project.CustomUI.UISequence.RemoveAll(x => (x.Dialog == prevDialog && x.Control == Buttons.Next) ||
(x.Dialog == nextDialog && x.Control == Buttons.Back));
//create new dialogs connection with showAction in between
project.CustomUI.On(prevDialog, Buttons.Next, new ExecuteCustomAction(showClrDialog))
.On(prevDialog, Buttons.Next, new ShowDialog(nextDialog, Condition.ClrDialog_NextPressed))
.On(prevDialog, Buttons.Next, new CloseDialog("Exit", Condition.ClrDialog_CancelPressed) { Order = 2 })
.On(nextDialog, Buttons.Back, new ExecuteCustomAction(showClrDialog))
.On(nextDialog, Buttons.Back, new ShowDialog(prevDialog, Condition.ClrDialog_BackPressed));
return project;
}
/// <summary>
/// Gets the file version.
/// </summary>
/// <param name="file">The path to the file.</param>
/// <returns></returns>
static public Version GetFileVersion(string file)
{
var info = FileVersionInfo.GetVersionInfo(file);
//cannot use info.FileVersion as it can include description string
return new Version(info.FileMajorPart,
info.FileMinorPart,
info.FileBuildPart,
info.FilePrivatePart);
}
/// <summary>
/// Binds the LaunchCondition to the automatically created REQUIRED_NET property which is set to the value of the
/// Software\Microsoft\NET Framework Setup\NDP\{version}\Install registry entry.
/// <para>It is a single step equivalent of the "Wix# Samples\LaunchConditions" sample.</para>
/// <para>Note that the value of the version parameter is a precise sub-key of the corresponding 'Install' registry entry
/// (e.g. as in 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4.0\Client\Install').</para>
/// <para>The typical values are:</para>
/// <para> v2.0.50727</para>
/// <para> v3.0</para>
/// <para> v3.5</para>
/// <para> v4\Client</para>
/// <para> v4\Full</para>
/// <para> v4.0\Client</para>
/// <para> ...</para>
/// </summary>
/// <param name="project">The project.</param>
/// <param name="version">The sub-key of the registry entry of the sub-key of the corresponding registry version of .NET to be checked.
/// </param>
/// <param name="errorMessage">The error message to be displayed if .NET version is not present.</param>
/// <returns></returns>
[Obsolete("SetClrPrerequisite is obsolete. Please use more reliable SetNetFxPrerequisite instead.", true)]
static public Project SetClrPrerequisite(this WixSharp.Project project, string version, string errorMessage = null)
{
string message = errorMessage ?? "Please install .NET " + version + " first.";
project.LaunchConditions.Add(new LaunchCondition("REQUIRED_NET=\"#1\"", message));
project.Properties = project.Properties.Add(new RegValueProperty("REQUIRED_NET",
RegistryHive.LocalMachine,
@"Software\Microsoft\NET Framework Setup\NDP\" + version,
"Install", "0"));
return project;
}
/// <summary>
/// Binds the LaunchCondition to the <c>version</c> condition based on WiXNetFxExtension properties.
/// <para>The typical conditions are:</para>
/// <para> NETFRAMEWORK20="#1"</para>
/// <para> NETFRAMEWORK40FULL="#1"</para>
/// <para> NETFRAMEWORK35="#1"</para>
/// <para> NETFRAMEWORK30_SP_LEVEL and NOT NETFRAMEWORK30_SP_LEVEL='#0'</para>
/// <para> ...</para>
/// The full list of names and values can be found here http://wixtoolset.org/documentation/manual/v3/customactions/wixnetfxextension.html
/// </summary>
/// <param name="project">The project.</param>
/// <param name="versionCondition">Condition expression.
/// </param>
/// <param name="errorMessage">The error message to be displayed if .NET version is not present.</param>
/// <returns></returns>
static public Project SetNetFxPrerequisite(this WixSharp.Project project, string versionCondition, string errorMessage = null)
{
var condition = Condition.Create(versionCondition);
string message = errorMessage ?? "Please install the appropriate .NET version first.";
project.LaunchConditions.Add(new LaunchCondition(condition, message));
foreach (var prop in condition.GetDistinctProperties())
project.Properties = project.Properties.Add(new PropertyRef(prop));
project.IncludeWixExtension(WixExtension.NetFx);
return project;
}
/// <summary>
/// Sets the value of the attribute value in the .NET application configuration file according
/// the specified XPath expression.
/// <para>
/// This simple routine is to be used for the customization of the installed config files
/// (e.g. in the deferred custom actions).
/// </para>
/// </summary>
/// <param name="configFile">The configuration file.</param>
/// <param name="elementPath">The element XPath value. It should include the attribute name.</param>
/// <param name="value">The value to be set to the attribute.</param>
///
/// <example>The following is an example demonstrates this simple technique:
/// <code>
/// Tasks.SetConfigAttribute(configFile, "//configuration/appSettings/add[@key='AppName']/@value", "My App");
/// </code>
/// </example>
static public void SetConfigAttribute(string configFile, string elementPath, string value)
{
XDocument.Load(configFile)
.Root
.SetConfigAttribute(elementPath, value)
.Document
.Save(configFile);
}
/// <summary>
/// Sets the value of the attribute value in the .NET application configuration file according
/// the specified XPath expression.
/// <para>
/// This simple routine is to be used for the customization of the installed config files
/// (e.g. in the deferred custom actions).
/// </para>
/// </summary>
/// <returns></returns>
/// <param name="config">The configuration file element.</param>
/// <param name="elementPath">The element XPath value. It should include the attribute name.</param>
/// <param name="value">The value to be set to the attribute.</param>
///
/// <example>The following is an example demonstrates this simple technique:
/// <code>
/// XDocument.Load(configFile).Root
/// .SetConfigAttribute("//configuration/appSettings/add[@key='AppName']/@value", "My App")
/// .SetConfigAttribute(...
/// .SetConfigAttribute(...
/// .Document.Save(configFile);
/// </code>
/// </example>
static public XElement SetConfigAttribute(this XElement config, string elementPath, string value)
{
var valueAttr = ((IEnumerable)config.XPathEvaluate(elementPath)).Cast<XAttribute>().FirstOrDefault();
if (valueAttr != null)
valueAttr.Value = value;
return config;
}
/// <summary>
/// Installs the windows service. It uses InstallUtil.exe to complete the actual installation/uninstallation.
/// During the run for the InstallUtil.exe console window is hidden. /// If any error occurred the console output is captured and embedded into the raised Exception object.
/// </summary>
/// <param name="serviceFile">The service file.</param>
/// <param name="isInstalling">if set to <c>true</c> [is installing].</param>
/// <returns></returns>
/// <exception cref="System.Exception"></exception>
static public string InstallService(string serviceFile, bool isInstalling)
{
var util = new ExternalTool
{
ExePath = IO.Path.Combine(LatestFrameworkDirectory, "InstallUtil.exe"),
Arguments = string.Format("{1} \"{0}\"", serviceFile, isInstalling ? "" : "/u")
};
var buf = new StringBuilder();
int retval = util.ConsoleRun(line => buf.AppendLine(line));
string output = buf.ToString();
string logoLastLine = "Microsoft Corporation. All rights reserved.";
int pos = output.IndexOf(logoLastLine);
if (pos != -1)
output = output.Substring(pos + logoLastLine.Length).Trim();
if (retval != 0)
throw new Exception(output);
return output;
}
/// <summary>
/// Starts the windows service. It uses sc.exe to complete the action. During the action console window is hidden.
/// If any error occurred the console output is captured and embedded into the raised Exception object.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
/// <returns></returns>
static public string StartService(string service, bool throwOnError = true)
{
return ServiceDo("start", service, throwOnError);
}
/// <summary>
/// Stops the windows service. It uses sc.exe to complete the action. During the action console window is hidden.
/// If any error occurred the console output is captured and embedded into the raised Exception object.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
/// <returns></returns>
static public string StopService(string service, bool throwOnError = true)
{
return ServiceDo("stop", service, throwOnError);
}
static string ServiceDo(string action, string service, bool throwOnError)
{
var util = new ExternalTool { ExePath = "sc.exe", Arguments = action + " \"" + service + "\"" };
var buf = new StringBuilder();
int retval = util.ConsoleRun(line => buf.AppendLine(line));
if (retval != 0 && throwOnError)
throw new Exception(buf.ToString());
return buf.ToString();
}
/// <summary>
/// Gets the directory of the latest installed verion of .NET framework.
/// </summary>
/// <value>
/// The latest framework directory.
/// </value>
public static string LatestFrameworkDirectory
{
get
{
string currentVersionDir = IO.Path.GetDirectoryName(typeof(string).Assembly.Location);
string rootDir = IO.Path.GetDirectoryName(currentVersionDir);
return IO.Directory.GetDirectories(rootDir, "v*.*")
.OrderByDescending(x => x)
.FirstOrDefault();
}
}
}
}
internal class ExternalTool
{
public string ExePath { set; get; }
public string Arguments { set; get; }
public string WellKnownLocations { set; get; }
public int WinRun()
{
string systemPathOriginal = Environment.GetEnvironmentVariable("PATH");
try
{
Environment.SetEnvironmentVariable("PATH", systemPathOriginal + ";" + Environment.ExpandEnvironmentVariables(this.WellKnownLocations ?? ""));
var process = new Process();
process.StartInfo.FileName = this.ExePath;
process.StartInfo.Arguments = this.Arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
process.WaitForExit();
return process.ExitCode;
}
finally
{
Environment.SetEnvironmentVariable("PATH", systemPathOriginal);
}
}
public int ConsoleRun()
{
return ConsoleRun(Console.WriteLine);
}
public int ConsoleRun(Action<string> onConsoleOut)
{
string systemPathOriginal = Environment.GetEnvironmentVariable("PATH");
try
{
Environment.SetEnvironmentVariable("PATH", Environment.ExpandEnvironmentVariables(this.WellKnownLocations ?? "") + ";" + "%WIXSHARP_PATH%;" + systemPathOriginal);
string exePath = GetFullPath(this.ExePath);
if (exePath == null)
{
Console.WriteLine("Error: Cannot find " + this.ExePath);
Console.WriteLine("Make sure it is in the System PATH or WIXSHARP_PATH environment variables or WellKnownLocations member/parameter is initialized properly. ");
return 1;
}
Console.WriteLine("Execute:\n\"" + this.ExePath + "\" " + this.Arguments);
var process = new Process();
process.StartInfo.FileName = exePath;
process.StartInfo.Arguments = this.Arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
if (onConsoleOut != null)
{
string line = null;
while (null != (line = process.StandardOutput.ReadLine()))
{
onConsoleOut(line);
}
string error = process.StandardError.ReadToEnd();
if (!error.IsEmpty())
onConsoleOut(error);
}
process.WaitForExit();
return process.ExitCode;
}
finally
{
Environment.SetEnvironmentVariable("PATH", systemPathOriginal);
}
}
string GetFullPath(string path)
{
if (IO.File.Exists(path))
return IO.Path.GetFullPath(path);
foreach (string dir in Environment.GetEnvironmentVariable("PATH").Split(';'))
{
if (IO.Directory.Exists(dir))
{
string fullPath = IO.Path.Combine(Environment.ExpandEnvironmentVariables(dir).Trim(), path);
if (IO.File.Exists(fullPath))
return fullPath;
}
}
return null;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using Lucene.Net.Support;
using NumericField = Lucene.Net.Documents.NumericField;
using IndexReader = Lucene.Net.Index.IndexReader;
using Single = Lucene.Net.Support.Single;
using Term = Lucene.Net.Index.Term;
using TermEnum = Lucene.Net.Index.TermEnum;
using StringHelper = Lucene.Net.Util.StringHelper;
namespace Lucene.Net.Search
{
/// <summary> Stores information about how to sort documents by terms in an individual
/// field. Fields must be indexed in order to sort by them.
///
/// <p/>Created: Feb 11, 2004 1:25:29 PM
/// </summary>
/// <seealso cref="Sort"></seealso>
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
public class SortField
{
/// <summary>Sort by document score (relevancy). Sort values are Float and higher
/// values are at the front.
/// </summary>
public const int SCORE = 0;
/// <summary>Sort by document number (index order). Sort values are Integer and lower
/// values are at the front.
/// </summary>
public const int DOC = 1;
// reserved, in Lucene 2.9, there was a constant: AUTO = 2
/// <summary>Sort using term values as Strings. Sort values are String and lower
/// values are at the front.
/// </summary>
public const int STRING = 3;
/// <summary>Sort using term values as encoded Integers. Sort values are Integer and
/// lower values are at the front.
/// </summary>
public const int INT = 4;
/// <summary>Sort using term values as encoded Floats. Sort values are Float and
/// lower values are at the front.
/// </summary>
public const int FLOAT = 5;
/// <summary>Sort using term values as encoded Longs. Sort values are Long and
/// lower values are at the front.
/// </summary>
public const int LONG = 6;
/// <summary>Sort using term values as encoded Doubles. Sort values are Double and
/// lower values are at the front.
/// </summary>
public const int DOUBLE = 7;
/// <summary>Sort using term values as encoded Shorts. Sort values are Short and
/// lower values are at the front.
/// </summary>
public const int SHORT = 8;
/// <summary>Sort using a custom Comparator. Sort values are any Comparable and
/// sorting is done according to natural order.
/// </summary>
public const int CUSTOM = 9;
/// <summary>Sort using term values as encoded Bytes. Sort values are Byte and
/// lower values are at the front.
/// </summary>
public const int BYTE = 10;
/// <summary>Sort using term values as Strings, but comparing by
/// value (using String.compareTo) for all comparisons.
/// This is typically slower than <see cref="STRING" />, which
/// uses ordinals to do the sorting.
/// </summary>
public const int STRING_VAL = 11;
// IMPLEMENTATION NOTE: the FieldCache.STRING_INDEX is in the same "namespace"
// as the above static int values. Any new values must not have the same value
// as FieldCache.STRING_INDEX.
/// <summary>Represents sorting by document score (relevancy). </summary>
public static readonly SortField FIELD_SCORE = new SortField(null, SCORE);
/// <summary>Represents sorting by document number (index order). </summary>
public static readonly SortField FIELD_DOC = new SortField(null, DOC);
private System.String field;
private int type; // defaults to determining type dynamically
private System.Globalization.CultureInfo locale; // defaults to "natural order" (no Locale)
internal bool reverse = false; // defaults to natural order
private Lucene.Net.Search.Parser parser;
// Used for CUSTOM sort
private FieldComparatorSource comparatorSource;
/// <summary>Creates a sort by terms in the given field with the type of term
/// values explicitly given.
/// </summary>
/// <param name="field"> Name of field to sort by. Can be <c>null</c> if
/// <c>type</c> is SCORE or DOC.
/// </param>
/// <param name="type"> Type of values in the terms.
/// </param>
public SortField(System.String field, int type)
{
InitFieldType(field, type);
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field with the
/// type of term values explicitly given.
/// </summary>
/// <param name="field"> Name of field to sort by. Can be <c>null</c> if
/// <c>type</c> is SCORE or DOC.
/// </param>
/// <param name="type"> Type of values in the terms.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
public SortField(System.String field, int type, bool reverse)
{
InitFieldType(field, type);
this.reverse = reverse;
}
/// <summary>Creates a sort by terms in the given field, parsed
/// to numeric values using a custom <see cref="Search.Parser" />.
/// </summary>
/// <param name="field"> Name of field to sort by. Must not be null.
/// </param>
/// <param name="parser">Instance of a <see cref="Search.Parser" />,
/// which must subclass one of the existing numeric
/// parsers from <see cref="FieldCache" />. Sort type is inferred
/// by testing which numeric parser the parser subclasses.
/// </param>
/// <throws> IllegalArgumentException if the parser fails to </throws>
/// <summary> subclass an existing numeric parser, or field is null
/// </summary>
public SortField(System.String field, Lucene.Net.Search.Parser parser):this(field, parser, false)
{
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field, parsed
/// to numeric values using a custom <see cref="Search.Parser" />.
/// </summary>
/// <param name="field"> Name of field to sort by. Must not be null.
/// </param>
/// <param name="parser">Instance of a <see cref="Search.Parser" />,
/// which must subclass one of the existing numeric
/// parsers from <see cref="FieldCache" />. Sort type is inferred
/// by testing which numeric parser the parser subclasses.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
/// <throws> IllegalArgumentException if the parser fails to </throws>
/// <summary> subclass an existing numeric parser, or field is null
/// </summary>
public SortField(System.String field, Lucene.Net.Search.Parser parser, bool reverse)
{
if (parser is Lucene.Net.Search.IntParser)
InitFieldType(field, INT);
else if (parser is Lucene.Net.Search.FloatParser)
InitFieldType(field, FLOAT);
else if (parser is Lucene.Net.Search.ShortParser)
InitFieldType(field, SHORT);
else if (parser is Lucene.Net.Search.ByteParser)
InitFieldType(field, BYTE);
else if (parser is Lucene.Net.Search.LongParser)
InitFieldType(field, LONG);
else if (parser is Lucene.Net.Search.DoubleParser)
InitFieldType(field, DOUBLE);
else
{
throw new System.ArgumentException("Parser instance does not subclass existing numeric parser from FieldCache (got " + parser + ")");
}
this.reverse = reverse;
this.parser = parser;
}
/// <summary>Creates a sort by terms in the given field sorted
/// according to the given locale.
/// </summary>
/// <param name="field"> Name of field to sort by, cannot be <c>null</c>.
/// </param>
/// <param name="locale">Locale of values in the field.
/// </param>
public SortField(System.String field, System.Globalization.CultureInfo locale)
{
InitFieldType(field, STRING);
this.locale = locale;
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field sorted
/// according to the given locale.
/// </summary>
/// <param name="field"> Name of field to sort by, cannot be <c>null</c>.
/// </param>
/// <param name="locale">Locale of values in the field.
/// </param>
public SortField(System.String field, System.Globalization.CultureInfo locale, bool reverse)
{
InitFieldType(field, STRING);
this.locale = locale;
this.reverse = reverse;
}
/// <summary>Creates a sort with a custom comparison function.</summary>
/// <param name="field">Name of field to sort by; cannot be <c>null</c>.
/// </param>
/// <param name="comparator">Returns a comparator for sorting hits.
/// </param>
public SortField(System.String field, FieldComparatorSource comparator)
{
InitFieldType(field, CUSTOM);
this.comparatorSource = comparator;
}
/// <summary>Creates a sort, possibly in reverse, with a custom comparison function.</summary>
/// <param name="field">Name of field to sort by; cannot be <c>null</c>.
/// </param>
/// <param name="comparator">Returns a comparator for sorting hits.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
public SortField(System.String field, FieldComparatorSource comparator, bool reverse)
{
InitFieldType(field, CUSTOM);
this.reverse = reverse;
this.comparatorSource = comparator;
}
// Sets field & type, and ensures field is not NULL unless
// type is SCORE or DOC
private void InitFieldType(System.String field, int type)
{
this.type = type;
if (field == null)
{
if (type != SCORE && type != DOC)
throw new System.ArgumentException("field can only be null when type is SCORE or DOC");
}
else
{
this.field = StringHelper.Intern(field);
}
}
/// <summary>Returns the name of the field. Could return <c>null</c>
/// if the sort is by SCORE or DOC.
/// </summary>
/// <value> Name of field, possibly <c>null</c>. </value>
public virtual string Field
{
get { return field; }
}
/// <summary>Returns the type of contents in the field.</summary>
/// <value> One of the constants SCORE, DOC, STRING, INT or FLOAT. </value>
public virtual int Type
{
get { return type; }
}
/// <summary>Returns the Locale by which term values are interpreted.
/// May return <c>null</c> if no Locale was specified.
/// </summary>
/// <value> Locale, or <c>null</c>. </value>
public virtual CultureInfo Locale
{
get { return locale; }
}
/// <summary>Returns the instance of a <see cref="FieldCache" /> parser that fits to the given sort type.
/// May return <c>null</c> if no parser was specified. Sorting is using the default parser then.
/// </summary>
/// <value> An instance of a <see cref="FieldCache" /> parser, or <c>null</c>. </value>
public virtual Parser Parser
{
get { return parser; }
}
/// <summary>Returns whether the sort should be reversed.</summary>
/// <value> True if natural order should be reversed. </value>
public virtual bool Reverse
{
get { return reverse; }
}
/// <summary>
/// Returns the <see cref="FieldComparatorSource"/> used for
/// custom sorting
/// </summary>
public virtual FieldComparatorSource ComparatorSource
{
get { return comparatorSource; }
}
public override System.String ToString()
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
switch (type)
{
case SCORE:
buffer.Append("<score>");
break;
case DOC:
buffer.Append("<doc>");
break;
case STRING:
buffer.Append("<string: \"").Append(field).Append("\">");
break;
case STRING_VAL:
buffer.Append("<string_val: \"").Append(field).Append("\">");
break;
case BYTE:
buffer.Append("<byte: \"").Append(field).Append("\">");
break;
case SHORT:
buffer.Append("<short: \"").Append(field).Append("\">");
break;
case INT:
buffer.Append("<int: \"").Append(field).Append("\">");
break;
case LONG:
buffer.Append("<long: \"").Append(field).Append("\">");
break;
case FLOAT:
buffer.Append("<float: \"").Append(field).Append("\">");
break;
case DOUBLE:
buffer.Append("<double: \"").Append(field).Append("\">");
break;
case CUSTOM:
buffer.Append("<custom:\"").Append(field).Append("\": ").Append(comparatorSource).Append('>');
break;
default:
buffer.Append("<???: \"").Append(field).Append("\">");
break;
}
if (locale != null)
buffer.Append('(').Append(locale).Append(')');
if (parser != null)
buffer.Append('(').Append(parser).Append(')');
if (reverse)
buffer.Append('!');
return buffer.ToString();
}
/// <summary>Returns true if <c>o</c> is equal to this. If a
/// <see cref="FieldComparatorSource" /> or <see cref="Search.Parser" />
/// was provided, it must properly
/// implement equals (unless a singleton is always used).
/// </summary>
public override bool Equals(System.Object o)
{
if (this == o)
return true;
if (!(o is SortField))
return false;
SortField other = (SortField) o;
return ((System.Object) other.field == (System.Object) this.field && other.type == this.type &&
other.reverse == this.reverse &&
(other.locale == null ? this.locale == null : other.locale.Equals(this.locale)) &&
(other.comparatorSource == null
? this.comparatorSource == null
: other.comparatorSource.Equals(this.comparatorSource)) &&
(other.parser == null ? this.parser == null : other.parser.Equals(this.parser)));
}
/// <summary>Returns true if <c>o</c> is equal to this. If a
/// <see cref="FieldComparatorSource" /> (deprecated) or <see cref="Search.Parser" />
/// was provided, it must properly
/// implement hashCode (unless a singleton is always
/// used).
/// </summary>
public override int GetHashCode()
{
int hash = type ^ 0x346565dd + (reverse ? Boolean.TrueString.GetHashCode() : Boolean.FalseString.GetHashCode()) ^ unchecked((int) 0xaf5998bb);
if (field != null)
hash += (field.GetHashCode() ^ unchecked((int) 0xff5685dd));
if (locale != null)
{
hash += (locale.GetHashCode() ^ 0x08150815);
}
if (comparatorSource != null)
hash += comparatorSource.GetHashCode();
if (parser != null)
hash += (parser.GetHashCode() ^ 0x3aaf56ff);
return hash;
}
//// field must be interned after reading from stream
// private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
// in.defaultReadObject();
// if (field != null)
// field = StringHelper.intern(field);
// }
[System.Runtime.Serialization.OnDeserialized]
internal void OnDeserialized(System.Runtime.Serialization.StreamingContext context)
{
field = StringHelper.Intern(field);
}
/// <summary>Returns the <see cref="FieldComparator" /> to use for
/// sorting.
///
/// <b>NOTE:</b> This API is experimental and might change in
/// incompatible ways in the next release.
///
/// </summary>
/// <param name="numHits">number of top hits the queue will store
/// </param>
/// <param name="sortPos">position of this SortField within <see cref="Sort" />
///. The comparator is primary if sortPos==0,
/// secondary if sortPos==1, etc. Some comparators can
/// optimize themselves when they are the primary sort.
/// </param>
/// <returns> <see cref="FieldComparator" /> to use when sorting
/// </returns>
public virtual FieldComparator GetComparator(int numHits, int sortPos)
{
if (locale != null)
{
// TODO: it'd be nice to allow FieldCache.getStringIndex
// to optionally accept a Locale so sorting could then use
// the faster StringComparator impls
return new FieldComparator.StringComparatorLocale(numHits, field, locale);
}
switch (type)
{
case SortField.SCORE:
return new FieldComparator.RelevanceComparator(numHits);
case SortField.DOC:
return new FieldComparator.DocComparator(numHits);
case SortField.INT:
return new FieldComparator.IntComparator(numHits, field, parser);
case SortField.FLOAT:
return new FieldComparator.FloatComparator(numHits, field, parser);
case SortField.LONG:
return new FieldComparator.LongComparator(numHits, field, parser);
case SortField.DOUBLE:
return new FieldComparator.DoubleComparator(numHits, field, parser);
case SortField.BYTE:
return new FieldComparator.ByteComparator(numHits, field, parser);
case SortField.SHORT:
return new FieldComparator.ShortComparator(numHits, field, parser);
case SortField.CUSTOM:
System.Diagnostics.Debug.Assert(comparatorSource != null);
return comparatorSource.NewComparator(field, numHits, sortPos, reverse);
case SortField.STRING:
return new FieldComparator.StringOrdValComparator(numHits, field, sortPos, reverse);
case SortField.STRING_VAL:
return new FieldComparator.StringValComparator(numHits, field);
default:
throw new System.SystemException("Illegal sort type: " + type);
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASCMD
{
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.Common.Response;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This scenario is designed to test the FolderDelete command.
/// </summary>
[TestClass]
public class S03_FolderDelete : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Cases
/// <summary>
/// This test case is used to verify if the FolderDelete command is successful, the status should be equal to 1.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S03_TC01_FolderDelete_Success()
{
#region Call method FolderCreate to create a new folder as a child folder of the specified parent folder.
FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderDelete"), "0");
Site.Assert.AreEqual<int>(
1,
int.Parse(folderCreateResponse.ResponseData.Status),
"The server should return a status code 1 in the FolderCreate command response to indicate success.");
#endregion
#region Call method FolderDelete to delete the created folder from the server.
FolderDeleteRequest folderDeleteRequest = Common.CreateFolderDeleteRequest(folderCreateResponse.ResponseData.SyncKey, folderCreateResponse.ResponseData.ServerId);
FolderDeleteResponse folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
Site.Assert.AreEqual<int>(
1,
int.Parse(folderDeleteResponse.ResponseData.Status),
"The server should return a status code 1 in the FolderDelete command response to indicate success.");
#endregion
#region Call method FolderSync to synchronize the collection hierarchy.
FolderSyncResponse folderSyncResponse = this.FolderSync();
Site.Assert.AreEqual<int>(
1,
int.Parse(folderSyncResponse.ResponseData.Status),
"The server should return a status code 1 in the FolderSync command response to indicate success.");
bool folderDeleteSuccess = true;
foreach (FolderSyncChangesAdd add in folderSyncResponse.ResponseData.Changes.Add)
{
if (add.ServerId == folderCreateResponse.ResponseData.ServerId)
{
folderDeleteSuccess = false;
break;
}
}
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R97");
// The folderDeleteSuccess is true indicates the folder which deleted by FolderDelete command is deleted successfully.
// Verify MS-ASCMD requirement: MS-ASCMD_R97
Site.CaptureRequirementIfIsTrue(
folderDeleteSuccess,
97,
@"[In FolderDelete] The FolderDelete command deletes a folder from the server.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R98");
// The folderDeleteSuccess is true indicates the folder which deleted by FolderDelete command is deleted successfully.
// Verify MS-ASCMD requirement: MS-ASCMD_R98
Site.CaptureRequirementIfIsTrue(
folderDeleteSuccess,
98,
@"[In FolderDelete] The ServerId (section 2.2.3.151.2) of the folder is passed to the server in the FolderDelete command request (section 2.2.2.3), which deletes the collection with the matching identifier.");
// The folderDeleteSuccess is true indicates the folder which deleted by FolderDelete command is deleted successfully.
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4045");
// Verify MS-ASCMD requirement: MS-ASCMD_R4045
Site.CaptureRequirementIfIsTrue(
folderDeleteSuccess,
4045,
@"[In Status(FolderDelete)] [When the scope is Global], [the cause of the status value 1 is] Server successfully completed command.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5783");
// If folder has been deleted successfully, the server must send a synchronization key to the client in a response.
Site.CaptureRequirementIfIsNotNull(
folderDeleteResponse.ResponseData.SyncKey,
5783,
@"[In SyncKey(FolderCreate, FolderDelete, and FolderUpdate)] After a successful [FolderCreate command (section 2.2.2.2),] FolderDelete command (section 2.2.2.3) [, or FolderUpdate command (section 2.2.2.5)], the server MUST send a synchronization key to the client in a response.");
#endregion
}
/// <summary>
/// This test case is used to verify FolderDelete command, if the specified folder is a special system folder, the status in return value is 3.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S03_TC02_FolderDelete_Status3()
{
// Call method FolderDelete to delete a Calendar folder from the server.
FolderDeleteRequest folderDeleteRequest = Common.CreateFolderDeleteRequest(this.LastFolderSyncKey, this.User1Information.CalendarCollectionId);
FolderDeleteResponse folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
Site.Assert.IsNotNull(folderDeleteResponse.ResponseData, "The FolderDelete element should not be null.");
Site.Assert.IsNotNull(folderDeleteResponse.ResponseData.Status, "As child element of FolderDelete, the Status should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "MS-ASCMD_R99");
// Since the FolderDelete and Status element are not null, server sends a response indicating the status of the deletion.
// Verify MS-ASCMD requirement: MS-ASCMD_R99
Site.CaptureRequirement(
99,
@"[In FolderDelete] The server then sends a response indicating the status of the deletion.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R101");
// The server should return a status code 3 in the FolderDelete command response to indicate the specified folder is a special folder.
// Verify MS-ASCMD requirement: MS-ASCMD_R101
Site.CaptureRequirementIfAreEqual<int>(
3,
int.Parse(folderDeleteResponse.ResponseData.Status),
101,
@"[In FolderDelete] Attempting to delete a recipient information cache using this command results in a Status element (section 2.2.3.162.3) value of 3.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4046");
// The server should return a status code 3 in the FolderDelete command response to indicate the specified folder is a special folder.
// Verify MS-ASCMD requirement: MS-ASCMD_R4046
Site.CaptureRequirementIfAreEqual<int>(
3,
int.Parse(folderDeleteResponse.ResponseData.Status),
4046,
@"[In Status(FolderDelete)] [When the scope is] Item, [the meaning of the status value] 3 [is] The specified folder is a special system folder, such as the Inbox folder, Outbox folder, Contacts folder, Recipient information, or Drafts folder, and cannot be deleted by the client.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4047");
// The server should return a status code 3 in the FolderDelete command response to indicate the specified folder is a special folder.
// Verify MS-ASCMD requirement: MS-ASCMD_R4047
Site.CaptureRequirementIfAreEqual<int>(
3,
int.Parse(folderDeleteResponse.ResponseData.Status),
4047,
@"[In Status(FolderDelete)] [When the scope is Item], [the cause of the status value 3 is] The client specified a special folder in a FolderDelete command request (section 2.2.2.3). special folders cannot be deleted.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4040");
// The server should return a status code 3 in the FolderDelete command response to indicate the specified folder is a special folder.
// Verify MS-ASCMD requirement: MS-ASCMD_R4040
Site.CaptureRequirementIfAreEqual<int>(
3,
int.Parse(folderDeleteResponse.ResponseData.Status),
4040,
@"[In Status(FolderDelete)] If the command failed, the Status element in the server response contains a code indicating the type of failure.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5785");
// If the FolderDelete command request fails, server returns a null SyncKey.
// Verify MS-ASCMD requirement: MS-ASCMD_R5785
Site.CaptureRequirementIfIsNull(
folderDeleteResponse.ResponseData.SyncKey,
5785,
@"[In SyncKey(FolderCreate, FolderDelete, and FolderUpdate)] If the [FolderCreate command,] FolderDelete command [, or FolderUpdate command] is not successful, the server MUST NOT return a SyncKey element.");
// The recipient information cache is not supported when the value of the MS-ASProtocolVersion header is set to 12.1.
// MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.
if ("12.1" != Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site))
{
// Call method FolderDelete to delete a recipient information cache from the server.
folderDeleteRequest = Common.CreateFolderDeleteRequest(this.LastFolderSyncKey, "RI");
folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
Site.Assert.IsNotNull(folderDeleteResponse.ResponseData, "The FolderDelete element should not be null.");
Site.Assert.IsNotNull(folderDeleteResponse.ResponseData.Status, "As child element of FolderDelete, the Status should not be null.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R100");
// The server should return a status code 3 in the FolderDelete command response to indicate the specified folder is a special folder.
// Verify MS-ASCMD requirement: MS-ASCMD_R100
Site.CaptureRequirementIfAreEqual<int>(
3,
int.Parse(folderDeleteResponse.ResponseData.Status),
100,
@"[In FolderDelete] The FolderDelete command cannot be used to delete a recipient information cache.");
}
}
/// <summary>
/// This test case is used to verify FolderDelete command, if the specified folder does not exist, the status in return value is 4.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S03_TC03_FolderDelete_Status4()
{
// Call method FolderDelete to delete an invalid folder from the server.
FolderDeleteRequest folderDeleteRequest = Common.CreateFolderDeleteRequest(this.LastFolderSyncKey, "InvalidServerId");
FolderDeleteResponse folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4048");
// The server should return a status code 4 in the FolderDelete command response to indicate the specified folder does not exist.
// Verify MS-ASCMD requirement: MS-ASCMD_R4048
Site.CaptureRequirementIfAreEqual<int>(
4,
int.Parse(folderDeleteResponse.ResponseData.Status),
4048,
@"[In Status(FolderDelete)] [When the scope is] Item, [the meaning of the status value] 4 [is] The specified folder does not exist.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4049");
// The server should return a status code 4 in the FolderDelete command response to indicate the specified folder does not exist.
// Verify MS-ASCMD requirement: MS-ASCMD_R4049
Site.CaptureRequirementIfAreEqual<int>(
4,
int.Parse(folderDeleteResponse.ResponseData.Status),
4049,
@"[In Status(FolderDelete)] [When the scope is Item], [the cause of the status value 4 is] The client specified a nonexistent folder in a FolderDelete command request.");
}
/// <summary>
/// This test case is used to verify FolderDelete command, if the SyncKey is an empty string, the status in return value is 9.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S03_TC04_FolderDelete_Status9()
{
#region Call method FolderCreate to create a new folder as a child folder of the specified parent folder.
FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderDelete"), "0");
Site.Assert.AreEqual<int>(
1,
int.Parse(folderCreateResponse.ResponseData.Status),
"The server should return a status code 1 in the FolderCreate command response to indicate success.");
#endregion
#region Call method FolderDelete to delete a folder from the server, and set SyncKey value to an empty string.
FolderDeleteRequest folderDeleteRequest = Common.CreateFolderDeleteRequest(string.Empty, folderCreateResponse.ResponseData.ServerId);
FolderDeleteResponse folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4060");
// Verify MS-ASCMD requirement: MS-ASCMD_R4060
Site.CaptureRequirementIfAreEqual<int>(
9,
int.Parse(folderDeleteResponse.ResponseData.Status),
4060,
@"[In Status(FolderDelete)] [When the scope is Global], [the cause of the status value 9 is] The client sent a malformed or mismatched synchronization key [, or the synchronization state is corrupted on the server].");
#endregion
#region Call method FolderDelete to delete the created folder from the server.
folderDeleteRequest = Common.CreateFolderDeleteRequest(folderCreateResponse.ResponseData.SyncKey, folderCreateResponse.ResponseData.ServerId);
folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
Site.Assert.AreEqual<int>(1, int.Parse(folderDeleteResponse.ResponseData.Status), "The created Folder should be deleted.");
#endregion
}
/// <summary>
/// This test case is used to verify FolderDelete command, if the request contains a semantic or syntactic error, the status in return value is 10.
/// </summary>
[TestCategory("MSASCMD"), TestMethod()]
public void MSASCMD_S03_TC05_FolderDelete_Status10()
{
#region Call method FolderCreate to create a new folder as a child folder of the specified parent folder.
FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderDelete"), "0");
Site.Assert.AreEqual<int>(1, int.Parse(folderCreateResponse.ResponseData.Status), "If the FolderCreate command creates a folder successfully, server should return a status code 1.");
#endregion
#region Call method FolderDelete without folder SyncKey to delete a folder from the server.
FolderDeleteRequest folderDeleteRequest = Common.CreateFolderDeleteRequest(null, folderCreateResponse.ResponseData.ServerId);
FolderDeleteResponse folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4063");
// Verify MS-ASCMD requirement: MS-ASCMD_R4063
Site.CaptureRequirementIfAreEqual<int>(
10,
int.Parse(folderDeleteResponse.ResponseData.Status),
4063,
@"[In Status(FolderDelete)] [When the scope is Global], [the cause of the status value 10 is] The client sent a FolderCreate command request (section 2.2.2.3) that contains a semantic or syntactic error.");
#endregion
#region Call method FolderDelete to delete the created folder from the server.
folderDeleteRequest = Common.CreateFolderDeleteRequest(folderCreateResponse.ResponseData.SyncKey, folderCreateResponse.ResponseData.ServerId);
folderDeleteResponse = this.CMDAdapter.FolderDelete(folderDeleteRequest);
Site.Assert.AreEqual<int>(1, int.Parse(folderDeleteResponse.ResponseData.Status), "The server should return a status code 1 in the FolderDelete command response to indicate success.");
#endregion
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/16/2009 5:25:17 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Xml.Serialization;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// LegendItem
/// </summary>
[Serializable]
public class LegendItem : Descriptor, ILegendItem
{
#region Events
/// <summary>
/// Occurs whenever the symbol content has been updated
/// </summary>
public event EventHandler ItemChanged;
/// <summary>
/// Occurs whenever the item should be removed from the parent collection
/// </summary>
public event EventHandler RemoveItem;
#endregion
#region Private Variables
// Legend Item properties
//private IChangeEventList<ILegendItem> _legendItems; // not used by mapwindow, but can be used by developers
private bool _changeOccured;
private bool _checked;
private bool _isDragable;
private bool _isExpanded;
private bool _isLegendGroup;
private bool _isSelected;
private int _itemChangedSuspend;
private bool _legendItemVisible;
private SymbolMode _legendSymbolMode;
private Size _legendSymbolSize;
private string _legendText;
private bool _legendTextReadInly;
private LegendType _legendType;
private List<SymbologyMenuItem> _menuItems;
private ILegendItem _parentLegendItem;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the legend item
/// </summary>
public LegendItem()
{
Configure();
}
/// <summary>
/// Configures the default settings of the legend item
/// </summary>
private void Configure()
{
_legendItemVisible = true;
_isSelected = false;
_isExpanded = false;
_legendSymbolMode = SymbolMode.Symbol;
_legendSymbolSize = new Size(16, 16);
_isDragable = false;
_legendType = LegendType.Symbol;
}
#endregion
#region Methods
/// <summary>
/// Returns a boolean indicating whether or not this item can have other items dropped on it.
/// By default this is false. This can be overridden for more customized behaviors.
/// </summary>
/// <param name="item">The item to test for dropping.</param>
/// <returns></returns>
public virtual bool CanReceiveItem(ILegendItem item)
{
if (LegendType == LegendType.Scheme)
{
if (item.LegendType == LegendType.Symbol) return true;
return false;
}
if (LegendType == LegendType.Group)
{
if (item.LegendType == LegendType.Symbol) return false;
if (item.LegendType == LegendType.Scheme) return false;
return true;
}
if (LegendType == LegendType.Layer)
{
if (item.LegendType == LegendType.Symbol) return true;
if (item.LegendType == LegendType.Scheme) return true;
return false;
}
if (LegendType == LegendType.Symbol)
{
return false;
}
return false;
}
/// <summary>
/// Draws the symbol for this specific category to the legend
/// </summary>
/// <param name="g"></param>
/// <param name="box"></param>
public virtual void LegendSymbol_Painted(Graphics g, Rectangle box)
{
// throw new NotImplementedException("This should be implemented in a sub-class");
}
/// <summary>
/// Prints the formal legend content without any resize boxes or other notations.
/// </summary>
/// <param name="g">The graphics object to print to</param>
/// <param name="font">The system.Drawing.Font to use for the lettering</param>
/// <param name="fontColor">The color of the font</param>
/// <param name="maxExtent">Assuming 0, 0 is the top left, this is the maximum extent</param>
public void PrintLegendItem(Graphics g, Font font, Color fontColor, SizeF maxExtent)
{
string text = LegendText;
if (text == null)
{
ILegendItem parent = GetParentItem();
if (parent != null)
{
if (parent.LegendItems.Count() == 1)
{
// go ahead and use the layer name, but only if this is the only category and the legend text is null
text = parent.LegendText;
}
}
}
// if LegendText is null, the measure string helpfully chooses a height that is 0, so use a fake text for height calc
SizeF emptyString = g.MeasureString("Sample text", font);
float h = emptyString.Height;
float x = 0;
bool drawBox = false;
if (LegendSymbolMode == SymbolMode.Symbol)
{
drawBox = true;
x = h * 2 + 4;
}
Brush b = new SolidBrush(fontColor);
StringFormat frmt = new StringFormat
{
Alignment = StringAlignment.Near,
Trimming = StringTrimming.EllipsisCharacter
};
float w = maxExtent.Width - x;
g.DrawString(text, font, b, new RectangleF(x, 2, w, h), frmt);
if (drawBox) LegendSymbol_Painted(g, new Rectangle(2, 2, (int)x - 4, (int)h));
b.Dispose();
}
/// <summary>
/// Handles updating event handlers during a copy process
/// </summary>
/// <param name="copy"></param>
protected override void OnCopy(Descriptor copy)
{
LegendItem myCopy = copy as LegendItem;
if (myCopy != null && myCopy.ItemChanged != null)
{
foreach (Delegate handler in myCopy.ItemChanged.GetInvocationList())
{
myCopy.ItemChanged -= (EventHandler)handler;
}
}
if (myCopy != null && myCopy.RemoveItem != null)
{
foreach (Delegate handler in myCopy.RemoveItem.GetInvocationList())
{
myCopy.RemoveItem -= (EventHandler)handler;
}
}
base.OnCopy(copy);
}
/// <summary>
/// Allows the ItemChanged event to fire in response to individual changes again.
/// This will also fire the event once if there were any changes that warent it
/// that were made while the event was suspended.
/// </summary>
public void ResumeChangeEvent()
{
_itemChangedSuspend -= 1;
if (_itemChangedSuspend == 0)
{
if (_changeOccured)
{
#if DEBUG
var sw = new Stopwatch();
sw.Start();
#endif
OnItemChanged();
#if DEBUG
sw.Stop();
Debug.WriteLine("OnItemChanged time:" + sw.ElapsedMilliseconds);
#endif
}
}
// Prevent forcing extra negatives.
if (_itemChangedSuspend < 0) _itemChangedSuspend = 0;
}
/// <summary>
/// Each suspend call increments an integer, essentially keeping track of the depth of
/// suspension. When the same number of ResumeChangeEvents methods have been called
/// as SuspendChangeEvents have been called, the suspension is aborted and the
/// legend item is allowed to broadcast its changes.
/// </summary>
public void SuspendChangeEvent()
{
if (_itemChangedSuspend == 0)
{
_changeOccured = false;
}
_itemChangedSuspend += 1;
}
#endregion
#region Properties
/// <summary>
/// Boolean, true if changes are suspended
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
XmlIgnore]
public bool ChangesSuspended
{
get { return (_itemChangedSuspend > 0); }
}
/// <summary>
/// Gets or sets a boolean that indicates whether or not this legend item can be dragged to a new position in the legend.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDragable
{
get { return _isDragable; }
set { _isDragable = value; }
}
/// <summary>
/// Gets or sets a boolean, that if false will prevent this item, or any of its child items
/// from appearing in the legend when the legend is drawn.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool LegendItemVisible
{
get { return _legendItemVisible; }
set { _legendItemVisible = value; }
}
/// <summary>
/// Because these are in symbol mode, this is not used.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool Checked
{
get
{
return _checked;
}
set
{
_checked = value;
}
}
/// <summary>
/// Gets the MenuItems that should appear in the context menu of the legend for this category
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
XmlIgnore]
public virtual List<SymbologyMenuItem> ContextMenuItems
{
get { return _menuItems; }
set { _menuItems = value; }
}
/// <summary>
/// Gets or sets a boolean that indicates whether or not the legend should draw the child LegendItems for this category.
/// </summary>
[Serialize("IsExpanded")]
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool IsExpanded
{
get
{
return _isExpanded;
}
set
{
_isExpanded = value;
}
}
/// <summary>
/// Gets or sets whether this legend item has been selected in the legend
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool IsSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
}
}
/// <summary>
/// Gets whatever the child collection is and returns it as an IEnumerable set of legend items
/// in order to make it easier to cycle through those values. This defaults to null and must
/// be overridden in specific cases where child legend items exist.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IEnumerable<ILegendItem> LegendItems
{
get { return null; }
}
/// <summary>
/// Gets or sets the symbol mode for the legend. By default this should be "Symbol", but this can be overridden
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual SymbolMode LegendSymbolMode
{
get { return _legendSymbolMode; }
protected set { _legendSymbolMode = value; }
}
/// <summary>
/// Gets or sets the size of the symbol to be drawn to the legend
/// </summary>
public virtual Size GetLegendSymbolSize()
{
return _legendSymbolSize;
}
/// <summary>
/// Gets or sets the text for this category to appear in the legend. This might be a category name,
/// or a range of values.
/// </summary>
[Description("Gets or sets the text for this category to appear in the legend.")]
[Browsable(false), Serialize("LegendText")]
public virtual string LegendText
{
get
{
return _legendText;
}
set
{
if (value == _legendText) return;
_legendText = value;
OnItemChanged(this);
}
}
/// <summary>
/// Indicates whether the user can change the legend text in GUI.
/// </summary>
[Description("Indicates whether the user can change the legend text in GUI.")]
[Browsable(false), Serialize("LegendTextReadOnly")]
public virtual bool LegendTextReadOnly
{
get
{
return _legendTextReadInly;
}
set
{
if (value == _legendTextReadInly) return;
_legendTextReadInly = value;
OnItemChanged(this);
}
}
/// <summary>
/// Gets or sets a pre-defined behavior in the legend when referring to drag and drop functionality.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public LegendType LegendType
{
get { return _legendType; }
protected set { _legendType = value; }
}
/// <summary>
/// Gets the Parent Legend item for this category. This should probably be the appropriate layer item.
/// </summary>
public ILegendItem GetParentItem()
{
return _parentLegendItem;
}
/// <summary>
/// Sets the parent legend item for this category.
/// </summary>
/// <param name="value"></param>
public void SetParentItem(ILegendItem value)
{
OnSetParentItem(value);
}
/// <summary>
/// Allows for the set behavior for the parent item to be overridden in child classes
/// </summary>
/// <param name="value"></param>
protected virtual void OnSetParentItem(ILegendItem value)
{
_parentLegendItem = value;
}
#endregion
#region Protected Methods
/// <summary>
/// If this is true, then "can receive
/// </summary>
[Serialize("IsLegendGroup")]
protected bool IsLegendGroup
{
get { return _isLegendGroup; }
set { _isLegendGroup = value; }
}
/// <summary>
/// Fires the ItemChanged event
/// </summary>
protected virtual void OnItemChanged()
{
OnItemChanged(this);
}
/// <summary>
/// Fires the ItemChanged event, optionally specifying a different
/// sender
/// </summary>
protected virtual void OnItemChanged(object sender)
{
if (_itemChangedSuspend > 0)
{
_changeOccured = true;
return;
}
if (ItemChanged == null) return;
ItemChanged(sender, EventArgs.Empty);
}
/// <summary>
/// Instructs the parent legend item to remove this item from the list of legend items.
/// </summary>
protected virtual void OnRemoveItem()
{
if (RemoveItem != null) RemoveItem(this, EventArgs.Empty);
// Maybe we don't need RemoveItem event. We could just invoke a method on the parent.
// One less thing to wire. But we currently need to wire parents.
}
#endregion
}
}
| |
#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
//Authors: Roman Ivantsov - initial implementation and some later edits
// Philipp Serr - implementation of advanced features for c#, python, VB
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Diagnostics;
using Irony.Ast;
namespace Irony.Parsing
{
using BigInteger = System.Numerics.BigInteger; //Microsoft.Scripting.Math.BigInteger;
using Complex64 = System.Numerics.Complex;
using Irony.Ast; // Microsoft.Scripting.Math.Complex64;
[Flags]
public enum NumberOptions
{
None = 0,
Default = None,
AllowStartEndDot = 0x01, //python : http://docs.python.org/ref/floating.html
IntOnly = 0x02,
NoDotAfterInt = 0x04, //for use with IntOnly flag; essentially tells terminal to avoid matching integer if
// it is followed by dot (or exp symbol) - leave to another terminal that will handle float numbers
AllowSign = 0x08,
DisableQuickParse = 0x10,
AllowLetterAfter = 0x20, // allow number be followed by a letter or underscore; by default this flag is not set, so "3a" would not be
// recognized as number followed by an identifier
AllowUnderscore = 0x40, // Ruby allows underscore inside number: 1_234
//The following should be used with base-identifying prefixes
Binary = 0x0100, //e.g. GNU GCC C Extension supports binary number literals
Octal = 0x0200,
Hex = 0x0400,
}
public class NumberLiteral : CompoundTerminalBase
{
//Flags for internal use
public enum NumberFlagsInternal : short
{
HasDot = 0x1000,
HasExp = 0x2000,
}
//nested helper class
public class ExponentsTable : Dictionary<char, TypeCode> { }
#region Public Consts
//currently using TypeCodes for identifying numeric types
public const TypeCode TypeCodeBigInt = (TypeCode)30;
public const TypeCode TypeCodeImaginary = (TypeCode)31;
#endregion
#region constructors and initialization
public NumberLiteral(string name)
: this(name, NumberOptions.Default)
{
}
public NumberLiteral(string name, NumberOptions options, Type astNodeType)
: this(name, options)
{
base.AstConfig.NodeType = astNodeType;
}
public NumberLiteral(string name, NumberOptions options, AstNodeCreator astNodeCreator)
: this(name, options)
{
base.AstConfig.NodeCreator = astNodeCreator;
}
public NumberLiteral(string name, NumberOptions options)
: base(name)
{
Options = options;
base.SetFlag(TermFlags.IsLiteral);
}
public void AddPrefix(string prefix, NumberOptions options)
{
PrefixFlags.Add(prefix, (short)options);
Prefixes.Add(prefix);
}
public void AddExponentSymbols(string symbols, TypeCode floatType)
{
foreach (var exp in symbols)
_exponentsTable[exp] = floatType;
}
#endregion
#region Public fields/properties: ExponentSymbols, Suffixes
public NumberOptions Options;
public char DecimalSeparator = '.';
//Default types are assigned to literals without suffixes; first matching type used
public TypeCode[] DefaultIntTypes = new TypeCode[] { TypeCode.Int32 };
public TypeCode DefaultFloatType = TypeCode.Double;
private ExponentsTable _exponentsTable = new ExponentsTable();
public bool IsSet(NumberOptions option)
{
return (Options & option) != 0;
}
#endregion
#region Private fields: _quickParseTerminators
#endregion
#region overrides
public override void Init(GrammarData grammarData)
{
base.Init(grammarData);
//Default Exponent symbols if table is empty
if (_exponentsTable.Count == 0 && !IsSet(NumberOptions.IntOnly))
{
_exponentsTable['e'] = DefaultFloatType;
_exponentsTable['E'] = DefaultFloatType;
}
if (this.EditorInfo == null)
this.EditorInfo = new TokenEditorInfo(TokenType.Literal, TokenColor.Number, TokenTriggers.None);
}
public override IList<string> GetFirsts()
{
StringList result = new StringList();
result.AddRange(base.Prefixes);
//we assume that prefix is always optional, so number can always start with plain digit
result.AddRange(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" });
// Python float numbers can start with a dot
if (IsSet(NumberOptions.AllowStartEndDot))
result.Add(DecimalSeparator.ToString());
if (IsSet(NumberOptions.AllowSign))
result.AddRange(new string[] { "-", "+" });
return result;
}
//Most numbers in source programs are just one-digit instances of 0, 1, 2, and maybe others until 9
// so we try to do a quick parse for these, without starting the whole general process
protected override Token QuickParse(ParsingContext context, ISourceStream source)
{
if (IsSet(NumberOptions.DisableQuickParse)) return null;
char current = source.PreviewChar;
//it must be a digit followed by a whitespace or delimiter
if (!char.IsDigit(current)) return null;
if (!Grammar.IsWhitespaceOrDelimiter(source.NextPreviewChar))
return null;
int iValue = current - '0';
object value = null;
switch (DefaultIntTypes[0])
{
case TypeCode.Int32: value = iValue; break;
case TypeCode.UInt32: value = (UInt32)iValue; break;
case TypeCode.Byte: value = (byte)iValue; break;
case TypeCode.SByte: value = (sbyte)iValue; break;
case TypeCode.Int16: value = (Int16)iValue; break;
case TypeCode.UInt16: value = (UInt16)iValue; break;
default: return null;
}
source.PreviewPosition++;
return source.CreateToken(this.OutputTerminal, value);
}
protected override void InitDetails(ParsingContext context, CompoundTokenDetails details)
{
base.InitDetails(context, details);
details.Flags = (short)this.Options;
}
protected override void ReadPrefix(ISourceStream source, CompoundTokenDetails details)
{
//check that is not a 0 followed by dot;
//this may happen in Python for number "0.123" - we can mistakenly take "0" as octal prefix
if (source.PreviewChar == '0' && source.NextPreviewChar == '.') return;
base.ReadPrefix(source, details);
}//method
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details)
{
//remember start - it may be different from source.TokenStart, we may have skipped prefix
int start = source.PreviewPosition;
char current = source.PreviewChar;
if (IsSet(NumberOptions.AllowSign) && (current == '-' || current == '+'))
{
details.Sign = current.ToString();
source.PreviewPosition++;
}
//Figure out digits set
string digits = GetDigits(details);
bool isDecimal = !details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex));
bool allowFloat = !IsSet(NumberOptions.IntOnly);
bool foundDigits = false;
while (!source.EOF())
{
current = source.PreviewChar;
//1. If it is a digit, just continue going; the same for '_' if it is allowed
if (digits.IndexOf(current) >= 0 || IsSet(NumberOptions.AllowUnderscore) && current == '_')
{
source.PreviewPosition++;
foundDigits = true;
continue;
}
//2. Check if it is a dot in float number
bool isDot = current == DecimalSeparator;
if (allowFloat && isDot)
{
//If we had seen already a dot or exponent, don't accept this one;
bool hasDotOrExp = details.IsSet((short)(NumberFlagsInternal.HasDot | NumberFlagsInternal.HasExp));
if (hasDotOrExp) break; //from while loop
//In python number literals (NumberAllowPointFloat) a point can be the first and last character,
//We accept dot only if it is followed by a digit
if (digits.IndexOf(source.NextPreviewChar) < 0 && !IsSet(NumberOptions.AllowStartEndDot))
break; //from while loop
details.Flags |= (int)NumberFlagsInternal.HasDot;
source.PreviewPosition++;
continue;
}
//3. Check if it is int number followed by dot or exp symbol
bool isExpSymbol = (details.ExponentSymbol == null) && _exponentsTable.ContainsKey(current);
if (!allowFloat && foundDigits && (isDot || isExpSymbol))
{
//If no partial float allowed then return false - it is not integer, let float terminal recognize it as float
if (IsSet(NumberOptions.NoDotAfterInt)) return false;
//otherwise break, it is integer and we're done reading digits
break;
}
//4. Only for decimals - check if it is (the first) exponent symbol
if (allowFloat && isDecimal && isExpSymbol)
{
char next = source.NextPreviewChar;
bool nextIsSign = next == '-' || next == '+';
bool nextIsDigit = digits.IndexOf(next) >= 0;
if (!nextIsSign && !nextIsDigit)
break; //Exponent should be followed by either sign or digit
//ok, we've got real exponent
details.ExponentSymbol = current.ToString(); //remember the exp char
details.Flags |= (int)NumberFlagsInternal.HasExp;
source.PreviewPosition++;
if (nextIsSign)
source.PreviewPosition++; //skip +/- explicitly so we don't have to deal with them on the next iteration
continue;
}
//4. It is something else (not digit, not dot or exponent) - we're done
break; //from while loop
}//while
int end = source.PreviewPosition;
if (!foundDigits)
return false;
details.Body = source.Text.Substring(start, end - start);
return true;
}
protected internal override void OnValidateToken(ParsingContext context)
{
if (!IsSet(NumberOptions.AllowLetterAfter))
{
var current = context.Source.PreviewChar;
if (char.IsLetter(current) || current == '_')
{
context.CurrentToken = context.CreateErrorToken(Resources.ErrNoLetterAfterNum); // "Number cannot be followed by a letter."
}
}
base.OnValidateToken(context);
}
protected override bool ConvertValue(CompoundTokenDetails details)
{
if (String.IsNullOrEmpty(details.Body))
{
details.Error = Resources.ErrInvNumber; // "Invalid number.";
return false;
}
AssignTypeCodes(details);
//check for underscore
if (IsSet(NumberOptions.AllowUnderscore) && details.Body.Contains("_"))
details.Body = details.Body.Replace("_", string.Empty);
//Try quick paths
switch (details.TypeCodes[0])
{
case TypeCode.Int32:
if (QuickConvertToInt32(details)) return true;
break;
case TypeCode.Double:
if (QuickConvertToDouble(details)) return true;
break;
}
//Go full cycle
details.Value = null;
foreach (TypeCode typeCode in details.TypeCodes)
{
switch (typeCode)
{
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCodeImaginary:
return ConvertToFloat(typeCode, details);
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
ConvertToFloat(typeCode, details);
return true;
if (details.Value == null) //if it is not done yet
TryConvertToLong(details, typeCode == TypeCode.UInt64); //try to convert to Long/Ulong and place the result into details.Value field;
if(TryCastToIntegerType(typeCode, details)) //now try to cast the ULong value to the target type
return true;
break;
case TypeCodeBigInt:
if (ConvertToBigInteger(details)) return true;
break;
}//switch
}
return false;
}//method
private void AssignTypeCodes(CompoundTokenDetails details)
{
//Type could be assigned when we read suffix; if so, just exit
if (details.TypeCodes != null) return;
//Decide on float types
var hasDot = details.IsSet((short)(NumberFlagsInternal.HasDot));
var hasExp = details.IsSet((short)(NumberFlagsInternal.HasExp));
var isFloat = (hasDot || hasExp);
if (!isFloat)
{
details.TypeCodes = DefaultIntTypes;
return;
}
//so we have a float. If we have exponent symbol then use it to select type
if (hasExp)
{
TypeCode code;
if (_exponentsTable.TryGetValue(details.ExponentSymbol[0], out code))
{
details.TypeCodes = new TypeCode[] { code };
return;
}
}//if hasExp
//Finally assign default float type
details.TypeCodes = new TypeCode[] { DefaultFloatType };
}
#endregion
#region private utilities
private bool QuickConvertToInt32(CompoundTokenDetails details)
{
int radix = GetRadix(details);
if (radix == 10 && details.Body.Length > 10) return false; //10 digits is maximum for int32; int32.MaxValue = 2 147 483 647
try
{
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
int iValue = 0;
if (radix == 10)
iValue = Convert.ToInt32(details.Body, CultureInfo.InvariantCulture);
else
iValue = Convert.ToInt32(details.Body, radix);
details.Value = iValue;
return true;
}
catch
{
return false;
}
}//method
private bool QuickConvertToDouble(CompoundTokenDetails details)
{
if (details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex))) return false;
if (details.IsSet((short)(NumberFlagsInternal.HasExp))) return false;
if (DecimalSeparator != '.') return false;
double dvalue;
if (!double.TryParse(details.Body, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dvalue)) return false;
details.Value = dvalue;
return true;
}
private bool ConvertToFloat(TypeCode typeCode, CompoundTokenDetails details)
{
//only decimal numbers can be fractions
if (details.IsSet((short)(NumberOptions.Binary | NumberOptions.Octal | NumberOptions.Hex)))
{
details.Error = Resources.ErrInvNumber; // "Invalid number.";
return false;
}
string body = details.Body;
//Some languages allow exp symbols other than E. Check if it is the case, and change it to E
// - otherwise .NET conversion methods may fail
if (details.IsSet((short)NumberFlagsInternal.HasExp) && details.ExponentSymbol.ToUpper() != "E")
body = body.Replace(details.ExponentSymbol, "E");
//'.' decimal seperator required by invariant culture
if (details.IsSet((short)NumberFlagsInternal.HasDot) && DecimalSeparator != '.')
body = body.Replace(DecimalSeparator, '.');
switch (typeCode)
{
case TypeCode.Double:
case TypeCodeImaginary:
double dValue;
if (!Double.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out dValue)) return false;
if (typeCode == TypeCodeImaginary)
details.Value = new Complex64(0, dValue);
else
details.Value = dValue;
return true;
case TypeCode.Single:
float fValue;
if (!Single.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out fValue)) return false;
details.Value = fValue;
return true;
case TypeCode.Decimal:
decimal decValue;
if (!Decimal.TryParse(body, NumberStyles.Float, CultureInfo.InvariantCulture, out decValue)) return false;
details.Value = decValue;
return true;
}//switch
return false;
}
private bool TryCastToIntegerType(TypeCode typeCode, CompoundTokenDetails details)
{
if (details.Value == null) return false;
try
{
if (typeCode != TypeCode.UInt64)
details.Value = Convert.ChangeType(details.Value, typeCode, CultureInfo.InvariantCulture);
return true;
}
catch (Exception)
{
details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, typeCode.ToString());
return false;
}
}//method
private bool TryConvertToLong(CompoundTokenDetails details, bool useULong)
{
try
{
int radix = GetRadix(details);
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
if (radix == 10)
if (useULong)
details.Value = Convert.ToUInt64(details.Body, CultureInfo.InvariantCulture);
else
details.Value = Convert.ToInt64(details.Body, CultureInfo.InvariantCulture);
else
if (useULong)
details.Value = Convert.ToUInt64(details.Body, radix);
else
details.Value = Convert.ToInt64(details.Body, radix);
return true;
}
catch (OverflowException)
{
details.Error = string.Format(Resources.ErrCannotConvertValueToType, details.Value, TypeCode.Int64.ToString());
return false;
}
}
private bool ConvertToBigInteger(CompoundTokenDetails details)
{
//ignore leading zeros and sign
details.Body = details.Body.TrimStart('+').TrimStart('-').TrimStart('0');
if (string.IsNullOrEmpty(details.Body))
details.Body = "0";
int bodyLength = details.Body.Length;
int radix = GetRadix(details);
int wordLength = GetSafeWordLength(details);
int sectionCount = GetSectionCount(bodyLength, wordLength);
ulong[] numberSections = new ulong[sectionCount]; //big endian
try
{
int startIndex = details.Body.Length - wordLength;
for (int sectionIndex = sectionCount - 1; sectionIndex >= 0; sectionIndex--)
{
if (startIndex < 0)
{
wordLength += startIndex;
startIndex = 0;
}
//workaround for .Net FX bug: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
if (radix == 10)
numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength));
else
numberSections[sectionIndex] = Convert.ToUInt64(details.Body.Substring(startIndex, wordLength), radix);
startIndex -= wordLength;
}
}
catch
{
details.Error = Resources.ErrInvNumber;// "Invalid number.";
return false;
}
//produce big integer
ulong safeWordRadix = GetSafeWordRadix(details);
BigInteger bigIntegerValue = numberSections[0];
for (int i = 1; i < sectionCount; i++)
bigIntegerValue = checked(bigIntegerValue * safeWordRadix + numberSections[i]);
if (details.Sign == "-")
bigIntegerValue = -bigIntegerValue;
details.Value = bigIntegerValue;
return true;
}
private int GetRadix(CompoundTokenDetails details)
{
if (details.IsSet((short)NumberOptions.Hex))
return 16;
if (details.IsSet((short)NumberOptions.Octal))
return 8;
if (details.IsSet((short)NumberOptions.Binary))
return 2;
return 10;
}
private string GetDigits(CompoundTokenDetails details)
{
if (details.IsSet((short)NumberOptions.Hex))
return Strings.HexDigits;
if (details.IsSet((short)NumberOptions.Octal))
return Strings.OctalDigits;
if (details.IsSet((short)NumberOptions.Binary))
return Strings.BinaryDigits;
return Strings.DecimalDigits;
}
private int GetSafeWordLength(CompoundTokenDetails details)
{
if (details.IsSet((short)NumberOptions.Hex))
return 15;
if (details.IsSet((short)NumberOptions.Octal))
return 21; //maxWordLength 22
if (details.IsSet((short)NumberOptions.Binary))
return 63;
return 19; //maxWordLength 20
}
private int GetSectionCount(int stringLength, int safeWordLength)
{
int quotient = stringLength / safeWordLength;
int remainder = stringLength - quotient * safeWordLength;
return remainder == 0 ? quotient : quotient + 1;
}
//radix^safeWordLength
private ulong GetSafeWordRadix(CompoundTokenDetails details)
{
if (details.IsSet((short)NumberOptions.Hex))
return 1152921504606846976;
if (details.IsSet((short)NumberOptions.Octal))
return 9223372036854775808;
if (details.IsSet((short)NumberOptions.Binary))
return 9223372036854775808;
return 10000000000000000000;
}
private static bool IsIntegerCode(TypeCode code)
{
return (code >= TypeCode.SByte && code <= TypeCode.UInt64);
}
#endregion
}//class
}
| |
using System.Collections.Generic;
using Kayak.Http;
using NUnit.Framework;
using Rhino.Mocks;
namespace HttpMock.Unit.Tests
{
[TestFixture]
public class EndpointMatchingRuleTests
{
[Test]
public void urls_match_it_returns_true( ) {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.QueryParams = new Dictionary<string, string>();
var httpRequestHead = new HttpRequestHead { Uri = "test" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
[Test]
public void urls_and_methods_the_same_it_returns_true() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "PUT";
requestHandler.QueryParams = new Dictionary<string, string>();
var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "PUT" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
[Test]
public void urls_and_methods_differ_it_returns_false() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string>();
var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "PUT" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False);
}
[Test]
public void urls_differ_and_methods_match_it_returns_false() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "pest";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string>();
var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False);
}
[Test]
public void urls_and_methods_match_queryparams_differ_it_returns_false() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } };
var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False);
}
[Test]
public void urls_and_methods_match_and_queryparams_exist_it_returns_true() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } };
var httpRequestHead = new HttpRequestHead { Uri = "test?oauth_consumer_key=test-api&elvis=alive&moonlandings=faked&myParam=one", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
[Test]
public void urls_and_methods_match_and_queryparams_does_not_exist_it_returns_false() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } };
var httpRequestHead = new HttpRequestHead { Uri = "test?oauth_consumer_key=test-api&elvis=alive&moonlandings=faked", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False);
}
[Test]
public void urls_and_methods_match_and_no_query_params_are_set_but_request_has_query_params_returns_true()
{
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string> ();
var httpRequestHead = new HttpRequestHead { Uri = "test?oauth_consumer_key=test-api&elvis=alive&moonlandings=faked", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.True);
}
[Test]
public void urls_and_methods_and_queryparams_match_it_returns_true() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string>{{"myParam", "one"}};
var httpRequestHead = new HttpRequestHead { Uri = "test?myParam=one", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
[Test]
public void urls_and_methods_match_headers_differ_it_returns_false() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string>();
requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } };
var httpRequestHead = new HttpRequestHead
{
Uri = "test",
Method = "GET",
Headers = new Dictionary<string, string>
{
{ "myHeader", "two" }
}
};
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False);
}
[Test]
public void urls_and_methods_match_and_headers_match_it_returns_true() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string>();
requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } };
var httpRequestHead = new HttpRequestHead
{
Uri = "test",
Method = "GET",
Headers = new Dictionary<string, string>
{
{ "myHeader", "one" },
{ "anotherHeader", "two" }
}
};
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
[Test]
public void urls_and_methods_match_and_header_does_not_exist_it_returns_false() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string>();
requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } };
var httpRequestHead = new HttpRequestHead { Uri = "test", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead), Is.False);
}
[Test]
public void should_do_a_case_insensitive_match_on_query_string_parameter_values() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string> { { "myParam", "one" } };
var httpRequestHead = new HttpRequestHead { Uri = "test?myParam=OnE", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
[Test]
public void should_do_a_case_insensitive_match_on_header_names_and_values() {
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string>();
requestHandler.RequestHeaders = new Dictionary<string, string> { { "myHeader", "one" } };
var httpRequestHead = new HttpRequestHead
{
Uri = "test",
Method = "GET",
Headers = new Dictionary<string, string>
{
{ "MYheaDER", "OnE" }
}
};
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
[Test]
public void should_match_when_the_query_string_has_a_trailing_ampersand()
{
var requestHandler = MockRepository.GenerateStub<IRequestHandler>();
requestHandler.Path = "test";
requestHandler.Method = "GET";
requestHandler.QueryParams = new Dictionary<string, string> { { "a", "b" } ,{"c","d"}};
var httpRequestHead = new HttpRequestHead { Uri = "test?a=b&c=d&", Method = "GET" };
var endpointMatchingRule = new EndpointMatchingRule();
Assert.That(endpointMatchingRule.IsEndpointMatch(requestHandler, httpRequestHead));
}
}
[TestFixture]
public class RequestMatcherTests
{
[Test]
public void Should_match_a_handler()
{
var expectedRequest = MockRepository.GenerateStub<IRequestHandler>();
expectedRequest.Method = "GET";
expectedRequest.Path = "/path";
expectedRequest.QueryParams = new Dictionary<string, string>();
expectedRequest.Stub(s => s.CanVerifyConstraintsFor("")).IgnoreArguments().Return(true);
var requestMatcher = new RequestMatcher(new EndpointMatchingRule());
var requestHandlerList = new List<IRequestHandler>{expectedRequest};
var httpRequestHead = new HttpRequestHead{Method = "GET", Path = "/path/", Uri = "/path"};
var matchedRequest = requestMatcher.Match(httpRequestHead, requestHandlerList);
Assert.That(matchedRequest.Path, Is.EqualTo(expectedRequest.Path));
}
[Test]
public void Should_match_a_specific_handler()
{
var expectedRequest = MockRepository.GenerateStub<IRequestHandler>();
expectedRequest.Method = "GET";
expectedRequest.Path = "/path/specific";
expectedRequest.QueryParams = new Dictionary<string, string>();
expectedRequest.Stub(s => s.CanVerifyConstraintsFor("")).IgnoreArguments().Return(true);
var otherRequest = MockRepository.GenerateStub<IRequestHandler>();
otherRequest.Method = "GET";
otherRequest.Path = "/path/";
otherRequest.QueryParams = new Dictionary<string, string>();
otherRequest.Stub(s => s.CanVerifyConstraintsFor("")).IgnoreArguments().Return(true);
var requestMatcher = new RequestMatcher(new EndpointMatchingRule());
var requestHandlerList = new List<IRequestHandler> { otherRequest, expectedRequest };
var httpRequestHead = new HttpRequestHead { Method = "GET", Path = "/path/specific", Uri = "/path/specific" };
var matchedRequest = requestMatcher.Match(httpRequestHead, requestHandlerList);
Assert.That(matchedRequest.Path, Is.EqualTo(expectedRequest.Path));
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Net;
using System.Reflection;
using log4net;
using log4net.Config;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
namespace OpenSim
{
/// <summary>
/// Starting class for the OpenSimulator Region
/// </summary>
public static class Application
{
/// <summary>
/// Text Console Logger
/// </summary>
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Save Crashes in the bin/crashes folder. Configurable with m_crashDir
/// </summary>
public static bool m_saveCrashDumps = false;
/// <summary>
/// Directory to save crash reports to. Relative to bin/
/// </summary>
public static string m_crashDir = "crashes";
/// <summary>
/// Instance of the OpenSim class. This could be OpenSim or OpenSimBackground depending on the configuration
/// </summary>
private static OpenSimBase m_sim = null;
//could move our main function into OpenSimMain and kill this class
public static void Main(string[] args)
{
// First line, hook the appdomain to the crash reporter
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
ServicePointManager.DefaultConnectionLimit = 12;
// Add the arguments supplied when running the application to the configuration
ArgvConfigSource configSource = new ArgvConfigSource(args);
// Configure Log4Net
configSource.AddSwitch("Startup", "logconfig");
string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);
if (!String.IsNullOrEmpty(logConfigFile))
{
XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
m_log.InfoFormat("[HALCYON MAIN]: configured log4net using \"{0}\" as configuration file",
logConfigFile);
}
else
{
XmlConfigurator.Configure();
m_log.Info("[HALCYON MAIN]: configured log4net using default Halcyon.exe.config");
}
m_log.Info("Performing compatibility checks... ");
string supported = String.Empty;
if (Util.IsEnvironmentSupported(ref supported))
{
m_log.Info("Environment is compatible.\n");
}
else
{
m_log.Warn("Environment is unsupported (" + supported + ")\n");
}
// Configure nIni aliases and localles
Culture.SetCurrentCulture();
configSource.Alias.AddAlias("On", true);
configSource.Alias.AddAlias("Off", false);
configSource.Alias.AddAlias("True", true);
configSource.Alias.AddAlias("False", false);
configSource.Alias.AddAlias("Yes", true);
configSource.Alias.AddAlias("No", false);
configSource.AddSwitch("Startup", "background");
configSource.AddSwitch("Startup", "inifile");
configSource.AddSwitch("Startup", "inimaster");
configSource.AddSwitch("Startup", "inidirectory");
configSource.AddSwitch("Startup", "gridmode");
configSource.AddSwitch("Startup", "physics");
configSource.AddSwitch("Startup", "gui");
configSource.AddSwitch("Startup", "console");
configSource.AddSwitch("Startup", "save_crashes");
configSource.AddSwitch("Startup", "crash_dir");
configSource.AddConfig("StandAlone");
configSource.AddConfig("Network");
// Check if we're running in the background or not
bool background = configSource.Configs["Startup"].GetBoolean("background", false);
// Check if we're saving crashes
m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);
// load Crash directory config
m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);
if (background)
{
m_sim = new OpenSimBackground(configSource);
m_sim.Startup();
}
else
{
m_sim = new OpenSim(configSource);
m_sim.Startup();
while (true)
{
try
{
// Block thread here for input
MainConsole.Instance.Prompt();
}
catch (Exception e)
{
m_log.ErrorFormat("Command error: {0}", e);
}
}
}
}
private static bool _IsHandlingException = false; // Make sure we don't go recursive on ourself
/// <summary>
/// Global exception handler -- all unhandlet exceptions end up here :)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (_IsHandlingException)
{
return;
}
_IsHandlingException = true;
// TODO: Add config option to allow users to turn off error reporting
// TODO: Post error report (disabled for now)
string msg = String.Empty;
msg += "\r\n";
msg += "APPLICATION EXCEPTION DETECTED: " + e.ToString() + "\r\n";
msg += "\r\n";
msg += "Exception: " + e.ExceptionObject.ToString() + "\r\n";
Exception ex = (Exception) e.ExceptionObject;
if (ex.InnerException != null)
{
msg += "InnerException: " + ex.InnerException.ToString() + "\r\n";
}
msg += "\r\n";
msg += "Application is terminating: " + e.IsTerminating.ToString() + "\r\n";
m_log.ErrorFormat("[APPLICATION]: {0}", msg);
if (m_saveCrashDumps)
{
// Log exception to disk
try
{
if (!Directory.Exists(m_crashDir))
{
Directory.CreateDirectory(m_crashDir);
}
string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
{
m_crashLog.WriteLine(msg);
}
File.Copy("Halcyon.ini", Path.Combine(m_crashDir, log + "_Halcyon.ini"), true);
}
catch (Exception e2)
{
m_log.ErrorFormat("[CRASH LOGGER CRASHED]: {0}", e2);
}
}
_IsHandlingException = false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using FoxTrader.UI.Anim;
using FoxTrader.UI.DragDrop;
using FoxTrader.UI.Input;
using OpenTK.Input;
namespace FoxTrader.UI.Control
{
/// <summary>Base class to display UI elements, handles drawing and colors..</summary>
internal class Canvas : GameControl
{
private readonly List<IDisposable> m_disposeQueue; // dictionary for faster access?
private readonly GameControlDevices m_gameControlDevices;
private readonly KeyData m_keyData = new KeyData();
// These are not created by us, so no disposing
internal GameControl m_firstTab;
private Point m_lastClickedPosition;
internal GameControl m_nextTab;
private float m_scale;
/// <summary>Initializes a new instance of the <see cref="Canvas" /> class</summary>
public Canvas()
{
m_gameControlDevices = FoxTraderWindow.Instance.GetGameControlDevices();
HookKeyboard();
HookMouse();
MouseInputEnabled = true;
KeyboardInputEnabled = true;
SetBounds(0, 0, 10000, 10000);
SetSkin(FoxTraderWindow.Instance.Skin);
Scale = 1.0f;
BackgroundColor = Color.White;
ShouldDrawBackground = false;
m_disposeQueue = new List<IDisposable>();
}
public GameControl MouseFocus
{
get;
internal set;
}
public GameControl HoveredControl
{
get;
internal set;
}
public GameControl KeyboardFocus
{
get;
internal set;
}
// Stupid Keyboard Logic, lol
public bool ShiftKeyToggled
{
get;
internal set;
}
public bool CtrlKeyToggled
{
get;
internal set;
}
public bool MetaKeyToggled
{
get;
internal set;
}
public bool AltKeyToggled
{
get;
internal set;
}
/// <summary>Scale for rendering</summary>
public float Scale
{
get
{
return m_scale;
}
set
{
if (m_scale == value)
{
return;
}
m_scale = value;
if (Skin?.Renderer != null)
{
Skin.Renderer.Scale = m_scale;
}
OnScaleChanged();
Redraw();
}
}
/// <summary>Background color</summary>
public Color BackgroundColor
{
get;
set;
}
/// <summary>In most situations you will be rendering the canvas every frame. But in some situations you will only want to render when there have been changes. You can do this by checking NeedsRedraw</summary>
public bool NeedsRedraw
{
get;
set;
}
private void HookKeyboard()
{
m_gameControlDevices.Keyboard.KeyDown += (c_sender, c_args) =>
{
if (IsHidden || !KeyboardInputEnabled)
{
return;
}
if (c_args.Key == Key.ShiftLeft)
{
ShiftKeyToggled = true;
}
var a_integerKey = (int)c_args.Key;
if (m_keyData.KeyState[a_integerKey])
{
return;
}
m_keyData.KeyState[a_integerKey] = true;
m_keyData.NextRepeat[a_integerKey] = Platform.Neutral.GetTimeInSeconds() + Constants.kKeyRepeatDelay;
m_keyData.KeyEventArgs[a_integerKey] = c_args;
if (KeyboardFocus != null)
{
m_keyData.Target = KeyboardFocus;
KeyboardFocus.OnKeyDown(c_args);
}
else
{
m_keyData.Target = HoveredControl;
HoveredControl?.OnKeyDown(c_args);
}
};
m_gameControlDevices.Keyboard.KeyUp += (c_sender, c_args) =>
{
var a_integerKey = (int)c_args.Key;
m_keyData.KeyState[a_integerKey] = false;
if (IsHidden || !KeyboardInputEnabled)
{
return;
}
if (c_args.Key == Key.ShiftLeft)
{
ShiftKeyToggled = false;
}
if (MouseFocus is Button && c_args.Key == Key.Space)
{
var a_button = HoveredControl as Button;
a_button?.OnClicked(new MouseButtonEventArgs());
}
m_keyData.Target = null;
if (KeyboardFocus != null)
{
KeyboardFocus.OnKeyUp(c_args);
}
else
{
HoveredControl?.OnKeyUp(c_args);
}
};
}
private void HookMouse()
{
m_gameControlDevices.Mouse.Move += (c_sender, c_args) =>
{
if (IsHidden || !MouseInputEnabled)
{
return;
}
if (HoveredControl != null)
{
HoveredControl.OnMouseMoved(c_args);
DragAndDrop.OnMouseMoved(HoveredControl, c_args);
}
var a_hoveredControl = GetControlAt(c_args.X, c_args.Y);
if (HoveredControl != a_hoveredControl)
{
if (HoveredControl != null)
{
HoveredControl.OnMouseOut(c_args);
HoveredControl = null;
}
HoveredControl = a_hoveredControl;
HoveredControl?.OnMouseOver(c_args);
}
};
m_gameControlDevices.Mouse.ButtonDown += (c_sender, c_args) =>
{
if (IsHidden || !MouseInputEnabled)
{
return;
}
if (HoveredControl == null || !HoveredControl.IsMenuComponent)
{
CloseMenus();
}
if (HoveredControl == null || !HoveredControl.IsVisible || HoveredControl == this)
{
return;
}
FindKeyboardFocusedControl(HoveredControl);
if (c_args.Button == MouseButton.Left && DragAndDrop.OnMouseButton(HoveredControl, c_args))
{
return;
}
HoveredControl.OnMouseDown(c_args);
};
m_gameControlDevices.Mouse.ButtonUp += (c_sender, c_args) =>
{
if (IsHidden || !MouseInputEnabled)
{
return;
}
HoveredControl?.OnMouseUp(c_args);
};
m_gameControlDevices.Mouse.WheelChanged += (c_sender, c_args) =>
{
if (IsHidden || !MouseInputEnabled)
{
return;
}
HoveredControl.OnMouseWheel(c_args);
};
}
private void FindKeyboardFocusedControl(GameControl c_hoveredControl)
{
while (true)
{
if (c_hoveredControl == null)
{
return;
}
if (c_hoveredControl.KeyboardInputEnabled)
{
if (c_hoveredControl.Children.Any(c_childControl => c_childControl == KeyboardFocus))
{
return;
}
c_hoveredControl.OnFocus();
return;
}
c_hoveredControl = c_hoveredControl.Parent;
}
}
public override void Dispose()
{
ProcessDelayedDeletes();
base.Dispose();
}
/// <summary>Re-renders the control, invalidates cached texture</summary>
public override void Redraw()
{
NeedsRedraw = true;
base.Redraw();
}
/// <summary>Final stop for children requesting their canvas</summary>
/// <returns>The canvas the child is from</returns>
internal override Canvas GetCanvas()
{
return this;
}
/// <summary>Updates the canvas</summary>
public void UpdateCanvas()
{
DoUpdate();
}
/// <summary>Renders the canvas</summary>
public void RenderCanvas()
{
DoThink();
var a_render = Skin.Renderer;
a_render.Begin();
RecurseLayout(Skin);
a_render.ClipRegion = Bounds;
a_render.RenderOffset = Point.Empty;
a_render.Scale = Scale;
if (ShouldDrawBackground)
{
a_render.DrawColor = BackgroundColor;
a_render.DrawFilledRect(RenderBounds);
}
if (ShiftKeyToggled)
{
a_render.DrawColor = Color.Blue;
a_render.DrawFilledRect(new Rectangle(0, 0, 100, 100));
}
DoRender(Skin);
DragAndDrop.RenderOverlay(this, Skin);
UI.ToolTip.RenderToolTip(Skin);
a_render.EndClip();
a_render.End();
}
/// <summary>Renders the control using specified skin</summary>
/// <param name="c_skin">Skin to use</param>
protected override void Render(Skin c_skin)
{
base.Render(c_skin);
NeedsRedraw = false;
}
/// <summary>Handler invoked when control's bounds change</summary>
/// <param name="c_oldBounds">Old bounds</param>
protected override void OnBoundsChanged(Rectangle c_oldBounds)
{
base.OnBoundsChanged(c_oldBounds);
InvalidateChildren(true);
}
/// <summary>Processes input and layout. Also purges delayed delete queue</summary>
private void DoThink()
{
if (IsHidden)
{
return;
}
Animation.GlobalThink();
// Reset tabbing
m_nextTab = null;
m_firstTab = null;
ProcessDelayedDeletes();
// Check has focus etc..
RecurseLayout(Skin);
// If we didn't have a next tab, cycle to the start.
if (m_nextTab == null)
{
m_nextTab = m_firstTab;
}
if (MouseFocus != null && !MouseFocus.IsVisible)
{
MouseFocus = null;
}
if (KeyboardFocus != null && (!KeyboardFocus.IsVisible || !KeyboardFocus.KeyboardInputEnabled))
{
KeyboardFocus = null;
}
if (KeyboardFocus == null)
{
}
var a_time = Platform.Neutral.GetTimeInSeconds();
for (var a_idx = 0; a_idx < 1024; a_idx++)
{
if (m_keyData.KeyState[a_idx])
{
if (m_keyData.Target != KeyboardFocus && m_keyData.Target != HoveredControl)
{
m_keyData.KeyState[a_idx] = false;
continue;
}
}
if (m_keyData.KeyState[a_idx] && a_time > m_keyData.NextRepeat[a_idx])
{
m_keyData.NextRepeat[a_idx] = Platform.Neutral.GetTimeInSeconds() + Constants.kKeyRepeatRate;
KeyboardFocus?.OnKeyPress(m_keyData.KeyEventArgs[a_idx]);
}
}
}
/// <summary>Adds given control to the delete queue and detaches it from canvas. Don't call from Dispose, it modifies child list</summary>
/// <param name="c_control">Control to delete</param>
public void AddDelayedDelete(GameControl c_control)
{
if (!m_disposeQueue.Contains(c_control))
{
m_disposeQueue.Add(c_control);
RemoveChild(c_control, false);
}
#if DEBUG
else
{
throw new InvalidOperationException("Control deleted twice");
}
#endif
}
private void ProcessDelayedDeletes()
{
if (m_disposeQueue.Count != 0)
{
foreach (var a_control in m_disposeQueue)
{
a_control.Dispose();
}
m_disposeQueue.Clear();
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Base class defining the formatting context and the
/// formatting context manager (stack based)
/// </summary>
internal class InnerFormatShapeCommandBase : ImplementationCommandBase
{
/// <summary>
/// constructor to set up the formatting context
/// </summary>
internal InnerFormatShapeCommandBase()
{
contextManager.Push(FormattingContextState.none);
}
/// <summary>
/// enum listing the possible states the context is in
/// </summary>
internal enum FormattingContextState { none, document, group }
/// <summary>
/// context manager: stack to keep track in which context
/// the formatter is
/// </summary>
protected Stack<FormattingContextState> contextManager = new Stack<FormattingContextState>();
}
/// <summary>
/// core inner implementation for format/xxx commands
/// </summary>
internal class InnerFormatShapeCommand : InnerFormatShapeCommandBase
{
/// <summary>
/// constructor to glue to the CRO
/// </summary>
internal InnerFormatShapeCommand(FormatShape shape)
{
_shape = shape;
}
internal static int FormatEnumerationLimit()
{
object enumLimitVal = null;
try
{
// Win8: 192504
if (LocalPipeline.GetExecutionContextFromTLS() != null)
{
enumLimitVal = LocalPipeline.GetExecutionContextFromTLS().SessionState.PSVariable.
GetValue("global:" + InitialSessionState.FormatEnumerationLimit);
}
}
// Eat the following exceptions, enumerationLimit will use the default value
catch (ProviderNotFoundException)
{
}
catch (ProviderInvocationException)
{
}
// if $global:FormatEnumerationLimit is an int, overwrite the default value
return enumLimitVal is int ? (int)enumLimitVal : InitialSessionState.DefaultFormatEnumerationLimit;
}
internal override void BeginProcessing()
{
base.BeginProcessing();
// Get the Format Enumeration Limit.
_enumerationLimit = InnerFormatShapeCommand.FormatEnumerationLimit();
_expressionFactory = new MshExpressionFactory();
_formatObjectDeserializer = new FormatObjectDeserializer(this.TerminatingErrorContext);
}
/// <summary>
/// execution entry point
/// </summary>
internal override void ProcessRecord()
{
_typeInfoDataBase = this.OuterCmdlet().Context.FormatDBManager.GetTypeInfoDataBase();
PSObject so = this.ReadObject();
if (so == null || so == AutomationNull.Value)
return;
IEnumerable e = PSObjectHelper.GetEnumerable(so);
if (e == null)
{
ProcessObject(so);
return;
}
// we have an IEnumerable, we have to decide if to expand, if at all
EnumerableExpansion expansionState = this.GetExpansionState(so);
switch (expansionState)
{
case EnumerableExpansion.EnumOnly:
{
foreach (object obj in e)
{
ProcessObject(PSObjectHelper.AsPSObject(obj));
}
}
break;
case EnumerableExpansion.Both:
{
var objs = e.Cast<object>().ToArray();
ProcessCoreOutOfBand(so, objs.Length);
foreach (object obj in objs)
{
ProcessObject(PSObjectHelper.AsPSObject(obj));
}
}
break;
default:
{
// do not eumerate at all (CoreOnly)
ProcessObject(so);
}
break;
}
}
private EnumerableExpansion GetExpansionState(PSObject so)
{
// if the command line swtich has been specified, use this as an override
if (_parameters != null && _parameters.expansion.HasValue)
{
return _parameters.expansion.Value;
}
// check if we have an expansion entry in format.mshxml
var typeNames = so.InternalTypeNames;
return DisplayDataQuery.GetEnumerableExpansionFromType(
_expressionFactory, _typeInfoDataBase, typeNames);
}
private void ProcessCoreOutOfBand(PSObject so, int count)
{
// emit some description header
SendCommentOutOfBand(FormatAndOut_format_xxx.IEnum_Header);
// emit the object as out of band
ProcessOutOfBand(so, isProcessingError: false);
string msg;
// emit a comment to signal that the next N objects are from the IEnumerable
switch (count)
{
case 0:
{
msg = FormatAndOut_format_xxx.IEnum_NoObjects;
}
break;
case 1:
{
msg = FormatAndOut_format_xxx.IEnum_OneObject;
}
break;
default:
{
msg = StringUtil.Format(FormatAndOut_format_xxx.IEnum_ManyObjects, count);
}
break;
}
SendCommentOutOfBand(msg);
}
private void SendCommentOutOfBand(string msg)
{
FormatEntryData fed = OutOfBandFormatViewManager.GenerateOutOfBandObjectAsToString(PSObjectHelper.AsPSObject(msg));
if (fed != null)
{
this.WriteObject(fed);
}
}
/// <summary>
/// execute formatting on a single object
/// </summary>
/// <param name="so">object to process</param>
private void ProcessObject(PSObject so)
{
// we do protect against reentrancy, assuming
// no fancy multiplexing
if (_formatObjectDeserializer.IsFormatInfoData(so))
{
// we are already formatted...
this.WriteObject(so);
return;
}
// if objects have to be treated as out of band, just
// bail now
// this is the case of objects coming before the
// context manager is properly set
if (ProcessOutOfBandObjectOutsideDocumentSequence(so))
{
return;
}
// if we haven't started yet, need to do so
FormattingContextState ctx = contextManager.Peek();
if (ctx == FormattingContextState.none)
{
// initialize the view manager
_viewManager.Initialize(this.TerminatingErrorContext, _expressionFactory, _typeInfoDataBase, so, _shape, _parameters);
// add the start message to output queue
WriteFormatStartData(so);
// enter the document context
contextManager.Push(FormattingContextState.document);
}
// if we are here, we are either in the document document, or in a group
// since we have a view now, we check if objects should be treated as out of band
if (ProcessOutOfBandObjectInsideDocumentSequence(so))
{
return;
}
// check if we have to enter or exit a group
GroupTransition transition = ComputeGroupTransition(so);
if (transition == GroupTransition.enter)
{
// insert the group start marker
PushGroup(so);
this.WritePayloadObject(so);
}
else if (transition == GroupTransition.exit)
{
this.WritePayloadObject(so);
// insert the group end marker
PopGroup();
}
else if (transition == GroupTransition.startNew)
{
// double transition
PopGroup(); // exit the current one
PushGroup(so); // start a sibling group
this.WritePayloadObject(so);
}
else // none, we did not have any transitions, just push out the data
{
this.WritePayloadObject(so);
}
}
private bool ShouldProcessOutOfBand
{
get
{
if (_shape == FormatShape.Undefined || _parameters == null)
{
return true;
}
return !_parameters.forceFormattingAlsoOnOutOfBand;
}
}
private bool ProcessOutOfBandObjectOutsideDocumentSequence(PSObject so)
{
if (!ShouldProcessOutOfBand)
{
return false;
}
if (so.InternalTypeNames.Count == 0)
{
return false;
}
List<ErrorRecord> errors;
var fed = OutOfBandFormatViewManager.GenerateOutOfBandData(this.TerminatingErrorContext, _expressionFactory,
_typeInfoDataBase, so, _enumerationLimit, false, out errors);
WriteErrorRecords(errors);
if (fed != null)
{
this.WriteObject(fed);
return true;
}
return false;
}
private bool ProcessOutOfBandObjectInsideDocumentSequence(PSObject so)
{
if (!ShouldProcessOutOfBand)
{
return false;
}
var typeNames = so.InternalTypeNames;
if (_viewManager.ViewGenerator.IsObjectApplicable(typeNames))
{
return false;
}
return ProcessOutOfBand(so, isProcessingError: false);
}
private bool ProcessOutOfBand(PSObject so, bool isProcessingError)
{
List<ErrorRecord> errors;
FormatEntryData fed = OutOfBandFormatViewManager.GenerateOutOfBandData(this.TerminatingErrorContext, _expressionFactory,
_typeInfoDataBase, so, _enumerationLimit, true, out errors);
if (!isProcessingError)
WriteErrorRecords(errors);
if (fed != null)
{
this.WriteObject(fed);
return true;
}
return false;
}
protected void WriteInternalErrorMessage(string message)
{
FormatEntryData fed = new FormatEntryData();
fed.outOfBand = true;
ComplexViewEntry cve = new ComplexViewEntry();
FormatEntry fe = new FormatEntry();
cve.formatValueList.Add(fe);
fe.formatValueList.Add(new FormatNewLine());
// get a field for the message
FormatTextField ftf = new FormatTextField();
ftf.text = message;
fe.formatValueList.Add(ftf);
fe.formatValueList.Add(new FormatNewLine());
fed.formatEntryInfo = cve;
this.WriteObject(fed);
}
private void WriteErrorRecords(List<ErrorRecord> errorRecordList)
{
if (errorRecordList == null)
return;
// NOTE: for the time being we directly process error records.
// This is should change if we hook up error pipelines; for the
// time being, this achieves partial results.
//
// see NTRAID#Windows OS Bug-932722-2004/10/21-kevinloo ("Output: SS: Swallowing exceptions")
foreach (ErrorRecord errorRecord in errorRecordList)
{
// we are recursing on formatting errors: isProcessingError == true
ProcessOutOfBand(PSObjectHelper.AsPSObject(errorRecord), true);
}
}
internal override void EndProcessing()
{
// need to pop all the contexts, in case the transmission sequence
// was interrupted
while (true)
{
FormattingContextState ctx = contextManager.Peek();
if (ctx == FormattingContextState.none)
{
break; // we emerged and we are done
}
else if (ctx == FormattingContextState.group)
{
PopGroup();
}
else if (ctx == FormattingContextState.document)
{
// inject the end format information
FormatEndData endFormat = new FormatEndData();
this.WriteObject(endFormat);
contextManager.Pop();
}
} // while
}
internal void SetCommandLineParameters(FormattingCommandLineParameters commandLineParameters)
{
Diagnostics.Assert(commandLineParameters != null, "the caller has to pass a valid instance");
_parameters = commandLineParameters;
}
/// <summary>
/// group transitions:
/// none: stay in the same group
/// enter: start a new group
/// exit: exit from the current group
/// </summary>
private enum GroupTransition { none, enter, exit, startNew }
/// <summary>
/// compute the group transition, given an input object
/// </summary>
/// <param name="so">object receoved from the input pipeline</param>
/// <returns>GroupTransition enumeration</returns>
private GroupTransition ComputeGroupTransition(PSObject so)
{
// check if we have to start a group
FormattingContextState ctx = contextManager.Peek();
if (ctx == FormattingContextState.document)
{
// prime the grouping algorithm
_viewManager.ViewGenerator.UpdateGroupingKeyValue(so);
// need to start a group, but we are not in one
return GroupTransition.enter;
}
// check if we need to start another group and keep track
// of the current value for the grouping property
return _viewManager.ViewGenerator.UpdateGroupingKeyValue(so) ? GroupTransition.startNew : GroupTransition.none;
}
private void WriteFormatStartData(PSObject so)
{
FormatStartData startFormat = _viewManager.ViewGenerator.GenerateStartData(so);
this.WriteObject(startFormat);
}
/// <summary>
/// write a payplad object by properly wrapping it into
/// a FormatEntry object
/// </summary>
/// <param name="so">object to process</param>
private void WritePayloadObject(PSObject so)
{
Diagnostics.Assert(so != null, "object so cannot be null");
FormatEntryData fed = _viewManager.ViewGenerator.GeneratePayload(so, _enumerationLimit);
fed.SetStreamTypeFromPSObject(so);
this.WriteObject(fed);
List<ErrorRecord> errors = _viewManager.ViewGenerator.ErrorManager.DrainFailedResultList();
WriteErrorRecords(errors);
}
/// <summary>
/// inject the start group information
/// and push group context on stack
/// </summary>
/// <param name="firstObjectInGroup">current pipeline object
/// that is starting the group</param>
private void PushGroup(PSObject firstObjectInGroup)
{
GroupStartData startGroup = _viewManager.ViewGenerator.GenerateGroupStartData(firstObjectInGroup, _enumerationLimit);
this.WriteObject(startGroup);
contextManager.Push(FormattingContextState.group);
}
/// <summary>
/// inject the end group information
/// and pop group context out of stack
/// </summary>
private void PopGroup()
{
GroupEndData endGroup = _viewManager.ViewGenerator.GenerateGroupEndData();
this.WriteObject(endGroup);
contextManager.Pop();
}
/// <summary>
/// the formatting shape this formatter emits
/// </summary>
private FormatShape _shape;
#region expression factory
/// <exception cref="ParseException"></exception>
internal ScriptBlock CreateScriptBlock(string scriptText)
{
var scriptBlock = this.OuterCmdlet().InvokeCommand.NewScriptBlock(scriptText);
scriptBlock.DebuggerStepThrough = true;
return scriptBlock;
}
private MshExpressionFactory _expressionFactory;
#endregion
private FormatObjectDeserializer _formatObjectDeserializer;
private TypeInfoDataBase _typeInfoDataBase = null;
private FormattingCommandLineParameters _parameters = null;
private FormatViewManager _viewManager = new FormatViewManager();
private int _enumerationLimit = InitialSessionState.DefaultFormatEnumerationLimit;
}
/// <summary>
///
/// </summary>
public class OuterFormatShapeCommandBase : FrontEndCommandBase
{
#region Command Line Switches
/// <summary>
/// optional, non positional parameter to specify the
/// group by property
/// </summary>
[Parameter]
public object GroupBy { get; set; } = null;
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
public string View { get; set; } = null;
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter ShowError
{
get
{
if (showErrorsAsMessages.HasValue)
return showErrorsAsMessages.Value;
return false;
}
set { showErrorsAsMessages = value; }
}
internal Nullable<bool> showErrorsAsMessages = null;
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter DisplayError
{
get
{
if (showErrorsInFormattedOutput.HasValue)
return showErrorsInFormattedOutput.Value;
return false;
}
set { showErrorsInFormattedOutput = value; }
}
internal Nullable<bool> showErrorsInFormattedOutput = null;
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter Force
{
get { return _forceFormattingAlsoOnOutOfBand; }
set { _forceFormattingAlsoOnOutOfBand = value; }
}
private bool _forceFormattingAlsoOnOutOfBand;
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
[ValidateSet(EnumerableExpansionConversion.CoreOnlyString,
EnumerableExpansionConversion.EnumOnlyString,
EnumerableExpansionConversion.BothString, IgnoreCase = true)]
public string Expand { get; set; } = null;
internal Nullable<EnumerableExpansion> expansion = null;
internal Nullable<EnumerableExpansion> ProcessExpandParameter()
{
Nullable<EnumerableExpansion> retVal = null;
if (string.IsNullOrEmpty(Expand))
{
return null;
}
EnumerableExpansion temp;
bool success = EnumerableExpansionConversion.Convert(Expand, out temp);
if (!success)
{
// this should never happen, since we use the [ValidateSet] attribute
// NOTE: this is an exception that should never be triggered
throw PSTraceSource.NewArgumentException("Expand", FormatAndOut_MshParameter.IllegalEnumerableExpansionValue);
}
retVal = temp;
return retVal;
}
internal MshParameter ProcessGroupByParameter()
{
if (GroupBy != null)
{
TerminatingErrorContext invocationContext =
new TerminatingErrorContext(this);
ParameterProcessor processor = new ParameterProcessor(new FormatGroupByParameterDefinition());
List<MshParameter> groupParameterList =
processor.ProcessParameters(new object[] { GroupBy },
invocationContext);
if (groupParameterList.Count != 0)
return groupParameterList[0];
}
return null;
}
#endregion
/// <summary>
///
/// </summary>
protected override void BeginProcessing()
{
InnerFormatShapeCommand innerFormatCommand =
(InnerFormatShapeCommand)this.implementation;
// read command line switches and pass them to the inner command
FormattingCommandLineParameters parameters = GetCommandLineParameters();
innerFormatCommand.SetCommandLineParameters(parameters);
// must call base class for further processing
base.BeginProcessing();
}
/// <summary>
/// it reads the command line switches and collects them into a
/// FormattingCommandLineParameters instance, ready to pass to the
/// inner format command
/// </summary>
/// <returns>parameters collected in unified manner</returns>
internal virtual FormattingCommandLineParameters GetCommandLineParameters()
{
return null;
}
internal void ReportCannotSpecifyViewAndProperty()
{
string msg = StringUtil.Format(FormatAndOut_format_xxx.CannotSpecifyViewAndPropertyError);
ErrorRecord errorRecord = new ErrorRecord(
new InvalidDataException(),
"FormatCannotSpecifyViewAndProperty",
ErrorCategory.InvalidArgument,
null);
errorRecord.ErrorDetails = new ErrorDetails(msg);
this.ThrowTerminatingError(errorRecord);
}
}
/// <summary>
///
/// </summary>
public class OuterFormatTableAndListBase : OuterFormatShapeCommandBase
{
#region Command Line Switches
/// <summary>
/// Positional parameter for properties, property sets and table sets
/// specified on the command line.
/// The paramater is optional, since the defaults
/// will be determined using property sets, etc.
/// </summary>
[Parameter(Position = 0)]
public object[] Property { get; set; }
#endregion
internal override FormattingCommandLineParameters GetCommandLineParameters()
{
FormattingCommandLineParameters parameters = new FormattingCommandLineParameters();
GetCommandLineProperties(parameters, false);
parameters.groupByParameter = this.ProcessGroupByParameter();
parameters.forceFormattingAlsoOnOutOfBand = this.Force;
if (this.showErrorsAsMessages.HasValue)
parameters.showErrorsAsMessages = this.showErrorsAsMessages;
if (this.showErrorsInFormattedOutput.HasValue)
parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput;
parameters.expansion = ProcessExpandParameter();
return parameters;
}
internal void GetCommandLineProperties(FormattingCommandLineParameters parameters, bool isTable)
{
if (Property != null)
{
CommandParameterDefinition def;
if (isTable)
def = new FormatTableParameterDefinition();
else
def = new FormatListParameterDefinition();
ParameterProcessor processor = new ParameterProcessor(def);
TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
parameters.mshParameterList = processor.ProcessParameters(Property, invocationContext);
}
if (!string.IsNullOrEmpty(this.View))
{
// we have a view command line switch
if (parameters.mshParameterList.Count != 0)
{
ReportCannotSpecifyViewAndProperty();
}
parameters.viewName = this.View;
}
}
}
/// <summary>
///
/// </summary>
public class OuterFormatTableBase : OuterFormatTableAndListBase
{
#region Command Line Switches
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter AutoSize
{
get
{
if (_autosize.HasValue)
return _autosize.Value;
return false;
}
set { _autosize = value; }
}
private Nullable<bool> _autosize = null;
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter HideTableHeaders
{
get
{
if (_hideHeaders.HasValue)
return _hideHeaders.Value;
return false;
}
set { _hideHeaders = value; }
}
private Nullable<bool> _hideHeaders = null;
/// <summary>
/// optional, non positional parameter
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter Wrap
{
get
{
if (_multiLine.HasValue)
return _multiLine.Value;
return false;
}
set { _multiLine = value; }
}
private Nullable<bool> _multiLine = null;
#endregion
internal override FormattingCommandLineParameters GetCommandLineParameters()
{
FormattingCommandLineParameters parameters = new FormattingCommandLineParameters();
GetCommandLineProperties(parameters, true);
parameters.forceFormattingAlsoOnOutOfBand = this.Force;
if (this.showErrorsAsMessages.HasValue)
parameters.showErrorsAsMessages = this.showErrorsAsMessages;
if (this.showErrorsInFormattedOutput.HasValue)
parameters.showErrorsInFormattedOutput = this.showErrorsInFormattedOutput;
parameters.expansion = ProcessExpandParameter();
if (_autosize.HasValue)
parameters.autosize = _autosize.Value;
parameters.groupByParameter = this.ProcessGroupByParameter();
TableSpecificParameters tableParameters = new TableSpecificParameters();
parameters.shapeParameters = tableParameters;
if (_hideHeaders.HasValue)
{
tableParameters.hideHeaders = _hideHeaders.Value;
}
if (_multiLine.HasValue)
{
tableParameters.multiLine = _multiLine.Value;
}
return parameters;
}
}
}
| |
using System.Collections;
namespace Python.Test
{
/// <summary>
/// Supports units tests for indexer access.
/// </summary>
public class IndexerBase
{
protected Hashtable t;
protected IndexerBase()
{
t = new Hashtable();
}
protected string GetValue(object index)
{
if (index == null)
{
return null;
}
object value = t[index];
if (value != null)
{
return (string)value;
}
return null;
}
}
public class PublicIndexerTest : IndexerBase
{
public PublicIndexerTest() : base()
{
}
public string this[int index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class ProtectedIndexerTest : IndexerBase
{
public ProtectedIndexerTest() : base()
{
}
protected string this[int index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class InternalIndexerTest : IndexerBase
{
public InternalIndexerTest() : base()
{
}
internal string this[int index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class PrivateIndexerTest : IndexerBase
{
public PrivateIndexerTest() : base()
{
}
private string this[int index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class BooleanIndexerTest : IndexerBase
{
public BooleanIndexerTest() : base()
{
}
public string this[bool index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class ByteIndexerTest : IndexerBase
{
public ByteIndexerTest() : base()
{
}
public string this[byte index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class SByteIndexerTest : IndexerBase
{
public SByteIndexerTest() : base()
{
}
public string this[sbyte index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class CharIndexerTest : IndexerBase
{
public CharIndexerTest() : base()
{
}
public string this[char index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class Int16IndexerTest : IndexerBase
{
public Int16IndexerTest() : base()
{
}
public string this[short index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class Int32IndexerTest : IndexerBase
{
public Int32IndexerTest() : base()
{
}
public string this[int index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class Int64IndexerTest : IndexerBase
{
public Int64IndexerTest() : base()
{
}
public string this[long index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class UInt16IndexerTest : IndexerBase
{
public UInt16IndexerTest() : base()
{
}
public string this[ushort index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class UInt32IndexerTest : IndexerBase
{
public UInt32IndexerTest() : base()
{
}
public string this[uint index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class UInt64IndexerTest : IndexerBase
{
public UInt64IndexerTest() : base()
{
}
public string this[ulong index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class SingleIndexerTest : IndexerBase
{
public SingleIndexerTest() : base()
{
}
public string this[float index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class DoubleIndexerTest : IndexerBase
{
public DoubleIndexerTest() : base()
{
}
public string this[double index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class DecimalIndexerTest : IndexerBase
{
public DecimalIndexerTest() : base()
{
}
public string this[decimal index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class StringIndexerTest : IndexerBase
{
public StringIndexerTest() : base()
{
}
public string this[string index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class EnumIndexerTest : IndexerBase
{
public EnumIndexerTest() : base()
{
}
public string this[ShortEnum index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class ObjectIndexerTest : IndexerBase
{
public ObjectIndexerTest() : base()
{
}
public string this[object index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class InterfaceIndexerTest : IndexerBase
{
public InterfaceIndexerTest() : base()
{
}
public string this[ISpam index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class TypedIndexerTest : IndexerBase
{
public TypedIndexerTest() : base()
{
}
public string this[Spam index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class MultiArgIndexerTest : IndexerBase
{
public MultiArgIndexerTest() : base()
{
}
public string this[int index1, int index2]
{
get
{
string key = index1.ToString() + index2.ToString();
object value = t[key];
if (value != null)
{
return (string)value;
}
return null;
}
set
{
string key = index1.ToString() + index2.ToString();
t[key] = value;
}
}
}
public class MultiTypeIndexerTest : IndexerBase
{
public MultiTypeIndexerTest() : base()
{
}
public string this[int i1, string i2, ISpam i3]
{
get
{
string key = i1.ToString() + i2.ToString() + i3.GetHashCode().ToString();
object value = t[key];
if (value != null)
{
return (string)value;
}
return null;
}
set
{
string key = i1.ToString() + i2.ToString() + i3.GetHashCode().ToString();
t[key] = value;
}
}
}
public class MultiDefaultKeyIndexerTest : IndexerBase
{
public MultiDefaultKeyIndexerTest() : base()
{
}
public string this[int i1, int i2 = 2]
{
get
{
string key = i1.ToString() + i2.ToString();
return (string)t[key];
}
set
{
string key = i1.ToString() + i2.ToString();
t[key] = value;
}
}
}
public class PublicInheritedIndexerTest : PublicIndexerTest { }
public class ProtectedInheritedIndexerTest : ProtectedIndexerTest { }
public class PrivateInheritedIndexerTest : ProtectedIndexerTest { }
public class InternalInheritedIndexerTest : InternalIndexerTest { }
public interface IIndexer
{
string this[int index] { get; set; }
}
public interface IInheritedIndexer : IIndexer { }
public class InterfaceInheritedIndexerTest : IndexerBase, IInheritedIndexer
{
private System.Collections.Generic.IDictionary<int, string> d = new System.Collections.Generic.Dictionary<int, string>();
public string this[int index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
public class PublicInheritedOverloadedIndexer : PublicIndexerTest
{
public string this[string index]
{
get { return GetValue(index); }
set { t[index] = value; }
}
}
}
| |
/*
Copyright 2019, Augurk
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.Globalization;
using System.Threading.Tasks;
using Augurk.Api;
using Augurk.Api.Managers;
using Augurk.Entities;
using NSubstitute;
using Raven.Client;
using Raven.Client.Documents;
using Raven.TestDriver;
using Shouldly;
using Xunit;
namespace Augurk.Test.Managers
{
/// <summary>
/// Contains unit tests for the <see cref="ExpirationManager" /> class.
/// </summary>
public class ExpirationManagerTests : RavenTestBase
{
/// <summary>
/// Tests that the ExpirationManager sets the expiration properly.
/// </summary>
[Fact(Skip = "Expiration needs to return in the next preview.")]
public async Task SetExpiration()
{
// Arrange
var configuration = new Configuration()
{
ExpirationEnabled = true,
ExpirationDays = 1,
ExpirationRegex = @"\d"
};
DateTime expectedUploadDate = await PersistDocument("testdocument1", new { Version = "1.0.0" });
// Act
var sut = new ExpirationManager(DocumentStoreProvider);
await sut.ApplyExpirationPolicyAsync(configuration);
WaitForIndexing(DocumentStore);
// Assert
await AssertMetadata("testdocument1", expectedUploadDate, expectedUploadDate.AddDays(configuration.ExpirationDays));
}
/// <summary>
/// Tests that the ExpirationManager removes expiration for documents that do not match the version regex.
/// </summary>
[Fact(Skip = "Expiration needs to return in the next preview.")]
public async Task RemoveExpirationFromNonMatchingVersion()
{
// Arrange
var configuration = new Configuration()
{
ExpirationEnabled = true,
ExpirationDays = 1,
ExpirationRegex = @"Hello World"
};
var additionalMetadata = new Dictionary<string, object> { { Constants.Documents.Metadata.Expires, DateTime.UtcNow } };
var expectedUploadDate = await PersistDocument("testdocument1", new { Version = "1.0.0" }, additionalMetadata);
// Act
var sut = new ExpirationManager(DocumentStoreProvider);
await sut.ApplyExpirationPolicyAsync(configuration);
WaitForIndexing(DocumentStore);
// Assert
await AssertMetadata("testdocument1", expectedUploadDate, null);
}
[Fact(Skip = "Expiration needs to return in the next preview.")]
public async Task SetUploadDateOnNonMatchingVersion()
{
// Arrange
var configuration = new Configuration()
{
ExpirationEnabled = true,
ExpirationDays = 1,
ExpirationRegex = @"Hello World"
};
var expectedUploadDate = await PersistDocument("testdocument1", new { Version = "1.0.0" });
// Act
var sut = new ExpirationManager(DocumentStoreProvider);
await sut.ApplyExpirationPolicyAsync(configuration);
WaitForIndexing(DocumentStore);
// Assert
await AssertMetadata("testdocument1", expectedUploadDate, null);
}
[Fact(Skip = "Expiration needs to return in the next preview.")]
public async Task RemoveExpirationWhenDisabled()
{
// Arrange
var configuration = new Configuration()
{
ExpirationEnabled = false,
ExpirationDays = 1,
ExpirationRegex = @"\d"
};
var dbFeature = new DbFeature { Version = "1.0.0" };
var additionalMetadata = new Dictionary<string, object> { { Constants.Documents.Metadata.Expires, DateTime.UtcNow } };
var expectedUploadDate = await PersistDocument("testdocument1", dbFeature, additionalMetadata);
// Act
var sut = new ExpirationManager(DocumentStoreProvider);
await sut.ApplyExpirationPolicyAsync(configuration);
WaitForIndexing(DocumentStore);
// Assert
await AssertMetadata("testdocument1", expectedUploadDate, null);
}
[Fact(Skip = "Expiration needs to return in the next preview.")]
public async Task SetUploadDateOnNewDocumentsWhenDisabled()
{
// Arrange
var configuration = new Configuration()
{
ExpirationEnabled = false,
ExpirationDays = 1,
ExpirationRegex = @"\d"
};
DateTime expectedUploadDate = await PersistDocument("testdocument1", new { Version = "1.0.0" });
// Act
var sut = new ExpirationManager(DocumentStoreProvider);
await sut.ApplyExpirationPolicyAsync(configuration);
WaitForIndexing(DocumentStore);
// Assert
await AssertMetadata("testdocument1", expectedUploadDate, null);
}
[Fact(Skip = "Expiration needs to return in the next preview.")]
public async Task DoNotSetExpirationOnNonVersionedDocuments()
{
// Arrange
var configuration = new Configuration()
{
ExpirationEnabled = true,
ExpirationDays = 1,
ExpirationRegex = @"Hello World"
};
await PersistDocument("testdocument1", new { SomeProperty = "SomeValue" });
// Act
var sut = new ExpirationManager(DocumentStoreProvider);
await sut.ApplyExpirationPolicyAsync(configuration);
WaitForIndexing(DocumentStore);
// Assert
await AssertMetadata("testdocument1", null, null);
}
[Fact(Skip = "Expiration needs to return in the next preview.")]
public async Task DoNotRemoveExpirationFromNonVersionedDocuments()
{
// Arrange
var configuration = new Configuration()
{
ExpirationEnabled = false
};
var utcNow = DateTime.UtcNow;
var expires = new DateTime(utcNow.Year, utcNow.Month, utcNow.Day, utcNow.Hour, utcNow.Minute, utcNow.Second);
var additionalMetadata = new Dictionary<string, object> { { Constants.Documents.Metadata.Expires, expires } };
await PersistDocument("testdocument1", new { SomeProperty = "SomeValue" }, additionalMetadata);
// Act
var sut = new ExpirationManager(DocumentStoreProvider);
await sut.ApplyExpirationPolicyAsync(configuration);
WaitForIndexing(DocumentStore);
// Assert
await AssertMetadata("testdocument1", null, expires);
}
private DateTime ParseWithoutMilliseconds(string dateString)
{
var result = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
result = new DateTime(result.Year, result.Month, result.Day, result.Hour, result.Minute, result.Second);
return result;
}
private async Task<DateTime> PersistDocument(string documentId, object document, Dictionary<string, object> additionalMetadata = null)
{
using (var session = DocumentStore.OpenAsyncSession())
{
await session.StoreAsync(document, documentId);
if (additionalMetadata != null)
{
var documentMetadata = session.Advanced.GetMetadataFor(document);
foreach (var pair in additionalMetadata)
{
documentMetadata[pair.Key] = pair.Value;
}
}
await session.SaveChangesAsync();
WaitForIndexing(DocumentStore);
var metadata = session.Advanced.GetMetadataFor(document);
return ParseWithoutMilliseconds(metadata[Constants.Documents.Metadata.LastModified].ToString());
}
}
private async Task AssertMetadata(string documentId, DateTime? expectedUploadDate, DateTime? expectedExpireDate)
{
using (var session = DocumentStore.OpenAsyncSession())
{
var document = await session.LoadAsync<object>(documentId);
var metadata = session.Advanced.GetMetadataFor(document);
if (expectedUploadDate.HasValue)
{
metadata.ContainsKey("upload-date").ShouldBeTrue();
DateTime uploadDate = ParseWithoutMilliseconds(metadata["upload-date"].ToString());
uploadDate.ShouldBe(expectedUploadDate.Value);
}
else
{
metadata.ContainsKey("upload-date").ShouldBeFalse();
}
if (expectedExpireDate.HasValue)
{
metadata.ContainsKey(Constants.Documents.Metadata.Expires).ShouldBeTrue();
DateTime expires = ParseWithoutMilliseconds(metadata[Constants.Documents.Metadata.Expires].ToString());
expires.ShouldBe(expectedExpireDate.Value);
}
else
{
metadata.ContainsKey(Constants.Documents.Metadata.Expires).ShouldBeFalse();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using BasicWebSite.Models;
using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using Microsoft.AspNetCore.Testing;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class ContentNegotiationTest : IClassFixture<MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting>>
{
public ContentNegotiationTest(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture)
{
Client = fixture.CreateDefaultClient();
}
public HttpClient Client { get; }
[Fact]
public async Task ProducesAttribute_SingleContentType_PicksTheFirstSupportedFormatter()
{
// Arrange
// Selects custom even though it is last in the list.
var expectedContentType = MediaTypeHeaderValue.Parse("application/custom;charset=utf-8");
var expectedBody = "Written using custom format.";
// Act
var response = await Client.GetAsync("http://localhost/Normal/WriteUserUsingCustomFormat");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_MultipleContentTypes_RunsConnegToSelectFormatter()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedBody = $"{{{Environment.NewLine} \"name\": \"My name\",{Environment.NewLine}" +
$" \"address\": \"My address\"{Environment.NewLine}}}";
// Act
var response = await Client.GetAsync("http://localhost/Normal/MultipleAllowedContentTypes");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task NoProducesAttribute_ActionReturningString_RunsUsingTextFormatter()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8");
var expectedBody = "NormalController";
// Act
var response = await Client.GetAsync("http://localhost/Normal/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task NoProducesAttribute_ActionReturningAnyObject_RunsUsingDefaultFormatters()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
// Act
var response = await Client.GetAsync("http://localhost/Normal/ReturnUser");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
}
[Theory]
[InlineData("/;q=0.9")]
[InlineData("/;q=0.9, invalid;q=0.5;application/json;q=0.1")]
[InlineData("/invalid;q=0.9, application/json;q=0.1,invalid;q=0.5")]
[InlineData("text/html, application/json, image/jpeg, *; q=.2, */*; q=.2")]
public async Task ContentNegotiationWithPartiallyValidAcceptHeader_SkipsInvalidEntries(string acceptHeader)
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ContentNegotiation/UserInfo_ProducesWithTypeOnly");
request.Headers.TryAddWithoutValidation("Accept", acceptHeader);
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
}
[Fact]
public async Task ProducesAttributeWithTypeOnly_RunsRegularContentNegotiation()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedOutput = "{\"name\":\"John\",\"address\":\"One Microsoft Way\"}";
var request = new HttpRequestMessage(
HttpMethod.Get,
"http://localhost/ContentNegotiation/UserInfo_ProducesWithTypeOnly");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var actual = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedOutput, actual);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ProducesAttribute_WithTypeAndContentType_UsesContentType()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8");
var expectedOutput = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns=\"http://schemas.datacontract.org/2004/07/BasicWebSite.Models\">" +
"<Address>One Microsoft Way</Address><Name>John</Name></User>";
var request = new HttpRequestMessage(
HttpMethod.Get,
"http://localhost/ContentNegotiation/UserInfo_ProducesWithTypeAndContentType");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var actual = await response.Content.ReadAsStringAsync();
XmlAssert.Equal(expectedOutput, actual);
}
[Theory]
[InlineData("http://localhost/FallbackOnTypeBasedMatch/UseTheFallback_WithDefaultFormatters")]
[InlineData("http://localhost/FallbackOnTypeBasedMatch/OverrideTheFallback_WithDefaultFormatters")]
public async Task NoAcceptAndRequestContentTypeHeaders_UsesFirstFormatterWhichCanWriteType(string url)
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
// Act
var response = await Client.GetAsync(url + "?input=100");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var actual = await response.Content.ReadAsStringAsync();
Assert.Equal("100", actual);
}
[Fact]
public async Task NoMatchingFormatter_ForTheGivenContentType_Returns406()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/Normal/ReturnUser_NoMatchingFormatter");
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Theory]
[InlineData(
"ContactInfoUsingV3Format",
"text/vcard; version=v3.0; charset=utf-8",
@"BEGIN:VCARD
FN:John Williams
END:VCARD
")]
[InlineData(
"ContactInfoUsingV4Format",
"text/vcard; version=v4.0; charset=utf-8",
@"BEGIN:VCARD
FN:John Williams
GENDER:M
END:VCARD
")]
public async Task ProducesAttribute_WithMediaTypeHavingParameters_IsCaseInsensitiveMatch(
string action,
string expectedMediaType,
string expectedResponseBody)
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ProducesWithMediaTypeParameters/" + action);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var contentType = response.Content.Headers.ContentType;
Assert.NotNull(contentType);
Assert.Equal(expectedMediaType, contentType.ToString());
var actualResponseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedResponseBody, actualResponseBody, ignoreLineEndingDifferences: true);
}
[Fact]
public async Task ProducesAttribute_OnAction_OverridesTheValueOnClass()
{
// Arrange
// Value on the class is application/json.
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentBaseController_Action;charset=utf-8");
var expectedBody = "ProducesContentBaseController";
// Act
var response = await Client.GetAsync("http://localhost/ProducesContentBase/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedClass_OverridesTheValueOnBaseClass()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentOnClassController;charset=utf-8");
var expectedBody = "ProducesContentOnClassController";
// Act
var response = await Client.GetAsync(
"http://localhost/ProducesContentOnClass/ReturnClassNameWithNoContentTypeOnAction");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseClass()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_NoProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "NoProducesContentOnClassController";
// Act
var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseAction()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_NoProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "NoProducesContentOnClassController";
// Act
var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedClassAndAction_OverridesTheValueOnBaseClass()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "ProducesContentOnClassController";
// Act
var response = await Client.GetAsync(
"http://localhost/ProducesContentOnClass/ReturnClassNameContentTypeOnDerivedAction");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_IsNotHonored_ForJsonResult()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedBody = "{\"methodName\":\"Produces_WithNonObjectResult\"}";
// Act
var response = await Client.GetAsync("http://localhost/ProducesJson/Produces_WithNonObjectResult");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task XmlFormatter_SupportedMediaType_DoesNotChangeAcrossRequests()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8");
var expectedBody = @"<User xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" " +
@"xmlns=""http://schemas.datacontract.org/2004/07/BasicWebSite.Models""><Address>" +
@"One Microsoft Way</Address><Name>John</Name></User>";
for (int i = 0; i < 5; i++)
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ContentNegotiation/UserInfo");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8"));
// Act and Assert
var response = await Client.SendAsync(request);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
}
[Theory]
[InlineData(null)]
[InlineData("text/plain")]
[InlineData("text/plain; charset=utf-8")]
[InlineData("text/html, application/xhtml+xml, image/jxr, */*")] // typical browser accept header
public async Task ObjectResult_WithStringReturnType_DefaultToTextPlain(string acceptMediaType)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "FallbackOnTypeBasedMatch/ReturnString");
request.Headers.Accept.ParseAdd(acceptMediaType);
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain; charset=utf-8", response.Content.Headers.ContentType.ToString());
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal("Hello World!", actualBody);
}
[Fact]
public async Task ObjectResult_WithStringReturnType_AndNonTextPlainMediaType_DoesNotReturnTextPlain()
{
// Arrange
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/ReturnString";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString());
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal("\"Hello World!\"", actualBody);
}
[Fact]
public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_NoMatchFound_Returns406()
{
// Arrange
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/FallbackGivesNoMatch/?input=1234";
var content = new StringContent("1234", Encoding.UTF8, "application/custom");
var request = new HttpRequestMessage(HttpMethod.Post, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/custom1"));
request.Content = content;
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task InvalidResponseContentType_WithNotMatchingAcceptHeader_Returns406()
{
// Arrange
var targetUri = "http://localhost/InvalidContentType/SetResponseContentTypeJson";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/custom1"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task InvalidResponseContentType_WithMatchingAcceptHeader_Returns406()
{
// Arrange
var targetUri = "http://localhost/InvalidContentType/SetResponseContentTypeJson";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task InvalidResponseContentType_WithoutAcceptHeader_Returns406()
{
// Arrange
var targetUri = "http://localhost/InvalidContentType/SetResponseContentTypeJson";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task ProducesAttribute_And_FormatFilterAttribute_Conflicting()
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/FormatFilter/ProducesTakesPrecedenceOverUserSuppliedFormatMethod?format=json");
// Assert
// Explicit content type set by the developer takes precedence over the format requested by the end user
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task ProducesAttribute_And_FormatFilterAttribute_Collaborating()
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/FormatFilter/ProducesTakesPrecedenceOverUserSuppliedFormatMethod");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("MethodWithFormatFilter", body);
}
[Fact]
public async Task ProducesAttribute_CustomMediaTypeWithJsonSuffix_RunsConnegAndSelectsJsonFormatter()
{
// Arrange
var expectedMediaType = MediaTypeHeaderValue.Parse("application/vnd.example.contact+json; v=2; charset=utf-8");
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ProducesWithMediaTypeSuffixesController/ContactInfo");
request.Headers.Add("Accept", "application/vnd.example.contact+json; v=2");
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
var contact = JsonConvert.DeserializeObject<Contact>(body);
Assert.Equal("Jason Ecsemelle", contact.Name);
}
[Fact]
public async Task ProducesAttribute_CustomMediaTypeWithXmlSuffix_RunsConnegAndSelectsXmlFormatter()
{
// Arrange
var expectedMediaType = MediaTypeHeaderValue.Parse("application/vnd.example.contact+xml; v=2; charset=utf-8");
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ProducesWithMediaTypeSuffixesController/ContactInfo");
request.Headers.Add("Accept", "application/vnd.example.contact+xml; v=2");
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
var bodyStream = await response.Content.ReadAsStreamAsync();
var xmlDeserializer = new DataContractSerializer(typeof(Contact));
var contact = xmlDeserializer.ReadObject(bodyStream) as Contact;
Assert.Equal("Jason Ecsemelle", contact.Name);
}
[Fact]
public async Task FormatFilter_XmlAsFormat_ReturnsXml()
{
// Arrange
var expectedBody = "<FormatFilterController.Customer xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns=\"http://schemas.datacontract.org/2004/07/BasicWebSite.Controllers.ContentNegotiation\">"
+ "<Name>John</Name></FormatFilterController.Customer>";
// Act
var response = await Client.GetAsync(
"http://localhost/FormatFilter/CustomerInfo?format=xml");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/xml; charset=utf-8", response.Content.Headers.ContentType.ToString());
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
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.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SpatialAnalysis.Data.Statistics
{
/// <summary>
/// Interaction logic for BoxPlot.xaml
/// </summary>
public partial class BoxPlot : UserControl
{
/// <summary>
/// Gets or sets the quartiles.
/// </summary>
/// <value>The quartiles.</value>
public double[] Quartiles { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="BoxPlot"/> class.
/// </summary>
public BoxPlot()
{
InitializeComponent();
}
double getMedian(List<double> values)
{
int size = values.Count;
int index = (int)((double)size / 2);
if (size % 2 == 1)
{
return values[index];
}
else
{
return (values[index - 1] + values[index]) / 2;
}
}
/// <summary>
/// Draws the a horizontal box plot
/// </summary>
/// <param name="data">The data.</param>
/// <param name="thickness">The thickness.</param>
public void DrawHorizontally(ISpatialData data, double thickness)
{
this._canvas.Children.Clear();
List<double> values = data.Data.Values.ToList();
values.Sort();
this.Quartiles = new double[5];
this.Quartiles[0] = data.Min;
this.Quartiles[4] = data.Max;
int size = values.Count;
List<double> first = new List<double>();
List<double> second = new List<double>();
int index50 = (int)((double)size / 2);
if (size % 2 == 1)
{
this.Quartiles[2] = values[index50];
first.AddRange(values.GetRange(0, index50));
second.AddRange(values.GetRange(index50 + 1, index50));
}
else
{
this.Quartiles[2] = (values[index50 - 1] + values[index50]) / 2;
first.AddRange(values.GetRange(0, index50 - 1));
second.AddRange(values.GetRange(index50, index50 - 1));
}
this.Quartiles[1] = this.getMedian(first);
this.Quartiles[3] = this.getMedian(second);
double widthRatio = this._canvas.RenderSize.Width/(data.Max - data.Min);
double w = this._canvas.RenderSize.Width;
double h = this._canvas.RenderSize.Height;
Line l0 = new Line
{
X1 = 0,
X2 = 0,
Y1 = 0,
Y2 = h,
StrokeThickness=thickness,
Stroke= Brushes.Black,
};
var fill = Brushes.Gray.CloneCurrentValue();
fill.Opacity=0.7d;
Rectangle rect = new Rectangle
{
Width = (this.Quartiles[3] - this.Quartiles[1]) * widthRatio,
Height = h,
StrokeThickness = thickness / 3,
Stroke = Brushes.Black,
Fill = fill,
};
Canvas.SetLeft(rect, (this.Quartiles[1] - this.Quartiles[0]) * widthRatio);
Line l4 = new Line
{
X1 = (this.Quartiles[4] - this.Quartiles[0]) * widthRatio,
X2 = (this.Quartiles[4] - this.Quartiles[0]) * widthRatio,
Y1 = 0,
Y2 = h,
StrokeThickness = thickness,
Stroke = Brushes.Black,
};
Line l2 = new Line
{
X1 = (this.Quartiles[2] - this.Quartiles[0]) * widthRatio,
X2 = (this.Quartiles[2] - this.Quartiles[0]) * widthRatio,
Y1 = 0,
Y2 = h,
StrokeThickness = thickness,
Stroke = Brushes.Black,
};
Line l01 = new Line
{
X1 = 0,
X2 = (this.Quartiles[1] - this.Quartiles[0]) * widthRatio,
Y1 = h/2,
Y2 = h/2,
StrokeThickness = thickness/3,
StrokeDashArray = new DoubleCollection() { 2 * thickness, thickness },
Stroke = Brushes.Black,
};
Line l34 = new Line
{
X1 = (this.Quartiles[3] - this.Quartiles[0]) * widthRatio,
X2 = w,
Y1 = h / 2,
Y2 = h / 2,
StrokeThickness = thickness / 3,
StrokeDashArray = new DoubleCollection(){2 * thickness, thickness},
Stroke = Brushes.Black,
};
this._canvas.Children.Add(l0);
this._canvas.Children.Add(l4);
this._canvas.Children.Add(l2);
this._canvas.Children.Add(l01);
this._canvas.Children.Add(l34);
this._canvas.Children.Add(rect);
Canvas.SetZIndex(l0, 1);
Canvas.SetZIndex(l4, 1);
Canvas.SetZIndex(l2, 1);
Canvas.SetZIndex(l01, 1);
Canvas.SetZIndex(l34, 1);
Canvas.SetZIndex(rect, 0);
}
/// <summary>
/// Draws the a vertical box plot
/// </summary>
/// <param name="data">The data.</param>
/// <param name="thickness">The thickness.</param>
public void DrawVertically(ISpatialData data, double thickness)
{
this._canvas.Children.Clear();
List<double> values = data.Data.Values.ToList();
values.Sort();
this.Quartiles = new double[5];
this.Quartiles[0] = data.Min;
this.Quartiles[4] = data.Max;
int size = values.Count;
List<double> first = new List<double>();
List<double> second = new List<double>();
int index50 = (int)((double)size / 2);
if (size % 2 == 1)
{
this.Quartiles[2] = values[index50];
first.AddRange(values.GetRange(0, index50));
second.AddRange(values.GetRange(index50 + 1, index50));
}
else
{
this.Quartiles[2] = (values[index50 - 1] + values[index50]) / 2;
first.AddRange(values.GetRange(0, index50 - 1));
second.AddRange(values.GetRange(index50, index50 - 1));
}
this.Quartiles[1] = this.getMedian(first);
this.Quartiles[3] = this.getMedian(second);
double heightRatio = this._canvas.RenderSize.Height / (data.Max - data.Min);
double w = this._canvas.RenderSize.Width;
double h = this._canvas.RenderSize.Height;
Line l0 = new Line
{
X1 = 0,
X2 = w,
Y1 = h,
Y2 = h,
StrokeThickness = thickness,
Stroke = Brushes.Black,
};
var fill = Brushes.Gray.CloneCurrentValue();
fill.Opacity = 0.7d;
Rectangle rect = new Rectangle
{
Height= (this.Quartiles[3] - this.Quartiles[1]) * heightRatio,
Width = w,
StrokeThickness = thickness / 3,
Stroke = Brushes.Black,
Fill = fill,
};
Canvas.SetBottom(rect, (this.Quartiles[1] - this.Quartiles[0]) * heightRatio);
Line l4 = new Line
{
Y1 = h - (this.Quartiles[4] - this.Quartiles[0]) * heightRatio,
Y2 = h - (this.Quartiles[4] - this.Quartiles[0]) * heightRatio,
X1 = 0,
X2 = w,
StrokeThickness = thickness,
Stroke = Brushes.Black,
};
Line l2 = new Line
{
Y1 = h - (this.Quartiles[2] - this.Quartiles[0]) * heightRatio,
Y2 = h - (this.Quartiles[2] - this.Quartiles[0]) * heightRatio,
X1 = 0,
X2 = w,
StrokeThickness = thickness,
Stroke = Brushes.Black,
};
Line l01 = new Line
{
Y1 = h,
Y2 = h - (this.Quartiles[1] - this.Quartiles[0]) * heightRatio,
X1 = w / 2,
X2 = w / 2,
StrokeThickness = thickness / 3,
StrokeDashArray = new DoubleCollection() { 2 * thickness, thickness },
Stroke = Brushes.Black,
};
Line l34 = new Line
{
Y1 = h - (this.Quartiles[3] - this.Quartiles[0]) * heightRatio,
Y2 = 0,
X1 = w / 2,
X2 = w / 2,
StrokeThickness = thickness / 3,
StrokeDashArray = new DoubleCollection() { 2 * thickness, thickness },
Stroke = Brushes.Black,
};
this._canvas.Children.Add(l0);
this._canvas.Children.Add(l4);
this._canvas.Children.Add(l2);
this._canvas.Children.Add(l01);
this._canvas.Children.Add(l34);
this._canvas.Children.Add(rect);
Canvas.SetZIndex(l0, 1);
Canvas.SetZIndex(l4, 1);
Canvas.SetZIndex(l2, 1);
Canvas.SetZIndex(l01, 1);
Canvas.SetZIndex(l34, 1);
Canvas.SetZIndex(rect, 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using Spring.Collections;
using Spring.Collections.Generic;
namespace Spring.Threading.Collections.Generic {
/// <summary>
/// An optionally-bounded <see cref="IBlockingQueue{T}"/> based on
/// linked nodes.
/// </summary>
/// <remarks>
/// This queue orders elements FIFO (first-in-first-out).
/// The <b>head</b> of the queue is that element that has been on the
/// queue the longest time.
/// The <b>tail</b> of the queue is that element that has been on the
/// queue the shortest time. New elements
/// are inserted at the tail of the queue, and the queue retrieval
/// operations obtain elements at the head of the queue.
/// Linked queues typically have higher throughput than array-based queues but
/// less predictable performance in most concurrent applications.
///
/// <p/>
/// The optional capacity bound constructor argument serves as a
/// way to prevent excessive queue expansion. The capacity, if unspecified,
/// is equal to <see cref="System.Int32.MaxValue"/>. Linked nodes are
/// dynamically created upon each insertion unless this would bring the
/// queue above capacity.
/// </remarks>
/// <author>Doug Lea</author>
/// <author>Griffin Caprio (.NET)</author>
[Serializable]
public class LinkedBlockingQueue<T> : AbstractBlockingQueue<T>, ISerializable {
#region inner classes
[Serializable]
private class SerializableLock {
}
[Serializable]
internal class Node {
internal T item;
internal Node next;
internal Node(T x) {
item = x;
}
}
#endregion
#region private fields
/// <summary>The capacity bound, or Integer.MAX_VALUE if none </summary>
private readonly int _capacity;
/// <summary>Current number of elements </summary>
private volatile int _activeCount;
/// <summary>Head of linked list </summary>
[NonSerialized]
private Node head;
/// <summary>Tail of linked list </summary>
[NonSerialized]
private Node last;
/// <summary>Lock held by take, poll, etc </summary>
private readonly object takeLock;
/// <summary>Lock held by put, offer, etc </summary>
private readonly object putLock;
/// <summary>
/// Signals a waiting take. Called only from put/offer (which do not
/// otherwise ordinarily lock takeLock.)
/// </summary>
private void signalNotEmpty() {
lock(takeLock) {
Monitor.Pulse(takeLock);
}
}
/// <summary> Signals a waiting put. Called only from take/poll.</summary>
private void signalNotFull() {
lock(putLock) {
Monitor.Pulse(putLock);
}
}
/// <summary>
/// Creates a node and links it at end of queue.</summary>
/// <param name="x">the item to insert</param>
private void insert(T x) {
last = last.next = new Node(x);
}
/// <summary>Removes a node from head of queue,</summary>
/// <returns>the node</returns>
private T extract() {
Node first = head.next;
head = first;
T x = first.item;
first.item = default(T);
return x;
}
#endregion
#region ctors
/// <summary> Creates a <see cref="LinkedBlockingQueue{T}"/> with a capacity of
/// <see cref="System.Int32.MaxValue"/>.
/// </summary>
public LinkedBlockingQueue()
: this(Int32.MaxValue) {
}
/// <summary> Creates a <see cref="LinkedBlockingQueue{T}"/> with the given (fixed) capacity.</summary>
/// <param name="capacity">the capacity of this queue</param>
/// <exception cref="System.ArgumentException">if the <paramref name="capacity"/> is not greater than zero.</exception>
public LinkedBlockingQueue(int capacity) {
if(capacity <= 0)
throw new ArgumentException();
takeLock = new SerializableLock();
putLock = new SerializableLock();
_capacity = capacity;
last = head = new Node(default(T));
}
/// <summary> Creates a <see cref="LinkedBlockingQueue{T}"/> with a capacity of
/// <see cref="System.Int32.MaxValue"/>, initially containing the elements o)f the
/// given collection, added in traversal order of the collection's iterator.
/// </summary>
/// <param name="collection">the collection of elements to initially contain</param>
/// <exception cref="System.ArgumentNullException">if the collection or any of its elements are null.</exception>
/// <exception cref="System.ArgumentException">if the collection size exceeds the capacity of this queue.</exception>
public LinkedBlockingQueue(ICollection<T> collection)
: this(Int32.MaxValue) {
if(collection == null) {
throw new ArgumentNullException("collection", "must not be null.");
}
if(collection.Count > _capacity) {
throw new ArgumentException("Collection size exceeds the capacity of this queue.");
}
foreach(T currentobject in collection) {
Add(currentobject);
}
}
/// <summary> Reconstitute this queue instance from a stream (that is,
/// deserialize it).
/// </summary>
/// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param>
/// <param name="context">The destination (see <see cref="System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param>
protected LinkedBlockingQueue(SerializationInfo info, StreamingContext context) {
MemberInfo[] mi = FormatterServices.GetSerializableMembers(GetType(), context);
for(int i = 0; i < mi.Length; i++) {
FieldInfo fi = (FieldInfo)mi[i];
fi.SetValue(this, info.GetValue(fi.Name, fi.FieldType));
}
lock(this) {
_activeCount = 0;
}
last = head = new Node(default(T));
for(; ; ) {
T item = (T)info.GetValue("Spring.Threading.Collections.LinkedBlockingQueuedata1", typeof(T));
Add(item);
}
}
#endregion
#region ISerializable Members
/// <summary>
///Populates a <see cref="System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param>
/// <param name="context">The destination (see <see cref="System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
lock(putLock) {
lock(takeLock) {
MemberInfo[] mi = FormatterServices.GetSerializableMembers(GetType(), context);
for(int i = 0; i < mi.Length; i++) {
info.AddValue(mi[i].Name, ((FieldInfo)mi[i]).GetValue(this));
}
for(Node p = head.next; p != null; p = p.next) {
info.AddValue("Spring.Threading.Collections.LinkedBlockingQueuedata1", p.item);
}
info.AddValue("Spring.Threading.Collections.LinkedBlockingQueuedata2", null);
}
}
}
#endregion
#region IBlockingQueue<T> Members
/// <summary>
/// Inserts the specified element into this queue, waiting if necessary
/// for space to become available.
/// </summary>
/// <param name="element">the element to add</param>
/// <exception cref="System.InvalidOperationException">
/// If the element cannot be added at this time due to capacity restrictions.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the element type of the queue is a reference type and the specified element
/// is <see lang="null"/> and this queue does not permit <see lang="null"/> elements.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If some property of the supplied <paramref name="element"/> prevents
/// it from being added to this queue.
/// </exception>
public override void Put(T element) {
int tempCount;
lock(putLock) {
try {
while(_activeCount == _capacity)
Monitor.Wait(putLock);
}
catch(ThreadInterruptedException) {
Monitor.Pulse(putLock);
throw;
}
insert(element);
lock(this) {
tempCount = _activeCount++;
}
if(tempCount + 1 < _capacity)
Monitor.Pulse(putLock);
}
if(tempCount == 0)
signalNotEmpty();
}
/// <summary>
/// Inserts the specified element into this queue, waiting up to the
/// specified wait time if necessary for space to become available.
/// </summary>
/// <param name="element">the element to add</param>
/// <param name="duration">how long to wait before giving up</param>
/// <returns> <see lang="true"/> if successful, or <see lang="false"/> if
/// the specified waiting time elapses before space is available
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// If the element cannot be added at this time due to capacity restrictions.
/// </exception>
/// <exception cref="System.InvalidCastException">
/// If the class of the supplied <paramref name="element"/> prevents it
/// from being added to this queue.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the element type of the queue is a reference type and the specified element
/// is <see lang="null"/> and this queue does not permit <see lang="null"/> elements.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If some property of the supplied <paramref name="element"/> prevents
/// it from being added to this queue.
/// </exception>
public override bool Offer(T element, TimeSpan duration) {
TimeSpan durationToWait = duration;
int tempCount;
lock(putLock) {
DateTime deadline = DateTime.Now.Add(durationToWait);
for(; ; ) {
if(_activeCount < _capacity) {
insert(element);
lock(this) {
tempCount = _activeCount++;
}
if(tempCount + 1 < _capacity)
Monitor.Pulse(putLock);
break;
}
if(durationToWait.TotalMilliseconds <= 0)
return false;
try {
lock(this) {
Monitor.Wait(this, duration);
}
durationToWait = deadline.Subtract(DateTime.Now);
}
catch(ThreadInterruptedException) {
Monitor.Pulse(putLock);
throw;
}
}
}
if(tempCount == 0)
signalNotEmpty();
return true;
}
/// <summary>
/// Retrieves and removes the head of this queue, waiting if necessary
/// until an element becomes available.
/// </summary>
/// <returns> the head of this queue</returns>
public override T Take() {
T x;
int tempCount;
lock(takeLock) {
try {
while(_activeCount == 0)
Monitor.Wait(takeLock);
}
catch(ThreadInterruptedException) {
Monitor.Pulse(takeLock);
throw;
}
x = extract();
lock(this) {
tempCount = _activeCount--;
}
if(tempCount > 1)
Monitor.Pulse(takeLock);
}
if(tempCount == _capacity)
signalNotFull();
return x;
}
/// <summary>
/// Retrieves and removes the head of this queue, waiting up to the
/// specified wait time if necessary for an element to become available.
/// </summary>
/// <param name="duration">how long to wait before giving up</param>
/// <param name="element"></param>
/// <returns>
/// the head of this queue, or <see lang="default(T)"/> if the
/// specified waiting time elapses before an element is available.
/// </returns>
public override bool Poll(TimeSpan duration, out T element) {
T x;
int c;
TimeSpan durationToWait = duration;
lock(takeLock) {
DateTime deadline = DateTime.Now.Add(duration);
for(; ; ) {
if(_activeCount > 0) {
x = extract();
lock(this) {
c = _activeCount--;
}
if(c > 1)
Monitor.Pulse(takeLock);
break;
}
if(durationToWait.TotalMilliseconds <= 0) {
element = default(T);
return false;
}
try {
lock(this) {
Monitor.Wait(this, duration);
}
durationToWait = deadline.Subtract(DateTime.Now);
}
catch(ThreadInterruptedException) {
Monitor.Pulse(takeLock);
throw;
}
}
}
if(c == _capacity)
signalNotFull();
element = x;
return true;
}
/// <summary>
/// Returns the number of additional elements that this queue can ideally
/// (in the absence of memory or resource constraints) accept without
/// blocking. This is always equal to the initial capacity of this queue
/// minus the current <see cref="LinkedBlockingQueue{T}.Count"/> of this queue.
/// </summary>
/// <remarks>
/// Note that you <b>cannot</b> always tell if an attempt to insert
/// an element will succeed by inspecting <see cref="LinkedBlockingQueue{T}.RemainingCapacity"/>
/// because it may be the case that another thread is about to
/// insert or remove an element.
/// </remarks>
public override int RemainingCapacity {
get {
return _capacity - _activeCount;
}
}
/// <summary>
/// Removes all available elements from this queue and adds them
/// to the given collection.
/// </summary>
/// <remarks>
/// This operation may be more
/// efficient than repeatedly polling this queue. A failure
/// encountered while attempting to add elements to
/// collection <paramref name="collection"/> may result in elements being in neither,
/// either or both collections when the associated exception is
/// thrown. Attempts to drain a queue to itself result in
/// <see cref="System.ArgumentException"/>. Further, the behavior of
/// this operation is undefined if the specified collection is
/// modified while the operation is in progress.
/// </remarks>
/// <param name="collection">the collection to transfer elements into</param>
/// <returns> the number of elements transferred</returns>
/// <exception cref="System.InvalidOperationException">
/// If the queue cannot be drained at this time.
/// </exception>
/// <exception cref="System.InvalidCastException">
/// If the class of the supplied <paramref name="collection"/> prevents it
/// from being used for the elemetns from the queue.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the specified collection is <see lang="null"/>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If <paramref name="collection"/> represents the queue itself.
/// </exception>
//TODO: do we really need this? can we leave it to the base class?
public override int DrainTo(ICollection<T> collection) {
if(collection == null)
throw new ArgumentNullException("collection", "Collection cannot be null.");
if(collection == this)
throw new ArgumentException("Cannot drain current collection to itself.");
Node first;
lock(putLock) {
lock(takeLock) {
first = head.next;
head.next = null;
last = head;
int cold;
lock(this) {
cold = _activeCount;
_activeCount = 0;
}
if(cold == _capacity)
Monitor.PulseAll(putLock);
}
}
int n = 0;
for(Node p = first; p != null; p = p.next) {
collection.Add(p.item);
p.item = default(T);
++n;
}
return n;
}
/// <summary>
/// Does the real work for all <c>Drain</c> methods. Caller must
/// guarantee the <paramref name="action"/> is not <c>null</c> and
/// <paramref name="maxElements"/> is greater then zero (0).
/// </summary>
/// <seealso cref="IBlockingQueue{T}.DrainTo(ICollection{T})"/>
/// <seealso cref="IBlockingQueue{T}.DrainTo(ICollection{T}, int)"/>
/// <seealso cref="IBlockingQueue{T}.Drain(System.Action{T})"/>
/// <seealso cref="IBlockingQueue{T}.DrainTo(ICollection{T},int)"/>
protected override int DoDrainTo(Action<T> action, int maxElements)
{
lock(putLock) {
lock(takeLock) {
int n = 0;
Node p = head.next;
while(p != null && n < maxElements) {
action(p.item);
p.item = default(T);
p = p.next;
++n;
}
if(n != 0) {
head.next = p;
if(p == null)
last = head;
int cold;
lock(this) {
cold = _activeCount;
_activeCount -= n;
}
if(cold == _capacity)
Monitor.PulseAll(putLock);
}
return n;
}
}
}
#endregion
#region base class overrides
/// <summary>
/// Removes a single instance of the specified element from this queue,
/// if it is present.
/// </summary>
/// <remarks>
/// If this queue contains one or more such elements.
/// Returns <see lang="true"/> if this queue contained the specified element
/// (or equivalently, if this queue changed as a result of the call).
/// </remarks>
/// <param name="objectToRemove">element to be removed from this queue, if present</param>
/// <returns><see lang="true"/> if this queue changed as a result of the call</returns>
public override bool Remove(T objectToRemove) {
bool removed = false;
lock(putLock) {
lock(takeLock) {
Node trail = head;
Node p = head.next;
while(p != null) {
if(objectToRemove.Equals(p.item)) {
removed = true;
break;
}
trail = p;
p = p.next;
}
if(removed) {
p.item = default(T);
trail.next = p.next;
if(last == p)
last = trail;
lock(this) {
if(_activeCount-- == _capacity)
Monitor.PulseAll(putLock);
}
}
}
}
return removed;
}
/// <summary>
/// Inserts the specified element into this queue if it is possible to do
/// so immediately without violating capacity restrictions.
/// </summary>
/// <remarks>
/// <p>
/// When using a capacity-restricted queue, this method is generally
/// preferable to <see cref="Spring.Collections.IQueue.Add(object)"/>,
/// which can fail to insert an element only by throwing an exception.
/// </p>
/// </remarks>
/// <param name="element">
/// The element to add.
/// </param>
/// <returns>
/// <see lang="true"/> if the element was added to this queue.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// If the element cannot be added at this time due to capacity restrictions.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// If the element type of the queue is a reference type and the specified element
/// is <see lang="null"/> and this queue does not permit <see lang="null"/> elements.
/// </exception>
/// <exception cref="System.ArgumentException">
/// If some property of the supplied <paramref name="element"/> prevents
/// it from being added to this queue.
/// </exception>
public override bool Offer(T element) {
if(_activeCount == _capacity)
return false;
int tempCount = -1;
lock(putLock) {
if(_activeCount < _capacity) {
insert(element);
lock(this) {
tempCount = _activeCount++;
}
if(tempCount + 1 < _capacity)
Monitor.Pulse(putLock);
}
}
if(tempCount == 0)
signalNotEmpty();
return tempCount >= 0;
}
/// <summary>
/// Retrieves, but does not remove, the head of this queue into out
/// parameter <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// The head of this queue. <c>default(T)</c> if queue is empty.
/// </param>
/// <returns>
/// <c>false</c> is the queue is empty. Otherwise <c>true</c>.
/// </returns>
public override bool Peek(out T element) {
if(_activeCount == 0) {
element = default(T);
return false;
}
lock(takeLock) {
Node first = head.next;
element = first.item;
return true;
}
}
/// <summary>
/// Retrieves and removes the head of this queue into out parameter
/// <paramref name="element"/>.
/// </summary>
/// <param name="element">
/// Set to the head of this queue. <c>default(T)</c> if queue is empty.
/// </param>
/// <returns>
/// <c>false</c> if the queue is empty. Otherwise <c>true</c>.
/// </returns>
public override bool Poll(out T element) {
if(_activeCount == 0) {
element = default(T);
return false;
}
T x = default(T);
int c = -1;
lock(takeLock) {
if(_activeCount > 0) {
x = extract();
lock(this) {
c = _activeCount--;
}
if(c > 1)
Monitor.Pulse(takeLock);
}
}
if(c == _capacity) {
signalNotFull();
}
element = x;
return true;
}
/// <summary>
/// Returns <see lang="true"/> if there are no elements in the <see cref="IQueue{T}"/>, <see lang="false"/> otherwise.
/// </summary>
public override bool IsEmpty {
get { return _activeCount == 0; }
}
/// <summary>
/// Gets the capacity of this queue.
/// </summary>
public override int Capacity {
get { return _capacity; }
}
/// <summary>
/// When implemented by a class, copies the elements of the ICollection to an Array, starting at a particular Array index.
/// </summary>
/// <param name="targetArray">The one-dimensional Array that is the destination of the elements copied from ICollection. The Array must have zero-based indexing.</param>
/// <param name="index">The zero-based index in array at which copying begins. </param>
public override void CopyTo(T[] targetArray, Int32 index) {
lock(putLock) {
lock(takeLock) {
int size = _activeCount;
if(targetArray.Length < size)
targetArray = new T[size];
int k = 0;
for(Node p = head.next; p != null; p = p.next)
targetArray.SetValue(p.item, k++);
}
}
}
/// <summary>
/// Gets the count of the queue.
/// </summary>
public override int Count {
get { return _activeCount; }
}
/// <summary>
///When implemented by a class, gets an object that can be used to synchronize access to the ICollection. For this implementation,
///always return null, indicating the array is already synchronized.
/// </summary>
protected override object SyncRoot {
get { return null; }
}
/// <summary>
/// When implemented by a class, gets a value indicating whether access to the ICollection is synchronized (thread-safe).
/// </summary>
protected override bool IsSynchronized {
get { return true; }
}
/// <summary>
/// test whether the queue contains <paramref name="item"/>
/// </summary>
/// <param name="item">the item whose containement should be checked</param>
/// <returns><c>true</c> if item is in the queue, <c>false</c> otherwise</returns>
public override bool Contains(T item) {
throw new NotImplementedException();
}
#endregion
/// <summary>
/// Returns an array containing all of the elements in this queue, in
/// proper sequence.
/// </summary>
/// <remarks>
/// The returned array will be "safe" in that no references to it are
/// maintained by this queue. (In other words, this method must allocate
/// a new array). The caller is thus free to modify the returned array.
///
/// <p/>
/// This method acts as bridge between array-based and collection-based
/// APIs.
/// </remarks>
/// <returns> an array containing all of the elements in this queue</returns>
public virtual T[] ToArray() {
lock(putLock) {
lock(takeLock) {
int size = _activeCount;
T[] a = new T[size];
int k = 0;
for(Node p = head.next; p != null; p = p.next)
a[k++] = p.item;
return a;
}
}
}
/// <summary>
/// Returns an array containing all of the elements in this queue, in
/// proper sequence; the runtime type of the returned array is that of
/// the specified array. If the queue fits in the specified array, it
/// is returned therein. Otherwise, a new array is allocated with the
/// runtime type of the specified array and the size of this queue.
/// </summary>
/// <remarks>
/// If this queue fits in the specified array with room to spare
/// (i.e., the array has more elements than this queue), the element in
/// the array immediately following the end of the queue is set to
/// <see lang="null"/>.
/// <p/>
/// Like the <see cref="LinkedBlockingQueue{T}.ToArray()"/> method, this method acts as bridge between
/// array-based and collection-based APIs. Further, this method allows
/// precise control over the runtime type of the output array, and may,
/// under certain circumstances, be used to save allocation costs.
/// <p/>
/// Suppose <i>x</i> is a queue known to contain only strings.
/// The following code can be used to dump the queue into a newly
/// allocated array of <see lang="string"/>s:
///
/// <code>
/// string[] y = x.ToArray(new string[0]);
/// </code>
/// <p/>
/// Note that <i>toArray(new object[0])</i> is identical in function to
/// <see cref="LinkedBlockingQueue{T}.ToArray()"/>.
///
/// </remarks>
/// <param name="targetArray">
/// the array into which the elements of the queue are to
/// be stored, if it is big enough; otherwise, a new array of the
/// same runtime type is allocated for this purpose
/// </param>
/// <returns> an array containing all of the elements in this queue</returns>
/// <exception cref="System.ArgumentNullException">
/// If the supplied <paramref name="targetArray"/> is
/// <see lang="null"/> and this queue does not permit <see lang="null"/>
/// elements.
/// </exception>
public virtual T[] ToArray(T[] targetArray) {
lock(putLock) {
lock(takeLock) {
int size = _activeCount;
if(targetArray.Length < size)
targetArray = new T[size];
int k = 0;
for(Node p = head.next; p != null; p = p.next)
targetArray[k++] = p.item;
return targetArray;
}
}
}
/// <summary>
/// Returns a string representation of this colleciton.
/// </summary>
/// <returns>String representation of the elements of this collection.</returns>
public override string ToString() {
lock(putLock) {
lock(takeLock) {
// TODO: ask Mark whether this method should take IEnumarable
//return StringUtils.CollectionToCommaDelimitedString(this);
return null;
}
}
}
/// <summary>
/// Removes all of the elements from this queue.
/// </summary>
/// <remarks>
/// <p>
/// The queue will be empty after this call returns.
/// </p>
/// <p>
/// This implementation repeatedly invokes
/// <see cref="Spring.Collections.AbstractQueue.Poll()"/> until it
/// returns <see lang="null"/>.
/// </p>
/// </remarks>
public override void Clear() {
lock(putLock) {
lock(takeLock) {
head.next = null;
last = head;
int c;
lock(this) {
c = _activeCount;
_activeCount = 0;
}
if(c == _capacity)
Monitor.PulseAll(putLock);
}
}
}
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that can iterate through a collection.
/// </summary>
/// <returns>An IEnumerator that can be used to iterate through the collection.</returns>
public override IEnumerator<T> GetEnumerator() {
return new LinkedBlockingQueueEnumerator(this);
}
/// <summary>
/// Internal enumerator class
/// </summary>
public class LinkedBlockingQueueEnumerator : IEnumerator<T> {
private readonly LinkedBlockingQueue<T> _enclosingInstance;
private Node _currentNode;
private readonly int _countAtStart;
private T _currentElement;
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public virtual T Current {
get {
return InternalCurrent;
}
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
private T InternalCurrent {
get {
lock(Enclosing_Instance.putLock) {
lock(Enclosing_Instance.takeLock) {
if(_currentNode == null)
throw new NoElementsException();
return _currentElement;
}
}
}
}
/// <summary>
///
/// </summary>
public LinkedBlockingQueue<T> Enclosing_Instance {
get { return _enclosingInstance; }
}
internal LinkedBlockingQueueEnumerator(LinkedBlockingQueue<T> enclosingInstance) {
_enclosingInstance = enclosingInstance;
lock(Enclosing_Instance.putLock) {
lock(Enclosing_Instance.takeLock) {
CurrentNode = Enclosing_Instance.head;
_countAtStart = Enclosing_Instance.Count;
}
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
public virtual void Reset() {
lock(Enclosing_Instance.putLock) {
lock(Enclosing_Instance.takeLock) {
if(_countAtStart != Enclosing_Instance.Count)
throw new InvalidOperationException("queue has changed during enumeration");
CurrentNode = Enclosing_Instance.head;
}
}
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns></returns>
public virtual bool MoveNext() {
if(_countAtStart != Enclosing_Instance.Count)
throw new InvalidOperationException("queue has changed during enumeration");
Node nextNode = _currentNode.next;
CurrentNode = nextNode;
return nextNode != null;
}
private Node CurrentNode {
set {
_currentNode = value;
if(_currentNode != null)
_currentElement = _currentNode.item;
}
}
#region IDisposable Members
/// <summary>
/// TODO implement and document
/// </summary>
public void Dispose() {
}
#endregion
#region IEnumerator Members
object System.Collections.IEnumerator.Current {
get {
return InternalCurrent;
}
}
#endregion
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// 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 System.IO;
using System.Collections.ObjectModel;
using Common;
using System.Diagnostics;
namespace Randoop
{
/// <summary>
/// This class is actually a wrapper around the actual input generator
/// (whose entrypoint is RandoopBare.MainMethod).
///
/// The wrapper performs the following steps.
///
/// 1. Parses command-line arguments.
///
/// 2. Invokes RandoopBare, possibly multiple times.
/// If RandoopBare fails before the user-specified time limit expires,
/// the wrapper calls the generator again. The reason for doing this is
/// that the generator may fail due to an error in the code under test
/// (e.g. an access violation). In this situation, the best course of
/// action is to continue generating test inputs until the time limit
/// expires.
///
/// The end result is a set of test cases (C# source files) and
/// an index.html file summarizing the results of the generation.
/// </summary>
public class Randoop
{
/// DEFAULTS.
public static readonly int defaultTotalTimeLimit = 100;
public static readonly int defaultStartTimeSeconds = 100;
/// <summary>
/// Main randoop entrypoint.
/// </summary>
static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine("Randoop.NET: an API fuzzer for .Net. Version {0} (compiled {1}).",
Common.Enviroment.RandoopVersion, Common.Enviroment.RandoopCompileDate);
if (args.Length == 0 || IsHelpCommand(args[0]))
{
Console.Error.WriteLine(HelpScreen.Usagestring());
System.Environment.Exit(1);
}
if (ContainsHelp(args))
{
Console.WriteLine(HelpScreen.Usagestring());
System.Environment.Exit(0);
}
if (args[0].Equals("/about"))
{
WriteAboutMessageToConsole();
System.Environment.Exit(0);
}
//[email protected] adds "RandoopMappedCalls"
if (args[0].Equals("methodtransformer"))
{
string mapfile = args[1];
string[] args2 = new string[args.Length - 2];
Array.Copy(args, 2, args2, 0, args.Length - 2);
Dictionary<string, string> methodmapper = new Dictionary<string,string>();
try
{
Instrument.ParseMapFile(mapfile, ref methodmapper); //parse a file that defines the mapping between target method and replacement method
foreach (string asm in args2)
{
int mapcnt = methodmapper.Count;
string [] origmethods = new string [mapcnt];
methodmapper.Keys.CopyTo(origmethods, 0);
foreach (string src in origmethods)
Instrument.MethodInstrument(asm, src, methodmapper[src]);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
System.Environment.Exit(-1);
}
System.Environment.Exit(0);
}
//[email protected] adds "RandoopMappedCalls"
if (args[0].Equals("minimize"))
{
string[] args2 = new string[args.Length - 1];
Array.Copy(args, 1, args2, 0, args.Length - 1);
TestCaseUtils.Minimize(TestCaseUtils.CollectFilesEndingWith(".cs", args2));
System.Environment.Exit(0);
}
if (args[0].Equals("reduce"))
{
string[] args2 = new string[args.Length - 1];
Array.Copy(args, 1, args2, 0, args.Length - 1);
Collection<FileInfo> oldTests = TestCaseUtils.CollectFilesEndingWith(".cs", args2);
Console.WriteLine("Number of original tests: " + oldTests.Count);
Collection<FileInfo> newTests = TestCaseUtils.Reduce(oldTests);
Console.WriteLine("Number of reduced tests: " + newTests.Count);
//Dictionary<TestCase.ExceptionDescription, Collection<FileInfo>> classifiedTests =
// TestCaseUtils.ClassifyTestsByMessage(newTests);
//PrintStats(classifiedTests);
//StringBuilder b = new StringBuilder();
//foreach (string s in args) b.Append(" " + s);
//string htmlFileName = "reduced" + Path.GetRandomFileName() + ".html";
////HtmlSummary.CreateIndexHtml(classifiedTests, htmlFileName, b.ToString());
//HtmlSummary.CreateIndexHtml2(classifiedTests, htmlFileName, b.ToString());
//OpenExplorer(htmlFileName);
System.Environment.Exit(0);
}
if (args[0].Equals("reduce2")) //[email protected] adds for sequence-based reduction
{
string[] args2 = new string[args.Length - 1];
Array.Copy(args, 1, args2, 0, args.Length - 1);
Collection<FileInfo> oldTests = TestCaseUtils.CollectFilesEndingWith(".cs", args2);
Console.WriteLine("Number of original tests: " + oldTests.Count);
Collection<FileInfo> newTests = TestCaseUtils.Reduce2(oldTests);
Console.WriteLine("Number of reduced tests: " + newTests.Count);
System.Environment.Exit(0);
}
if (args[0].Equals("reproduce"))
{
string[] args2 = new string[args.Length - 1];
Array.Copy(args, 1, args2, 0, args.Length - 1);
TestCaseUtils.ReproduceBehavior(TestCaseUtils.CollectFilesEndingWith(".cs", args2));
System.Environment.Exit(0);
}
if (args[0].StartsWith("stats:"))
{
string statsResultsFileName = args[0].Substring("stats:".Length);
string[] args2 = new string[args.Length - 1];
Array.Copy(args, 1, args2, 0, args.Length - 1);
StatsManager.ComputeStats(statsResultsFileName,
TestCaseUtils.CollectFilesEndingWith(".stats.txt", args2));
System.Environment.Exit(0);
}
GenerateTests(args);
}
private static bool ContainsHelp(string[] args)
{
foreach (string s in args)
if (s.ToLower().Equals("/?"))
return true;
return false;
}
/// <summary>
/// The "real" main entrypoint into test generation.
/// Generates tests by invoking the test generator, potentially multiple times.
/// </summary>
private static void GenerateTests(string[] argArray)
{
// Parse command line arguments.
string errorMessage;
CommandLineArguments args = new CommandLineArguments(
argArray,
defaultTotalTimeLimit,
defaultStartTimeSeconds,
out errorMessage);
if (errorMessage != null)
{
Console.WriteLine("Error in command-line arguments: " + errorMessage);
System.Environment.Exit(1);
}
//CheckAssembliesExist(args);
int randomseed = 0;
if (args.RandomSeed != null)
{
int.TryParse(args.RandomSeed, out randomseed);
}
// Invoke the generator, possibly multiple times.
// If timeLimit > Randoop.TIME_PER_INVOCATION, then the generator
// is invoked multiple times each time with time limit <= TIME_PER_INVOCATION.
string tempDir = null;
try
{
// Create temporary directory.
tempDir = Common.TempDir.CreateTempDir();
// Determine output directory.
string outputDir;
if (args.OutputDir == null)
{
// The output directory's name is calculated based on
// the day and time that this invocation of Randoop occurred.
outputDir =
System.Environment.CurrentDirectory
+ "\\randoop_output\\"
+ CalculateOutputDirBase();
}
else
{
outputDir = args.OutputDir; // TODO check legal file name.
}
// Create output directory, if it doesn't exist.
if (!Directory.Exists(outputDir))
new DirectoryInfo(outputDir).Create(); // TODO resource error checking.
// Determine execution log file name.
string executionLog = tempDir + "\\" + "execution.log";
if (args.PageHeap) PageHeaEnableRandoop();
if (args.UseDHandler) DHandlerEnable();
TimeSpan totalTime = new TimeSpan(0);
int round = 0;
Collection<string> methodsToOmit = new Collection<string>();
Collection<string> constructorsToOmit = new Collection<string>();
while (Convert.ToInt32(totalTime.TotalSeconds) < Convert.ToInt32(args.TimeLimit.TotalSeconds))
{
round++;
int exitCode = DoInputGenerationRound(args, outputDir, round,
ref totalTime, tempDir, executionLog, randomseed,
methodsToOmit, constructorsToOmit);
if (exitCode != 0)
break;
}
if (args.PageHeap) PageHeapDisableRandoop();
if (args.UseDHandler) DHandlerDisable();
// Create allstats.txt and index.html.
bool testsCreated;
if (!PostProcessTests(args, outputDir))
{
testsCreated = false;
Console.WriteLine("No tests created.");
}
else
{
testsCreated = true;
}
if (!args.KeepStatLogs)
DeleteStatLogs(outputDir);
// The final step invokes IE and displays a summary (file index.html).
if (!args.NoExplorer && testsCreated)
OpenExplorer(outputDir + "\\index.html");
}
catch (Exception e)
{
Console.WriteLine("*** Randoop error. "
+ "Please report this error to Randoop's developers.");
Console.WriteLine(e);
System.Environment.Exit(1);
}
finally
{
// Delete temp dir.
if (tempDir != null)
{
Console.WriteLine("Removing temporary directory: " + tempDir);
try
{
new DirectoryInfo(tempDir).Delete(true);
}
catch (Exception e)
{
Console.WriteLine("Exception raised while deleting temporary directory: " + e.Message);
}
}
}
}
private static void DeleteStatLogs(string outputDir)
{
foreach (FileInfo fi in TestCaseUtils.CollectFilesEndingWith(".stats.txt", outputDir))
{
fi.Delete();
}
}
private static void CheckAssembliesExist(CommandLineArguments args)
{
foreach (string s in args.AssemblyNames)
{
if (!File.Exists(s))
{
Console.WriteLine("Assembly file does not exist: " + s);
System.Environment.Exit(1);
}
}
}
/// THE RETURN VALUE MEANS "PARAMETERS WRE OK"!!!!! BAD!!
private static int DoInputGenerationRound(
CommandLineArguments args,
string outputDir,
int round,
ref TimeSpan totalTime,
string tempDir,
string executionLogFileName,
int randomseed,
Collection<string> methodsToOmit,
Collection<string> constructorsToOmit)
{
// Calculate time for next invocation of Randoop.
TimeSpan timeForNextInvocation = CalculateNextTimeLimit(args.TimeLimit, totalTime,
new TimeSpan(0, 0, args.restartTimeSeconds));
// Analyze last execution.
int lastPlanId;
AnalyzeLastExecution(executionLogFileName, out lastPlanId, outputDir);
// Create a new randoop configuration.
RandoopConfiguration config = ConfigFileCreator.CreateConfigFile(args, outputDir, lastPlanId,
timeForNextInvocation, round, executionLogFileName, randomseed);
string configFileName = tempDir + "\\config" + round + ".xml";
config.Save(configFileName);
FileInfo configFileInfo = new FileInfo(configFileName);
// Launch new instance of Randoop.
Console.WriteLine();
Console.WriteLine("------------------------------------");
Console.WriteLine("Spawning new input generator process (round " + round + ")");
Process p = new Process();
p.StartInfo.FileName = Common.Enviroment.RandoopBareExe;
p.StartInfo.Arguments = ConfigFileName.ToString(configFileInfo);
p.StartInfo.UseShellExecute = false;
p.StartInfo.ErrorDialog = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.WorkingDirectory = tempDir;
Console.WriteLine("Spawning process: ");
Console.WriteLine(Util.PrintProcess(p));
// Give it 30 seconds to load reflection info, etc.
int waitTime = (Convert.ToInt32(timeForNextInvocation.TotalSeconds) + 30)*1000;
Console.WriteLine("Will wait " + waitTime + " milliseconds for process to terminate.");
p.Start();
if (!p.WaitForExit(waitTime))
{
// Process didn't terminate. Kill it forcefully.
Console.WriteLine("Killing process " + p.Id);
try
{
p.Kill();
}
catch (InvalidOperationException)
{
// p has already terminated. No problem.
}
p.WaitForExit();
}
// Update total time.
totalTime += p.ExitTime - p.StartTime;
string err = p.StandardError.ReadToEnd();
// Randoop terminated with error.
if (p.ExitCode != 0)
{
if (err.Contains(Common.Enviroment.RandoopBareInternalErrorMessage))
{
Console.WriteLine(err);
Console.WriteLine("*** RandoopBare had an internal error. Exiting.");
return p.ExitCode;
}
if (err.Contains(Common.Enviroment.RandoopBareInvalidUserParametersErrorMessage))
{
Console.WriteLine(err);
Console.WriteLine("*** RandoopBare terminated normally. Exiting.");
return p.ExitCode;
}
}
return 0;
}
private static void OpenExplorer(string file)
{
Process explorerProcess = new Process();
explorerProcess.StartInfo.FileName = "explorer";
explorerProcess.StartInfo.Arguments = file;
explorerProcess.Start();
}
// false if no tests found.
private static bool PostProcessTests(CommandLineArguments args, string outputDir)
{
//////////////////////////////////////////////////////////////////////
// Determine directory where generated tests were written.
DirectoryInfo resultsDir = new DirectoryInfo(outputDir);
//////////////////////////////////////////////////////////////////////
// Collect all tests generated.
Collection<FileInfo> tests = TestCaseUtils.CollectFilesEndingWith(".cs", resultsDir);
if (tests.Count == 0)
{
return false;
}
Dictionary<TestCase.ExceptionDescription, Collection<FileInfo>> classifiedTests =
TestCaseUtils.ClassifyTestsByMessage(tests);
PrintStats(classifiedTests);
//////////////////////////////////////////////////////////////////////
// Create stats file.
StatsManager.ComputeStats(resultsDir + "\\allstats.txt",
TestCaseUtils.CollectFilesEndingWith(".stats.txt", resultsDir));
//////////////////////////////////////////////////////////////////////
// Create HTML index.
//HtmlSummary.CreateIndexHtml(classifiedTests, resultsDir + "\\index.html", args.ToString());
HtmlSummary.CreateIndexHtml2(classifiedTests, resultsDir + "\\index.html", args.ToString());
Console.WriteLine();
Console.WriteLine("Results written to " + resultsDir + ".");
Console.WriteLine("You can browse the results by opening the file "
+ System.Environment.NewLine
+ " " + resultsDir + "\\index.html");
return true;
}
private static string CalculateOutputDirBase()
{
System.DateTime now = System.DateTime.Now;
return
"run_"
+ Common.Misc.Monthstring(now.Month)
+ "_"
+ now.Day
+ "_"
+ now.Year
+ "_"
+ now.Hour
+ "h_"
+ now.Minute
+ "m_"
+ now.Second
+ "s";
}
private static TimeSpan CalculateNextTimeLimit(TimeSpan timeLimit, TimeSpan totalTime, TimeSpan timePerInvocation)
{
if (timeLimit - totalTime < timePerInvocation)
{
return timeLimit - totalTime;
}
else
{
return timePerInvocation;
}
}
private static void AnalyzeLastExecution(
string executionLogFileName,
out int lastPlanId,
string outputDir)
{
lastPlanId = 0;
if (new FileInfo(executionLogFileName).Exists)
{
StreamReader r = new StreamReader(executionLogFileName);
string line;
while ((line = r.ReadLine()) != null)
{
if (line.StartsWith("LASTPLANID:"))
{
lastPlanId = int.Parse(line.Substring("LASTPLANID:".Length).Trim());
continue;
}
if (r.EndOfStream)
{
AddMethodToOmit(line, outputDir);
}
}
r.Close();
}
}
private static string WrapInDHandler(string randoopCommand)
{
StringBuilder b = new StringBuilder();
b.Append("/O:\" "
+ Common.Enviroment.RandoopHome
+ "\\randoopruntime\\pagehandleroutput.txt"
+ "\"");
b.Append(" /I:"
+ "\""
+ Common.Enviroment.DefaultDhi
+ "\"");
b.Append(" /App:\"" + randoopCommand + "\"");
return b.ToString();
}
private static void WriteAboutMessageToConsole()
{
Console.WriteLine("Version "
+ Common.Enviroment.RandoopVersion
+ "."
+ System.Environment.NewLine
+ "Compiled on "
+ Common.Enviroment.RandoopCompileDate
+ "."
+ System.Environment.NewLine
+ System.Environment.NewLine
+ "Credits"
+ System.Environment.NewLine
+ " Authors: Carlos Pacheco (t-carpac)"
+ System.Environment.NewLine
+ " Shuvendu Lahiri (shuvendu)"
+ System.Environment.NewLine
+ " Tom Ball (tball)"
//+ System.Environment.NewLine
//+ " DHandler pop-up blocker by Jeff Schwartz (jeffschw)"
+ System.Environment.NewLine
+ " Help and guidance from Scott Wadsworth and Eugene Bobukh."
+ System.Environment.NewLine
);
}
private static void PrintStats(Dictionary<TestCase.ExceptionDescription, Collection<FileInfo>> testsByMessage)
{
Console.WriteLine("Results statistics:");
foreach (TestCase.ExceptionDescription message in testsByMessage.Keys)
{
String testCount =
testsByMessage[message].Count
+ " test"
+ (testsByMessage[message].Count > 1 ? "s" : "")
+ ":";
testCount = testCount.PadRight(15, ' ');
Console.WriteLine(testCount + message.ExceptionDescriptionString);
}
}
private static void PageHeapDisableRandoop()
{
Process p = new Process();
p.StartInfo.FileName = Common.Enviroment.PageHeap;
p.StartInfo.Arguments = "/disable randoopbare.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.ErrorDialog = true;
Console.WriteLine("Starting process:");
Console.WriteLine(Util.PrintProcess(p));
p.Start();
p.WaitForExit();
}
private static void PageHeaEnableRandoop()
{
Process p = new Process();
p.StartInfo.FileName = Common.Enviroment.PageHeap;
p.StartInfo.Arguments = "/enable randoopbare.exe /full";
p.StartInfo.UseShellExecute = false;
p.StartInfo.ErrorDialog = true;
Console.WriteLine("Starting process:");
Console.WriteLine(Util.PrintProcess(p));
p.Start();
p.WaitForExit();
}
private static Process dHandlerProcess;
private static void DHandlerDisable()
{
if (dHandlerProcess != null)
{
Console.WriteLine("Killing DHandler process.");
dHandlerProcess.Kill();
}
}
private static void DHandlerEnable()
{
dHandlerProcess = new Process();
dHandlerProcess.StartInfo.FileName = Common.Enviroment.DHandler;
dHandlerProcess.StartInfo.Arguments = "/I:\"" + Common.Enviroment.DefaultDhi + "\"";
dHandlerProcess.StartInfo.UseShellExecute = false;
dHandlerProcess.StartInfo.ErrorDialog = true;
Console.WriteLine("Starting process:");
Console.WriteLine(Util.PrintProcess(dHandlerProcess));
dHandlerProcess.Start();
}
private static bool IsHelpCommand(string p)
{
return p.ToLower().Equals("/?")
||
p.ToLower().Equals("-?")
||
p.ToLower().Equals("--?")
||
p.ToLower().Equals("/help")
||
p.ToLower().Equals("-help")
||
p.ToLower().Equals("--help");
}
private static void AddMethodToOmit(string line, string outputDir)
{
if (line.StartsWith("execute method ") && !line.EndsWith("end execute method"))
{
string methodName = line.Substring("execute method ".Length).Trim();
Createforbid_memberFile(methodName, outputDir);
}
else if (line.StartsWith("execute constructor ") && !line.EndsWith("end execute constructor"))
{
string constructorName = line.Substring("execute constructor ".Length).Trim();
Createforbid_memberFile(constructorName, outputDir);
}
// TODO:
// If execution terminated abruptly, find last test input that led to the termination
// (will be under "temp" Directory) and add it to an "abrupt-termination" Directory.
}
private static void Createforbid_memberFile(string methodName, string outputDir)
{
string newConfigFileName = outputDir + "\\" + Path.GetRandomFileName();
Console.WriteLine("Creating config file {0}.", newConfigFileName);
StreamWriter w = new StreamWriter(newConfigFileName);
w.WriteLine(methodName);
w.Close();
}
}
}
| |
// <copyright file="RepeatableStack{T}.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using IX.StandardExtensions.Contracts;
using JetBrains.Annotations;
// ReSharper disable once CheckNamespace
namespace IX.System.Collections.Generic;
/// <summary>
/// A stack that is able to accurately repeat the sequence of items that has been popped from it.
/// </summary>
/// <typeparam name="T">The type of items contained in this stack.</typeparam>
/// <seealso cref="IStack{T}" />
[PublicAPI]
[SuppressMessage(
"Design",
"CA1010:Generic interface should also be implemented",
Justification = "This is not necessary.")]
public class RepeatableStack<T> : IStack<T>
{
#region Internal state
private readonly List<T> internalRepeatingStack;
private readonly IStack<T> internalStack;
#endregion
#region Constructors and destructors
/// <summary>
/// Initializes a new instance of the <see cref="RepeatableStack{T}" /> class.
/// </summary>
public RepeatableStack()
{
this.internalStack = new Stack<T>();
this.internalRepeatingStack = new List<T>();
}
/// <summary>
/// Initializes a new instance of the <see cref="RepeatableStack{T}" /> class.
/// </summary>
/// <param name="originalStack">The original stack.</param>
/// <remarks>
/// <para>
/// Please note that the <paramref name="originalStack" /> will be taken and used as a source for this repeatable
/// stack, meaning that operations on this instance
/// will reflect to the original.
/// </para>
/// </remarks>
public RepeatableStack(IStack<T> originalStack)
{
Requires.NotNull(
out this.internalStack,
originalStack,
nameof(originalStack));
this.internalRepeatingStack = new List<T>();
}
/// <summary>
/// Initializes a new instance of the <see cref="RepeatableStack{T}" /> class.
/// </summary>
/// <param name="originalData">The original data.</param>
public RepeatableStack(IEnumerable<T> originalData)
{
Requires.NotNull(
originalData,
nameof(originalData));
this.internalStack = new Stack<T>(originalData);
this.internalRepeatingStack = new List<T>();
}
#endregion
#region Properties and indexers
/// <summary>Gets the number of elements in the collection.</summary>
/// <returns>The number of elements in the collection. </returns>
public int Count => ((IReadOnlyCollection<T>)this.internalStack).Count;
/// <summary>
/// Gets a value indicating whether this stack is empty.
/// </summary>
/// <value>
/// <c>true</c> if this stack is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty => this.Count == 0;
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection" /> is synchronized (thread safe).
/// </summary>
public bool IsSynchronized => false;
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection" />.
/// </summary>
public object SyncRoot => this.internalStack;
#endregion
#region Methods
#region Interface implementations
/// <summary>
/// Copies the elements of the <see cref="ICollection" /> to an <see cref="Array" />, starting at a particular
/// <see cref="Array" /> index.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array" /> that is the destination of the elements copied from
/// <see cref="ICollection" />. The <see cref="Array" /> must have zero-based indexing.
/// </param>
/// <param name="index">The zero-based index in <paramref name="array" /> at which copying begins.</param>
public void CopyTo(
Array array,
int index) =>
this.internalStack.CopyTo(
array,
index);
/// <summary>Returns an enumerator that iterates through the collection.</summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
[SuppressMessage(
"Performance",
"HAA0401:Possible allocation of reference type enumerator",
Justification = "Unavoidable.")]
public IEnumerator<T> GetEnumerator() => this.internalStack.GetEnumerator();
/// <summary>
/// Clears the observable stack.
/// </summary>
public void Clear() => this.internalStack.Clear();
/// <summary>
/// Checks whether or not a certain item is in the stack.
/// </summary>
/// <param name="item">The item to check for.</param>
/// <returns><see langword="true" /> if the item was found, <see langword="false" /> otherwise.</returns>
public bool Contains(T item) => this.internalStack.Contains(item);
/// <summary>
/// Peeks in the stack to view the topmost item, without removing it.
/// </summary>
/// <returns>The topmost element in the stack, if any.</returns>
public T Peek() => this.internalStack.Peek();
/// <summary>
/// Pops the topmost element from the stack, removing it.
/// </summary>
/// <returns>The topmost element in the stack, if any.</returns>
public T Pop()
{
T item = this.internalStack.Pop();
this.internalRepeatingStack.Add(item);
return item;
}
/// <summary>
/// Pushes an element to the top of the stack.
/// </summary>
/// <param name="item">The item to push.</param>
public void Push(T item) => this.internalStack.Push(item);
/// <summary>
/// Pushes a range of elements to the top of the stack.
/// </summary>
/// <param name="items">The item range to push.</param>
public void PushRange(T[] items) => this.internalStack.PushRange(items);
/// <summary>
/// Pushes a range of elements to the top of the stack.
/// </summary>
/// <param name="items">The item range to push.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="count">The number of items to push.</param>
public void PushRange(
T[] items,
int startIndex,
int count) =>
this.internalStack.PushRange(
items,
startIndex,
count);
/// <summary>
/// Copies all elements of the stack to a new array.
/// </summary>
/// <returns>An array containing all items in the stack.</returns>
public T[] ToArray() => this.internalStack.ToArray();
/// <summary>
/// Sets the capacity to the actual number of elements in the stack if that number is less than 90 percent of current
/// capacity.
/// </summary>
public void TrimExcess() => this.internalStack.TrimExcess();
/// <summary>
/// Attempts to peek at the topmost item from the stack, without removing it.
/// </summary>
/// <param name="item">The topmost element in the stack, default if unsuccessful.</param>
/// <returns>
/// <see langword="true" /> if an item is peeked at successfully, <see langword="false" /> otherwise, or if the
/// stack is empty.
/// </returns>
public bool TryPeek([MaybeNullWhen(false)] out T item) => this.internalStack.TryPeek(out item);
/// <summary>
/// Attempts to pop the topmost item from the stack, and remove it if successful.
/// </summary>
/// <param name="item">The topmost element in the stack, default if unsuccessful.</param>
/// <returns>
/// <see langword="true" /> if an item is popped successfully, <see langword="false" /> otherwise, or if the
/// stack is empty.
/// </returns>
public bool TryPop([MaybeNullWhen(false)] out T item)
{
if (!this.internalStack.TryPop(out T? item2))
{
item = default;
return false;
}
this.internalRepeatingStack.Add(item2);
item = item2;
return true;
}
/// <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>
[SuppressMessage(
"Performance",
"HAA0401:Possible allocation of reference type enumerator",
Justification = "Unavoidable.")]
[ExcludeFromCodeCoverage]
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
#endregion
/// <summary>
/// Gets a repeat of the sequence of elements popped from this instance.
/// </summary>
/// <returns>A repeating stack.</returns>
[SuppressMessage(
"ReSharper",
"AssignNullToNotNullAttribute",
Justification = "We want this exception if it occurs.")]
public IStack<T> Repeat() =>
new Stack<T>(
this.internalRepeatingStack.AsEnumerable()
.Reverse()
.ToArray());
#endregion
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.MenuItem_))]
public interface MenuItem : global::MonoJavaBridge.IJavaObject
{
bool isChecked();
global::android.view.MenuItem setChecked(bool arg0);
bool isEnabled();
global::android.view.MenuItem setEnabled(bool arg0);
global::android.content.Intent getIntent();
global::android.view.MenuItem setVisible(bool arg0);
bool isVisible();
global::android.view.MenuItem setIntent(android.content.Intent arg0);
global::android.view.MenuItem setTitle(int arg0);
global::android.view.MenuItem setTitle(java.lang.CharSequence arg0);
global::java.lang.CharSequence getTitle();
int getItemId();
int getGroupId();
int getOrder();
global::android.view.MenuItem setTitleCondensed(java.lang.CharSequence arg0);
global::java.lang.CharSequence getTitleCondensed();
global::android.view.MenuItem setIcon(android.graphics.drawable.Drawable arg0);
global::android.view.MenuItem setIcon(int arg0);
global::android.graphics.drawable.Drawable getIcon();
global::android.view.MenuItem setShortcut(char arg0, char arg1);
global::android.view.MenuItem setNumericShortcut(char arg0);
char getNumericShortcut();
global::android.view.MenuItem setAlphabeticShortcut(char arg0);
char getAlphabeticShortcut();
global::android.view.MenuItem setCheckable(bool arg0);
bool isCheckable();
bool hasSubMenu();
global::android.view.SubMenu getSubMenu();
global::android.view.MenuItem setOnMenuItemClickListener(android.view.MenuItem_OnMenuItemClickListener arg0);
global::android.view.ContextMenu_ContextMenuInfo getMenuInfo();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.MenuItem))]
public sealed partial class MenuItem_ : java.lang.Object, MenuItem
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static MenuItem_()
{
InitJNI();
}
internal MenuItem_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _isChecked8887;
bool android.view.MenuItem.isChecked()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.MenuItem_._isChecked8887);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._isChecked8887);
}
internal static global::MonoJavaBridge.MethodId _setChecked8888;
global::android.view.MenuItem android.view.MenuItem.setChecked(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setChecked8888, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setChecked8888, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _isEnabled8889;
bool android.view.MenuItem.isEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.MenuItem_._isEnabled8889);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._isEnabled8889);
}
internal static global::MonoJavaBridge.MethodId _setEnabled8890;
global::android.view.MenuItem android.view.MenuItem.setEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setEnabled8890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setEnabled8890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getIntent8891;
global::android.content.Intent android.view.MenuItem.getIntent()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._getIntent8891)) as android.content.Intent;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getIntent8891)) as android.content.Intent;
}
internal static global::MonoJavaBridge.MethodId _setVisible8892;
global::android.view.MenuItem android.view.MenuItem.setVisible(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setVisible8892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setVisible8892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _isVisible8893;
bool android.view.MenuItem.isVisible()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.MenuItem_._isVisible8893);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._isVisible8893);
}
internal static global::MonoJavaBridge.MethodId _setIntent8894;
global::android.view.MenuItem android.view.MenuItem.setIntent(android.content.Intent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setIntent8894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setIntent8894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _setTitle8895;
global::android.view.MenuItem android.view.MenuItem.setTitle(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setTitle8895, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setTitle8895, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _setTitle8896;
global::android.view.MenuItem android.view.MenuItem.setTitle(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setTitle8896, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setTitle8896, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getTitle8897;
global::java.lang.CharSequence android.view.MenuItem.getTitle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._getTitle8897)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getTitle8897)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _getItemId8898;
int android.view.MenuItem.getItemId()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.MenuItem_._getItemId8898);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getItemId8898);
}
internal static global::MonoJavaBridge.MethodId _getGroupId8899;
int android.view.MenuItem.getGroupId()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.MenuItem_._getGroupId8899);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getGroupId8899);
}
internal static global::MonoJavaBridge.MethodId _getOrder8900;
int android.view.MenuItem.getOrder()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.MenuItem_._getOrder8900);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getOrder8900);
}
internal static global::MonoJavaBridge.MethodId _setTitleCondensed8901;
global::android.view.MenuItem android.view.MenuItem.setTitleCondensed(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setTitleCondensed8901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setTitleCondensed8901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getTitleCondensed8902;
global::java.lang.CharSequence android.view.MenuItem.getTitleCondensed()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._getTitleCondensed8902)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getTitleCondensed8902)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _setIcon8903;
global::android.view.MenuItem android.view.MenuItem.setIcon(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setIcon8903, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setIcon8903, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _setIcon8904;
global::android.view.MenuItem android.view.MenuItem.setIcon(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setIcon8904, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setIcon8904, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getIcon8905;
global::android.graphics.drawable.Drawable android.view.MenuItem.getIcon()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._getIcon8905)) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getIcon8905)) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _setShortcut8906;
global::android.view.MenuItem android.view.MenuItem.setShortcut(char arg0, char arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setShortcut8906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setShortcut8906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _setNumericShortcut8907;
global::android.view.MenuItem android.view.MenuItem.setNumericShortcut(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setNumericShortcut8907, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setNumericShortcut8907, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getNumericShortcut8908;
char android.view.MenuItem.getNumericShortcut()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallCharMethod(this.JvmHandle, global::android.view.MenuItem_._getNumericShortcut8908);
else
return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getNumericShortcut8908);
}
internal static global::MonoJavaBridge.MethodId _setAlphabeticShortcut8909;
global::android.view.MenuItem android.view.MenuItem.setAlphabeticShortcut(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setAlphabeticShortcut8909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setAlphabeticShortcut8909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getAlphabeticShortcut8910;
char android.view.MenuItem.getAlphabeticShortcut()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallCharMethod(this.JvmHandle, global::android.view.MenuItem_._getAlphabeticShortcut8910);
else
return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getAlphabeticShortcut8910);
}
internal static global::MonoJavaBridge.MethodId _setCheckable8911;
global::android.view.MenuItem android.view.MenuItem.setCheckable(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setCheckable8911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setCheckable8911, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _isCheckable8912;
bool android.view.MenuItem.isCheckable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.MenuItem_._isCheckable8912);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._isCheckable8912);
}
internal static global::MonoJavaBridge.MethodId _hasSubMenu8913;
bool android.view.MenuItem.hasSubMenu()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.MenuItem_._hasSubMenu8913);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._hasSubMenu8913);
}
internal static global::MonoJavaBridge.MethodId _getSubMenu8914;
global::android.view.SubMenu android.view.MenuItem.getSubMenu()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._getSubMenu8914)) as android.view.SubMenu;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.SubMenu>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getSubMenu8914)) as android.view.SubMenu;
}
internal static global::MonoJavaBridge.MethodId _setOnMenuItemClickListener8915;
global::android.view.MenuItem android.view.MenuItem.setOnMenuItemClickListener(android.view.MenuItem_OnMenuItemClickListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._setOnMenuItemClickListener8915, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.MenuItem>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._setOnMenuItemClickListener8915, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.MenuItem;
}
internal static global::MonoJavaBridge.MethodId _getMenuInfo8916;
global::android.view.ContextMenu_ContextMenuInfo android.view.MenuItem.getMenuInfo()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.ContextMenu_ContextMenuInfo>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.MenuItem_._getMenuInfo8916)) as android.view.ContextMenu_ContextMenuInfo;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.view.ContextMenu_ContextMenuInfo>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.MenuItem_.staticClass, global::android.view.MenuItem_._getMenuInfo8916)) as android.view.ContextMenu_ContextMenuInfo;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.MenuItem_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/MenuItem"));
global::android.view.MenuItem_._isChecked8887 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "isChecked", "()Z");
global::android.view.MenuItem_._setChecked8888 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setChecked", "(Z)Landroid/view/MenuItem;");
global::android.view.MenuItem_._isEnabled8889 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "isEnabled", "()Z");
global::android.view.MenuItem_._setEnabled8890 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setEnabled", "(Z)Landroid/view/MenuItem;");
global::android.view.MenuItem_._getIntent8891 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getIntent", "()Landroid/content/Intent;");
global::android.view.MenuItem_._setVisible8892 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setVisible", "(Z)Landroid/view/MenuItem;");
global::android.view.MenuItem_._isVisible8893 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "isVisible", "()Z");
global::android.view.MenuItem_._setIntent8894 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setIntent", "(Landroid/content/Intent;)Landroid/view/MenuItem;");
global::android.view.MenuItem_._setTitle8895 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setTitle", "(I)Landroid/view/MenuItem;");
global::android.view.MenuItem_._setTitle8896 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setTitle", "(Ljava/lang/CharSequence;)Landroid/view/MenuItem;");
global::android.view.MenuItem_._getTitle8897 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getTitle", "()Ljava/lang/CharSequence;");
global::android.view.MenuItem_._getItemId8898 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getItemId", "()I");
global::android.view.MenuItem_._getGroupId8899 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getGroupId", "()I");
global::android.view.MenuItem_._getOrder8900 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getOrder", "()I");
global::android.view.MenuItem_._setTitleCondensed8901 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setTitleCondensed", "(Ljava/lang/CharSequence;)Landroid/view/MenuItem;");
global::android.view.MenuItem_._getTitleCondensed8902 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getTitleCondensed", "()Ljava/lang/CharSequence;");
global::android.view.MenuItem_._setIcon8903 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setIcon", "(Landroid/graphics/drawable/Drawable;)Landroid/view/MenuItem;");
global::android.view.MenuItem_._setIcon8904 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setIcon", "(I)Landroid/view/MenuItem;");
global::android.view.MenuItem_._getIcon8905 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getIcon", "()Landroid/graphics/drawable/Drawable;");
global::android.view.MenuItem_._setShortcut8906 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setShortcut", "(CC)Landroid/view/MenuItem;");
global::android.view.MenuItem_._setNumericShortcut8907 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setNumericShortcut", "(C)Landroid/view/MenuItem;");
global::android.view.MenuItem_._getNumericShortcut8908 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getNumericShortcut", "()C");
global::android.view.MenuItem_._setAlphabeticShortcut8909 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setAlphabeticShortcut", "(C)Landroid/view/MenuItem;");
global::android.view.MenuItem_._getAlphabeticShortcut8910 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getAlphabeticShortcut", "()C");
global::android.view.MenuItem_._setCheckable8911 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setCheckable", "(Z)Landroid/view/MenuItem;");
global::android.view.MenuItem_._isCheckable8912 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "isCheckable", "()Z");
global::android.view.MenuItem_._hasSubMenu8913 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "hasSubMenu", "()Z");
global::android.view.MenuItem_._getSubMenu8914 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getSubMenu", "()Landroid/view/SubMenu;");
global::android.view.MenuItem_._setOnMenuItemClickListener8915 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "setOnMenuItemClickListener", "(Landroid/view/MenuItem$OnMenuItemClickListener;)Landroid/view/MenuItem;");
global::android.view.MenuItem_._getMenuInfo8916 = @__env.GetMethodIDNoThrow(global::android.view.MenuItem_.staticClass, "getMenuInfo", "()Landroid/view/ContextMenu$ContextMenuInfo;");
}
}
}
| |
#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
[assembly: Elmah.Scc("$Id: ErrorTweetModule.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
#endregion
/// <summary>
/// HTTP module implementation that posts tweets (short messages
/// usually limited to 140 characters) about unhandled exceptions in
/// an ASP.NET Web application to a Twitter account.
/// </summary>
/// <remarks>
/// This module requires that the hosting application has permissions
/// send HTTP POST requests to another Internet domain.
/// </remarks>
public class ErrorTweetModule : HttpModuleBase, IExceptionFiltering
{
public event ExceptionFilterEventHandler Filtering;
private ICredentials _credentials;
private string _statusFormat;
private Uri _url;
private int _maxStatusLength;
private string _ellipsis;
private string _formFormat;
private ArrayList _requests;
/// <summary>
/// Initializes the module and prepares it to handle requests.
/// </summary>
protected override void OnInit(HttpApplication application)
{
if (application == null)
throw new ArgumentNullException("application");
//
// Get the configuration section of this module.
// If it's not there then there is nothing to initialize or do.
// In this case, the module is as good as mute.
//
IDictionary config = (IDictionary) GetConfig();
if (config == null)
return;
string userName = GetSetting(config, "userName", string.Empty);
string password = GetSetting(config, "password", string.Empty);
string statusFormat = GetSetting(config, "statusFormat", "{Message}");
int maxStatusLength = int.Parse(GetSetting(config, "maxStatusLength", "140"), NumberStyles.None, CultureInfo.InvariantCulture);
string ellipsis = GetSetting(config, "ellipsis", /* ... */ "\x2026");
string formFormat = GetSetting(config, "formFormat", "status={0}");
Uri url = new Uri(GetSetting(config, "url", "http://twitter.com/statuses/update.xml")
#if !NET_1_1 && !NET_1_0
, UriKind.Absolute
#endif
);
_credentials = new NetworkCredential(userName, password);
_statusFormat = statusFormat;
_url = url;
_maxStatusLength = maxStatusLength;
_ellipsis = ellipsis;
_formFormat = formFormat;
_requests = ArrayList.Synchronized(new ArrayList(4));
application.Error += new EventHandler(OnError);
ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled);
}
/// <summary>
/// Gets the <see cref="ErrorLog"/> instance to which the module
/// will log exceptions.
/// </summary>
protected virtual ErrorLog GetErrorLog(HttpContext context)
{
return ErrorLog.GetDefault(context);
}
/// <summary>
/// The handler called when an unhandled exception bubbles up to
/// the module.
/// </summary>
protected virtual void OnError(object sender, EventArgs args)
{
HttpApplication application = (HttpApplication) sender;
LogException(application.Server.GetLastError(), application.Context);
}
/// <summary>
/// The handler called when an exception is explicitly signaled.
/// </summary>
protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args)
{
LogException(args.Exception, args.Context);
}
/// <summary>
/// Logs an exception and its context to the error log.
/// </summary>
protected virtual void LogException(Exception e, HttpContext context)
{
if (e == null)
throw new ArgumentNullException("e");
//
// Fire an event to check if listeners want to filter out
// logging of the uncaught exception.
//
ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context);
OnFiltering(args);
if (args.Dismissed)
return;
//
// Tweet away...
//
HttpWebRequest request = null;
try
{
string status = StringFormatter.Format(_statusFormat, new Error(e, context));
//
// Apply ellipsis if status is too long. If the trimmed
// status plus ellipsis yields nothing then just use
// the trimmed status without ellipsis. This can happen if
// someone gives an ellipsis that is ridiculously long.
//
int maxLength = _maxStatusLength;
if (status.Length > maxLength)
{
string ellipsis = _ellipsis;
int trimmedStatusLength = maxLength - ellipsis.Length;
status = trimmedStatusLength >= 0
? status.Substring(0, trimmedStatusLength) + ellipsis
: status.Substring(0, maxLength);
}
//
// Submit the status by posting form data as typically down
// by browsers for forms found in HTML.
//
request = (HttpWebRequest) WebRequest.Create(_url);
request.Method = "POST"; // WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
if (_credentials != null) // Need Basic authentication?
{
request.Credentials = _credentials;
request.PreAuthenticate = true;
}
// See http://blogs.msdn.com/shitals/archive/2008/12/27/9254245.aspx
request.ServicePoint.Expect100Continue = false;
//
// URL-encode status into the form and get the bytes to
// determine and set the content length.
//
string encodedForm = string.Format(_formFormat, HttpUtility.UrlEncode(status));
byte[] data = Encoding.ASCII.GetBytes(encodedForm);
Debug.Assert(data.Length > 0);
request.ContentLength = data.Length;
//
// Get the request stream into which the form data is to
// be written. This is done asynchronously to free up this
// thread.
//
// NOTE: We maintain a (possibly paranoid) list of
// outstanding requests and add the request to it so that
// it does not get treated as garbage by GC. In effect,
// we are creating an explicit root. It is also possible
// for this module to get disposed before a request
// completes. During the callback, no other member should
// be touched except the requests list!
//
_requests.Add(request);
IAsyncResult ar = request.BeginGetRequestStream(
new AsyncCallback(OnGetRequestStreamCompleted),
AsyncArgs(request, data));
}
catch (Exception localException)
{
//
// IMPORTANT! We swallow any exception raised during the
// logging and send them out to the trace . The idea
// here is that logging of exceptions by itself should not
// be critical to the overall operation of the application.
// The bad thing is that we catch ANY kind of exception,
// even system ones and potentially let them slip by.
//
OnWebPostError(request, localException);
}
}
private void OnWebPostError(WebRequest request, Exception e)
{
Debug.Assert(e != null);
Trace.WriteLine(e);
if (request != null) _requests.Remove(request);
}
private static object[] AsyncArgs(params object[] args)
{
return args;
}
private void OnGetRequestStreamCompleted(IAsyncResult ar)
{
if (ar == null) throw new ArgumentNullException("ar");
object[] args = (object[]) ar.AsyncState;
OnGetRequestStreamCompleted(ar, (WebRequest) args[0], (byte[]) args[1]);
}
private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data)
{
Debug.Assert(ar != null);
Debug.Assert(request != null);
Debug.Assert(data != null);
Debug.Assert(data.Length > 0);
try
{
using (Stream output = request.EndGetRequestStream(ar))
output.Write(data, 0, data.Length);
request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request);
}
catch (Exception e)
{
OnWebPostError(request, e);
}
}
private void OnGetResponseCompleted(IAsyncResult ar)
{
if (ar == null) throw new ArgumentNullException("ar");
OnGetResponseCompleted(ar, (WebRequest) ar.AsyncState);
}
private void OnGetResponseCompleted(IAsyncResult ar, WebRequest request)
{
Debug.Assert(ar != null);
Debug.Assert(request != null);
try
{
Debug.Assert(request != null);
request.EndGetResponse(ar).Close(); // Not interested; assume OK
_requests.Remove(request);
}
catch (Exception e)
{
OnWebPostError(request, e);
}
}
/// <summary>
/// Raises the <see cref="Filtering"/> event.
/// </summary>
protected virtual void OnFiltering(ExceptionFilterEventArgs args)
{
ExceptionFilterEventHandler handler = Filtering;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Determines whether the module will be registered for discovery
/// in partial trust environments or not.
/// </summary>
protected override bool SupportDiscoverability
{
get { return true; }
}
/// <summary>
/// Gets the configuration object used by <see cref="OnInit"/> to read
/// the settings for module.
/// </summary>
protected virtual object GetConfig()
{
return Configuration.GetSubsection("errorTweet");
}
private static string GetSetting(IDictionary config, string name, string defaultValue)
{
Debug.Assert(config != null);
Debug.AssertStringNotEmpty(name);
string value = Mask.NullString((string)config[name]);
if (value.Length == 0)
{
if (defaultValue == null)
{
throw new ApplicationException(string.Format(
"The required configuration setting '{0}' is missing for the error tweeting module.", name));
}
value = defaultValue;
}
return value;
}
}
}
| |
namespace KabMan.Client
{
partial class ServerDetailList
{
/// <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(ServerDetailList));
this.barManager1 = new DevExpress.XtraBars.BarManager(this.components);
this.bar1 = new DevExpress.XtraBars.Bar();
this.BBtnNew = new DevExpress.XtraBars.BarButtonItem();
this.BBtnDetail = new DevExpress.XtraBars.BarButtonItem();
this.BBtnDelete = new DevExpress.XtraBars.BarButtonItem();
this.BBtnClose = new DevExpress.XtraBars.BarButtonItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.gridControl1 = new DevExpress.XtraGrid.GridControl();
this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView();
this.ServerDetail = new DevExpress.XtraGrid.Columns.GridColumn();
this.RackId = new DevExpress.XtraGrid.Columns.GridColumn();
this.LC_URM = new DevExpress.XtraGrid.Columns.GridColumn();
this.Blech = new DevExpress.XtraGrid.Columns.GridColumn();
this.Trunk = new DevExpress.XtraGrid.Columns.GridColumn();
this.VTPort = new DevExpress.XtraGrid.Columns.GridColumn();
this.UrmUrm = new DevExpress.XtraGrid.Columns.GridColumn();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
this.SuspendLayout();
//
// barManager1
//
this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.bar1});
this.barManager1.DockControls.Add(this.barDockControlTop);
this.barManager1.DockControls.Add(this.barDockControlBottom);
this.barManager1.DockControls.Add(this.barDockControlLeft);
this.barManager1.DockControls.Add(this.barDockControlRight);
this.barManager1.Form = this;
this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.BBtnNew,
this.BBtnDetail,
this.BBtnDelete,
this.BBtnClose});
this.barManager1.MaxItemId = 4;
//
// bar1
//
this.bar1.BarName = "Tools";
this.bar1.DockCol = 0;
this.bar1.DockRow = 0;
this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.BBtnNew),
new DevExpress.XtraBars.LinkPersistInfo(this.BBtnDetail),
new DevExpress.XtraBars.LinkPersistInfo(this.BBtnDelete),
new DevExpress.XtraBars.LinkPersistInfo(this.BBtnClose, true)});
this.bar1.Text = "Tools";
//
// BBtnNew
//
this.BBtnNew.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnNew.Glyph")));
this.BBtnNew.Id = 0;
this.BBtnNew.Name = "BBtnNew";
this.BBtnNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.BBtnNew_ItemClick);
//
// BBtnDetail
//
this.BBtnDetail.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnDetail.Glyph")));
this.BBtnDetail.Id = 1;
this.BBtnDetail.Name = "BBtnDetail";
//
// BBtnDelete
//
this.BBtnDelete.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnDelete.Glyph")));
this.BBtnDelete.Id = 2;
this.BBtnDelete.Name = "BBtnDelete";
//
// BBtnClose
//
this.BBtnClose.Glyph = ((System.Drawing.Image)(resources.GetObject("BBtnClose.Glyph")));
this.BBtnClose.Id = 3;
this.BBtnClose.Name = "BBtnClose";
//
// layoutControl1
//
this.layoutControl1.Controls.Add(this.gridControl1);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 26);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(680, 433);
this.layoutControl1.TabIndex = 4;
this.layoutControl1.Text = "layoutControl1";
//
// gridControl1
//
this.gridControl1.EmbeddedNavigator.Name = "";
this.gridControl1.Location = new System.Drawing.Point(7, 7);
this.gridControl1.MainView = this.gridView1;
this.gridControl1.Name = "gridControl1";
this.gridControl1.Size = new System.Drawing.Size(667, 420);
this.gridControl1.TabIndex = 6;
this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.gridView1});
//
// gridView1
//
this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true;
this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true;
this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true;
this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.gridView1.Appearance.Empty.Options.UseBackColor = true;
this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite;
this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.EvenRow.Options.UseBackColor = true;
this.gridView1.Appearance.EvenRow.Options.UseForeColor = true;
this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225)))));
this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true;
this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true;
this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true;
this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135)))));
this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true;
this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true;
this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58)))));
this.gridView1.Appearance.FixedLine.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225)))));
this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true;
this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy;
this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178)))));
this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true;
this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true;
this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true;
this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true;
this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.GroupButton.Options.UseBackColor = true;
this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true;
this.gridView1.Appearance.GroupButton.Options.UseForeColor = true;
this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true;
this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true;
this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true;
this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165)))));
this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White;
this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true;
this.gridView1.Appearance.GroupPanel.Options.UseFont = true;
this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true;
this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupRow.Options.UseBackColor = true;
this.gridView1.Appearance.GroupRow.Options.UseForeColor = true;
this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true;
this.gridView1.Appearance.HeaderPanel.Options.UseFont = true;
this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true;
this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true;
this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true;
this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HorzLine.Options.UseBackColor = true;
this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White;
this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
this.gridView1.Appearance.OddRow.Options.UseBackColor = true;
this.gridView1.Appearance.OddRow.Options.UseForeColor = true;
this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy;
this.gridView1.Appearance.Preview.Options.UseBackColor = true;
this.gridView1.Appearance.Preview.Options.UseForeColor = true;
this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.Row.Options.UseBackColor = true;
this.gridView1.Appearance.Row.Options.UseForeColor = true;
this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true;
this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138)))));
this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true;
this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true;
this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.VertLine.Options.UseBackColor = true;
this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.ServerDetail,
this.RackId,
this.LC_URM,
this.Blech,
this.Trunk,
this.VTPort,
this.UrmUrm});
this.gridView1.GridControl = this.gridControl1;
this.gridView1.Name = "gridView1";
this.gridView1.OptionsBehavior.AllowIncrementalSearch = true;
this.gridView1.OptionsBehavior.Editable = false;
this.gridView1.OptionsCustomization.AllowFilter = false;
this.gridView1.OptionsMenu.EnableColumnMenu = false;
this.gridView1.OptionsMenu.EnableFooterMenu = false;
this.gridView1.OptionsMenu.EnableGroupPanelMenu = false;
this.gridView1.OptionsView.EnableAppearanceEvenRow = true;
this.gridView1.OptionsView.EnableAppearanceOddRow = true;
this.gridView1.OptionsView.ShowAutoFilterRow = true;
this.gridView1.OptionsView.ShowGroupPanel = false;
this.gridView1.OptionsView.ShowIndicator = false;
//
// ServerDetail
//
this.ServerDetail.Caption = "Server Detail Id";
this.ServerDetail.FieldName = "Id";
this.ServerDetail.Name = "ServerDetail";
//
// RackId
//
this.RackId.Caption = "Rack Id";
this.RackId.FieldName = "RackId";
this.RackId.Name = "RackId";
//
// LC_URM
//
this.LC_URM.Caption = "LC_URM Cable";
this.LC_URM.FieldName = "LcUrmId";
this.LC_URM.Name = "LC_URM";
this.LC_URM.Visible = true;
this.LC_URM.VisibleIndex = 0;
this.LC_URM.Width = 108;
//
// Blech
//
this.Blech.Caption = "Blech";
this.Blech.FieldName = "BlechId";
this.Blech.Name = "Blech";
this.Blech.Visible = true;
this.Blech.VisibleIndex = 1;
this.Blech.Width = 108;
//
// Trunk
//
this.Trunk.Caption = "Trunk Cable";
this.Trunk.FieldName = "TrunkId";
this.Trunk.Name = "Trunk";
this.Trunk.Visible = true;
this.Trunk.VisibleIndex = 2;
this.Trunk.Width = 84;
//
// VTPort
//
this.VTPort.Caption = "VT Port";
this.VTPort.FieldName = "VTPortId";
this.VTPort.Name = "VTPort";
this.VTPort.Visible = true;
this.VTPort.VisibleIndex = 3;
this.VTPort.Width = 108;
//
// UrmUrm
//
this.UrmUrm.Caption = "URM_URM Cable";
this.UrmUrm.FieldName = "UrmUrmId";
this.UrmUrm.Name = "UrmUrm";
this.UrmUrm.Visible = true;
this.UrmUrm.VisibleIndex = 4;
this.UrmUrm.Width = 115;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(680, 433);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.gridControl1;
this.layoutControlItem1.CustomizationFormText = "layoutControlItem1";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(678, 431);
this.layoutControlItem1.Text = "layoutControlItem1";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextToControlDistance = 0;
this.layoutControlItem1.TextVisible = false;
//
// ServerDetailList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(680, 459);
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Name = "ServerDetailList";
this.Text = "ServerDetailList";
this.Load += new System.EventHandler(this.ServerDetailList_Load);
((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraBars.BarManager barManager1;
private DevExpress.XtraBars.Bar bar1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraBars.BarButtonItem BBtnNew;
private DevExpress.XtraBars.BarButtonItem BBtnDetail;
private DevExpress.XtraGrid.GridControl gridControl1;
private DevExpress.XtraGrid.Views.Grid.GridView gridView1;
private DevExpress.XtraGrid.Columns.GridColumn ServerDetail;
private DevExpress.XtraGrid.Columns.GridColumn RackId;
private DevExpress.XtraGrid.Columns.GridColumn LC_URM;
private DevExpress.XtraGrid.Columns.GridColumn Blech;
private DevExpress.XtraGrid.Columns.GridColumn Trunk;
private DevExpress.XtraGrid.Columns.GridColumn VTPort;
private DevExpress.XtraGrid.Columns.GridColumn UrmUrm;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraBars.BarButtonItem BBtnDelete;
private DevExpress.XtraBars.BarButtonItem BBtnClose;
}
}
| |
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 OrgPortalServer.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Wave Auto Install Request
///<para>SObject Name: WaveAutoInstallRequest</para>
///<para>Custom Object: False</para>
///</summary>
public class SfWaveAutoInstallRequest : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "WaveAutoInstallRequest"; }
}
///<summary>
/// Request Id
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Request Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Wave Template Api Name
/// <para>Name: TemplateApiName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "templateApiName")]
[Updateable(false), Createable(true)]
public string TemplateApiName { get; set; }
///<summary>
/// Wave Template Version
/// <para>Name: TemplateVersion</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "templateVersion")]
[Updateable(false), Createable(true)]
public string TemplateVersion { get; set; }
///<summary>
/// Folder ID
/// <para>Name: FolderId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "folderId")]
[Updateable(false), Createable(true)]
public string FolderId { get; set; }
///<summary>
/// ReferenceTo: Folder
/// <para>RelationshipName: Folder</para>
///</summary>
[JsonProperty(PropertyName = "folder")]
[Updateable(false), Createable(false)]
public SfFolder Folder { get; set; }
///<summary>
/// Request Type
/// <para>Name: RequestType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "requestType")]
[Updateable(false), Createable(true)]
public string RequestType { get; set; }
///<summary>
/// Request Status
/// <para>Name: RequestStatus</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "requestStatus")]
public string RequestStatus { get; set; }
///<summary>
/// Failed Reason
/// <para>Name: FailedReason</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "failedReason")]
[Updateable(false), Createable(false)]
public string FailedReason { get; set; }
///<summary>
/// Configuration
/// <para>Name: Configuration</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "configuration")]
[Updateable(false), Createable(true)]
public string Configuration { get; set; }
///<summary>
/// Request Log
/// <para>Name: RequestLog</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "requestLog")]
public string RequestLog { get; set; }
}
}
| |
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
public class PostEffectsBase : MonoBehaviour {
protected bool supportHDRTextures = true;
protected bool supportDX11 = false;
protected bool isSupported = true;
protected Material CheckShaderAndCreateMaterial ( Shader s , Material m2Create ){
if (!s) {
Debug.Log("Missing shader in " + this.ToString ());
enabled = false;
return null;
}
if (s.isSupported && m2Create && m2Create.shader == s)
return m2Create;
if (!s.isSupported) {
NotSupported ();
Debug.Log("The shader " + s.ToString() + " on effect "+this.ToString()+" is not supported on this platform!");
return null;
}
else {
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
protected Material CreateMaterial ( Shader s , Material m2Create ){
if (!s) {
Debug.Log ("Missing shader in " + this.ToString ());
return null;
}
if (m2Create && (m2Create.shader == s) && (s.isSupported))
return m2Create;
if (!s.isSupported) {
return null;
}
else {
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
void OnEnable (){
isSupported = true;
}
protected bool CheckSupport (){
return CheckSupport (false);
}
public virtual bool CheckResources (){
Debug.LogWarning ("CheckResources () for " + this.ToString() + " should be overwritten.");
return isSupported;
}
protected void Start (){
CheckResources ();
}
protected bool CheckSupport ( bool needDepth ){
isSupported = true;
supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf);
supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders;
if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures) {
NotSupported ();
return false;
}
if(needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) {
NotSupported ();
return false;
}
if(needDepth)
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
return true;
}
protected bool CheckSupport ( bool needDepth , bool needHdr ){
if(!CheckSupport(needDepth))
return false;
if(needHdr && !supportHDRTextures) {
NotSupported ();
return false;
}
return true;
}
public bool Dx11Support (){
return supportDX11;
}
protected void ReportAutoDisable (){
Debug.LogWarning ("The image effect " + this.ToString() + " has been disabled as it's not supported on the current platform.");
}
// deprecated but needed for old effects to survive upgrading
bool CheckShader ( Shader s ){
Debug.Log("The shader " + s.ToString () + " on effect "+ this.ToString () + " is not part of the Unity 3.2f+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package.");
if (!s.isSupported) {
NotSupported ();
return false;
}
else {
return false;
}
}
protected void NotSupported (){
enabled = false;
isSupported = false;
return;
}
protected void DrawBorder ( RenderTexture dest , Material material ){
float x1;
float x2;
float y1;
float y2;
RenderTexture.active = dest;
bool invertY = true; // source.texelSize.y < 0.0ff;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadOrtho();
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
// left
x1 = 0.0f;
x2 = 0.0f + 1.0f/(dest.width*1.0f);
y1 = 0.0f;
y2 = 1.0f;
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// right
x1 = 1.0f - 1.0f/(dest.width*1.0f);
x2 = 1.0f;
y1 = 0.0f;
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// top
x1 = 0.0f;
x2 = 1.0f;
y1 = 0.0f;
y2 = 0.0f + 1.0f/(dest.height*1.0f);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// bottom
x1 = 0.0f;
x2 = 1.0f;
y1 = 1.0f - 1.0f/(dest.height*1.0f);
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
GL.End();
}
GL.PopMatrix();
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Microsoft.Xrm.Sdk;
namespace PowerShellLibrary.Crm.CmdletProviders
{
[GeneratedCode("CrmSvcUtil", "7.1.0001.3108")]
[DataContract]
[Microsoft.Xrm.Sdk.Client.EntityLogicalName("publisher")]
public class Publisher : Entity, INotifyPropertyChanging, INotifyPropertyChanged
{
public const string EntityLogicalName = "publisher";
public const int EntityTypeCode = 7101;
[AttributeLogicalName("address1_addressid")]
public Guid? Address1_AddressId
{
get
{
return this.GetAttributeValue<Guid?>("address1_addressid");
}
set
{
this.OnPropertyChanging("Address1_AddressId");
this.SetAttributeValue("address1_addressid", (object) value);
this.OnPropertyChanged("Address1_AddressId");
}
}
[AttributeLogicalName("address1_addresstypecode")]
public OptionSetValue Address1_AddressTypeCode
{
get
{
return this.GetAttributeValue<OptionSetValue>("address1_addresstypecode");
}
set
{
this.OnPropertyChanging("Address1_AddressTypeCode");
this.SetAttributeValue("address1_addresstypecode", (object) value);
this.OnPropertyChanged("Address1_AddressTypeCode");
}
}
[AttributeLogicalName("address1_city")]
public string Address1_City
{
get
{
return this.GetAttributeValue<string>("address1_city");
}
set
{
this.OnPropertyChanging("Address1_City");
this.SetAttributeValue("address1_city", (object) value);
this.OnPropertyChanged("Address1_City");
}
}
[AttributeLogicalName("address1_country")]
public string Address1_Country
{
get
{
return this.GetAttributeValue<string>("address1_country");
}
set
{
this.OnPropertyChanging("Address1_Country");
this.SetAttributeValue("address1_country", (object) value);
this.OnPropertyChanged("Address1_Country");
}
}
[AttributeLogicalName("address1_county")]
public string Address1_County
{
get
{
return this.GetAttributeValue<string>("address1_county");
}
set
{
this.OnPropertyChanging("Address1_County");
this.SetAttributeValue("address1_county", (object) value);
this.OnPropertyChanged("Address1_County");
}
}
[AttributeLogicalName("address1_fax")]
public string Address1_Fax
{
get
{
return this.GetAttributeValue<string>("address1_fax");
}
set
{
this.OnPropertyChanging("Address1_Fax");
this.SetAttributeValue("address1_fax", (object) value);
this.OnPropertyChanged("Address1_Fax");
}
}
[AttributeLogicalName("address1_latitude")]
public double? Address1_Latitude
{
get
{
return this.GetAttributeValue<double?>("address1_latitude");
}
set
{
this.OnPropertyChanging("Address1_Latitude");
this.SetAttributeValue("address1_latitude", (object) value);
this.OnPropertyChanged("Address1_Latitude");
}
}
[AttributeLogicalName("address1_line1")]
public string Address1_Line1
{
get
{
return this.GetAttributeValue<string>("address1_line1");
}
set
{
this.OnPropertyChanging("Address1_Line1");
this.SetAttributeValue("address1_line1", (object) value);
this.OnPropertyChanged("Address1_Line1");
}
}
[AttributeLogicalName("address1_line2")]
public string Address1_Line2
{
get
{
return this.GetAttributeValue<string>("address1_line2");
}
set
{
this.OnPropertyChanging("Address1_Line2");
this.SetAttributeValue("address1_line2", (object) value);
this.OnPropertyChanged("Address1_Line2");
}
}
[AttributeLogicalName("address1_line3")]
public string Address1_Line3
{
get
{
return this.GetAttributeValue<string>("address1_line3");
}
set
{
this.OnPropertyChanging("Address1_Line3");
this.SetAttributeValue("address1_line3", (object) value);
this.OnPropertyChanged("Address1_Line3");
}
}
[AttributeLogicalName("address1_longitude")]
public double? Address1_Longitude
{
get
{
return this.GetAttributeValue<double?>("address1_longitude");
}
set
{
this.OnPropertyChanging("Address1_Longitude");
this.SetAttributeValue("address1_longitude", (object) value);
this.OnPropertyChanged("Address1_Longitude");
}
}
[AttributeLogicalName("address1_name")]
public string Address1_Name
{
get
{
return this.GetAttributeValue<string>("address1_name");
}
set
{
this.OnPropertyChanging("Address1_Name");
this.SetAttributeValue("address1_name", (object) value);
this.OnPropertyChanged("Address1_Name");
}
}
[AttributeLogicalName("address1_postalcode")]
public string Address1_PostalCode
{
get
{
return this.GetAttributeValue<string>("address1_postalcode");
}
set
{
this.OnPropertyChanging("Address1_PostalCode");
this.SetAttributeValue("address1_postalcode", (object) value);
this.OnPropertyChanged("Address1_PostalCode");
}
}
[AttributeLogicalName("address1_postofficebox")]
public string Address1_PostOfficeBox
{
get
{
return this.GetAttributeValue<string>("address1_postofficebox");
}
set
{
this.OnPropertyChanging("Address1_PostOfficeBox");
this.SetAttributeValue("address1_postofficebox", (object) value);
this.OnPropertyChanged("Address1_PostOfficeBox");
}
}
[AttributeLogicalName("address1_shippingmethodcode")]
public OptionSetValue Address1_ShippingMethodCode
{
get
{
return this.GetAttributeValue<OptionSetValue>("address1_shippingmethodcode");
}
set
{
this.OnPropertyChanging("Address1_ShippingMethodCode");
this.SetAttributeValue("address1_shippingmethodcode", (object) value);
this.OnPropertyChanged("Address1_ShippingMethodCode");
}
}
[AttributeLogicalName("address1_stateorprovince")]
public string Address1_StateOrProvince
{
get
{
return this.GetAttributeValue<string>("address1_stateorprovince");
}
set
{
this.OnPropertyChanging("Address1_StateOrProvince");
this.SetAttributeValue("address1_stateorprovince", (object) value);
this.OnPropertyChanged("Address1_StateOrProvince");
}
}
[AttributeLogicalName("address1_telephone1")]
public string Address1_Telephone1
{
get
{
return this.GetAttributeValue<string>("address1_telephone1");
}
set
{
this.OnPropertyChanging("Address1_Telephone1");
this.SetAttributeValue("address1_telephone1", (object) value);
this.OnPropertyChanged("Address1_Telephone1");
}
}
[AttributeLogicalName("address1_telephone2")]
public string Address1_Telephone2
{
get
{
return this.GetAttributeValue<string>("address1_telephone2");
}
set
{
this.OnPropertyChanging("Address1_Telephone2");
this.SetAttributeValue("address1_telephone2", (object) value);
this.OnPropertyChanged("Address1_Telephone2");
}
}
[AttributeLogicalName("address1_telephone3")]
public string Address1_Telephone3
{
get
{
return this.GetAttributeValue<string>("address1_telephone3");
}
set
{
this.OnPropertyChanging("Address1_Telephone3");
this.SetAttributeValue("address1_telephone3", (object) value);
this.OnPropertyChanged("Address1_Telephone3");
}
}
[AttributeLogicalName("address1_upszone")]
public string Address1_UPSZone
{
get
{
return this.GetAttributeValue<string>("address1_upszone");
}
set
{
this.OnPropertyChanging("Address1_UPSZone");
this.SetAttributeValue("address1_upszone", (object) value);
this.OnPropertyChanged("Address1_UPSZone");
}
}
[AttributeLogicalName("address1_utcoffset")]
public int? Address1_UTCOffset
{
get
{
return this.GetAttributeValue<int?>("address1_utcoffset");
}
set
{
this.OnPropertyChanging("Address1_UTCOffset");
this.SetAttributeValue("address1_utcoffset", (object) value);
this.OnPropertyChanged("Address1_UTCOffset");
}
}
[AttributeLogicalName("address2_addressid")]
public Guid? Address2_AddressId
{
get
{
return this.GetAttributeValue<Guid?>("address2_addressid");
}
set
{
this.OnPropertyChanging("Address2_AddressId");
this.SetAttributeValue("address2_addressid", (object) value);
this.OnPropertyChanged("Address2_AddressId");
}
}
[AttributeLogicalName("address2_addresstypecode")]
public OptionSetValue Address2_AddressTypeCode
{
get
{
return this.GetAttributeValue<OptionSetValue>("address2_addresstypecode");
}
set
{
this.OnPropertyChanging("Address2_AddressTypeCode");
this.SetAttributeValue("address2_addresstypecode", (object) value);
this.OnPropertyChanged("Address2_AddressTypeCode");
}
}
[AttributeLogicalName("address2_city")]
public string Address2_City
{
get
{
return this.GetAttributeValue<string>("address2_city");
}
set
{
this.OnPropertyChanging("Address2_City");
this.SetAttributeValue("address2_city", (object) value);
this.OnPropertyChanged("Address2_City");
}
}
[AttributeLogicalName("address2_country")]
public string Address2_Country
{
get
{
return this.GetAttributeValue<string>("address2_country");
}
set
{
this.OnPropertyChanging("Address2_Country");
this.SetAttributeValue("address2_country", (object) value);
this.OnPropertyChanged("Address2_Country");
}
}
[AttributeLogicalName("address2_county")]
public string Address2_County
{
get
{
return this.GetAttributeValue<string>("address2_county");
}
set
{
this.OnPropertyChanging("Address2_County");
this.SetAttributeValue("address2_county", (object) value);
this.OnPropertyChanged("Address2_County");
}
}
[AttributeLogicalName("address2_fax")]
public string Address2_Fax
{
get
{
return this.GetAttributeValue<string>("address2_fax");
}
set
{
this.OnPropertyChanging("Address2_Fax");
this.SetAttributeValue("address2_fax", (object) value);
this.OnPropertyChanged("Address2_Fax");
}
}
[AttributeLogicalName("address2_latitude")]
public double? Address2_Latitude
{
get
{
return this.GetAttributeValue<double?>("address2_latitude");
}
set
{
this.OnPropertyChanging("Address2_Latitude");
this.SetAttributeValue("address2_latitude", (object) value);
this.OnPropertyChanged("Address2_Latitude");
}
}
[AttributeLogicalName("address2_line1")]
public string Address2_Line1
{
get
{
return this.GetAttributeValue<string>("address2_line1");
}
set
{
this.OnPropertyChanging("Address2_Line1");
this.SetAttributeValue("address2_line1", (object) value);
this.OnPropertyChanged("Address2_Line1");
}
}
[AttributeLogicalName("address2_line2")]
public string Address2_Line2
{
get
{
return this.GetAttributeValue<string>("address2_line2");
}
set
{
this.OnPropertyChanging("Address2_Line2");
this.SetAttributeValue("address2_line2", (object) value);
this.OnPropertyChanged("Address2_Line2");
}
}
[AttributeLogicalName("address2_line3")]
public string Address2_Line3
{
get
{
return this.GetAttributeValue<string>("address2_line3");
}
set
{
this.OnPropertyChanging("Address2_Line3");
this.SetAttributeValue("address2_line3", (object) value);
this.OnPropertyChanged("Address2_Line3");
}
}
[AttributeLogicalName("address2_longitude")]
public double? Address2_Longitude
{
get
{
return this.GetAttributeValue<double?>("address2_longitude");
}
set
{
this.OnPropertyChanging("Address2_Longitude");
this.SetAttributeValue("address2_longitude", (object) value);
this.OnPropertyChanged("Address2_Longitude");
}
}
[AttributeLogicalName("address2_name")]
public string Address2_Name
{
get
{
return this.GetAttributeValue<string>("address2_name");
}
set
{
this.OnPropertyChanging("Address2_Name");
this.SetAttributeValue("address2_name", (object) value);
this.OnPropertyChanged("Address2_Name");
}
}
[AttributeLogicalName("address2_postalcode")]
public string Address2_PostalCode
{
get
{
return this.GetAttributeValue<string>("address2_postalcode");
}
set
{
this.OnPropertyChanging("Address2_PostalCode");
this.SetAttributeValue("address2_postalcode", (object) value);
this.OnPropertyChanged("Address2_PostalCode");
}
}
[AttributeLogicalName("address2_postofficebox")]
public string Address2_PostOfficeBox
{
get
{
return this.GetAttributeValue<string>("address2_postofficebox");
}
set
{
this.OnPropertyChanging("Address2_PostOfficeBox");
this.SetAttributeValue("address2_postofficebox", (object) value);
this.OnPropertyChanged("Address2_PostOfficeBox");
}
}
[AttributeLogicalName("address2_shippingmethodcode")]
public OptionSetValue Address2_ShippingMethodCode
{
get
{
return this.GetAttributeValue<OptionSetValue>("address2_shippingmethodcode");
}
set
{
this.OnPropertyChanging("Address2_ShippingMethodCode");
this.SetAttributeValue("address2_shippingmethodcode", (object) value);
this.OnPropertyChanged("Address2_ShippingMethodCode");
}
}
[AttributeLogicalName("address2_stateorprovince")]
public string Address2_StateOrProvince
{
get
{
return this.GetAttributeValue<string>("address2_stateorprovince");
}
set
{
this.OnPropertyChanging("Address2_StateOrProvince");
this.SetAttributeValue("address2_stateorprovince", (object) value);
this.OnPropertyChanged("Address2_StateOrProvince");
}
}
[AttributeLogicalName("address2_telephone1")]
public string Address2_Telephone1
{
get
{
return this.GetAttributeValue<string>("address2_telephone1");
}
set
{
this.OnPropertyChanging("Address2_Telephone1");
this.SetAttributeValue("address2_telephone1", (object) value);
this.OnPropertyChanged("Address2_Telephone1");
}
}
[AttributeLogicalName("address2_telephone2")]
public string Address2_Telephone2
{
get
{
return this.GetAttributeValue<string>("address2_telephone2");
}
set
{
this.OnPropertyChanging("Address2_Telephone2");
this.SetAttributeValue("address2_telephone2", (object) value);
this.OnPropertyChanged("Address2_Telephone2");
}
}
[AttributeLogicalName("address2_telephone3")]
public string Address2_Telephone3
{
get
{
return this.GetAttributeValue<string>("address2_telephone3");
}
set
{
this.OnPropertyChanging("Address2_Telephone3");
this.SetAttributeValue("address2_telephone3", (object) value);
this.OnPropertyChanged("Address2_Telephone3");
}
}
[AttributeLogicalName("address2_upszone")]
public string Address2_UPSZone
{
get
{
return this.GetAttributeValue<string>("address2_upszone");
}
set
{
this.OnPropertyChanging("Address2_UPSZone");
this.SetAttributeValue("address2_upszone", (object) value);
this.OnPropertyChanged("Address2_UPSZone");
}
}
[AttributeLogicalName("address2_utcoffset")]
public int? Address2_UTCOffset
{
get
{
return this.GetAttributeValue<int?>("address2_utcoffset");
}
set
{
this.OnPropertyChanging("Address2_UTCOffset");
this.SetAttributeValue("address2_utcoffset", (object) value);
this.OnPropertyChanged("Address2_UTCOffset");
}
}
[AttributeLogicalName("createdby")]
public EntityReference CreatedBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdby");
}
}
[AttributeLogicalName("createdon")]
public DateTime? CreatedOn
{
get
{
return this.GetAttributeValue<DateTime?>("createdon");
}
}
[AttributeLogicalName("createdonbehalfby")]
public EntityReference CreatedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("createdonbehalfby");
}
}
[AttributeLogicalName("customizationoptionvalueprefix")]
public int? CustomizationOptionValuePrefix
{
get
{
return this.GetAttributeValue<int?>("customizationoptionvalueprefix");
}
set
{
this.OnPropertyChanging("CustomizationOptionValuePrefix");
this.SetAttributeValue("customizationoptionvalueprefix", (object) value);
this.OnPropertyChanged("CustomizationOptionValuePrefix");
}
}
[AttributeLogicalName("customizationprefix")]
public string CustomizationPrefix
{
get
{
return this.GetAttributeValue<string>("customizationprefix");
}
set
{
this.OnPropertyChanging("CustomizationPrefix");
this.SetAttributeValue("customizationprefix", (object) value);
this.OnPropertyChanged("CustomizationPrefix");
}
}
[AttributeLogicalName("description")]
public string Description
{
get
{
return this.GetAttributeValue<string>("description");
}
set
{
this.OnPropertyChanging("Description");
this.SetAttributeValue("description", (object) value);
this.OnPropertyChanged("Description");
}
}
[AttributeLogicalName("emailaddress")]
public string EMailAddress
{
get
{
return this.GetAttributeValue<string>("emailaddress");
}
set
{
this.OnPropertyChanging("EMailAddress");
this.SetAttributeValue("emailaddress", (object) value);
this.OnPropertyChanged("EMailAddress");
}
}
[AttributeLogicalName("entityimage")]
public byte[] EntityImage
{
get
{
return this.GetAttributeValue<byte[]>("entityimage");
}
set
{
this.OnPropertyChanging("EntityImage");
this.SetAttributeValue("entityimage", (object) value);
this.OnPropertyChanged("EntityImage");
}
}
[AttributeLogicalName("entityimage_timestamp")]
public long? EntityImage_Timestamp
{
get
{
return this.GetAttributeValue<long?>("entityimage_timestamp");
}
}
[AttributeLogicalName("entityimage_url")]
public string EntityImage_URL
{
get
{
return this.GetAttributeValue<string>("entityimage_url");
}
}
[AttributeLogicalName("entityimageid")]
public Guid? EntityImageId
{
get
{
return this.GetAttributeValue<Guid?>("entityimageid");
}
}
[AttributeLogicalName("friendlyname")]
public string FriendlyName
{
get
{
return this.GetAttributeValue<string>("friendlyname");
}
set
{
this.OnPropertyChanging("FriendlyName");
this.SetAttributeValue("friendlyname", (object) value);
this.OnPropertyChanged("FriendlyName");
}
}
[AttributeLogicalName("isreadonly")]
public bool? IsReadonly
{
get
{
return this.GetAttributeValue<bool?>("isreadonly");
}
}
[AttributeLogicalName("modifiedby")]
public EntityReference ModifiedBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedby");
}
}
[AttributeLogicalName("modifiedon")]
public DateTime? ModifiedOn
{
get
{
return this.GetAttributeValue<DateTime?>("modifiedon");
}
}
[AttributeLogicalName("modifiedonbehalfby")]
public EntityReference ModifiedOnBehalfBy
{
get
{
return this.GetAttributeValue<EntityReference>("modifiedonbehalfby");
}
}
[AttributeLogicalName("organizationid")]
public EntityReference OrganizationId
{
get
{
return this.GetAttributeValue<EntityReference>("organizationid");
}
}
[AttributeLogicalName("pinpointpublisherdefaultlocale")]
public string PinpointPublisherDefaultLocale
{
get
{
return this.GetAttributeValue<string>("pinpointpublisherdefaultlocale");
}
}
[AttributeLogicalName("pinpointpublisherid")]
public long? PinpointPublisherId
{
get
{
return this.GetAttributeValue<long?>("pinpointpublisherid");
}
}
[AttributeLogicalName("publisherid")]
public Guid? PublisherId
{
get
{
return this.GetAttributeValue<Guid?>("publisherid");
}
set
{
this.OnPropertyChanging("PublisherId");
this.SetAttributeValue("publisherid", (object) value);
if (value.HasValue)
base.Id = value.Value;
else
base.Id = Guid.Empty;
this.OnPropertyChanged("PublisherId");
}
}
[AttributeLogicalName("publisherid")]
public override Guid Id
{
get
{
return base.Id;
}
set
{
this.PublisherId = new Guid?(value);
}
}
[AttributeLogicalName("supportingwebsiteurl")]
public string SupportingWebsiteUrl
{
get
{
return this.GetAttributeValue<string>("supportingwebsiteurl");
}
set
{
this.OnPropertyChanging("SupportingWebsiteUrl");
this.SetAttributeValue("supportingwebsiteurl", (object) value);
this.OnPropertyChanged("SupportingWebsiteUrl");
}
}
[AttributeLogicalName("uniquename")]
public string UniqueName
{
get
{
return this.GetAttributeValue<string>("uniquename");
}
set
{
this.OnPropertyChanging("UniqueName");
this.SetAttributeValue("uniquename", (object) value);
this.OnPropertyChanged("UniqueName");
}
}
[AttributeLogicalName("versionnumber")]
public long? VersionNumber
{
get
{
return this.GetAttributeValue<long?>("versionnumber");
}
}
[RelationshipSchemaName("Publisher_PublisherAddress")]
public IEnumerable<PublisherAddress> Publisher_PublisherAddress
{
get
{
return this.GetRelatedEntities<PublisherAddress>("Publisher_PublisherAddress", new EntityRole?());
}
set
{
this.OnPropertyChanging("Publisher_PublisherAddress");
this.SetRelatedEntities<PublisherAddress>("Publisher_PublisherAddress", new EntityRole?(), value);
this.OnPropertyChanged("Publisher_PublisherAddress");
}
}
[RelationshipSchemaName("publisher_solution")]
public IEnumerable<Solution> publisher_solution
{
get
{
return this.GetRelatedEntities<Solution>("publisher_solution", new EntityRole?());
}
set
{
this.OnPropertyChanging("publisher_solution");
this.SetRelatedEntities<Solution>("publisher_solution", new EntityRole?(), value);
this.OnPropertyChanged("publisher_solution");
}
}
[AttributeLogicalName("createdby")]
[RelationshipSchemaName("lk_publisher_createdby")]
public SystemUser lk_publisher_createdby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_publisher_createdby", new EntityRole?());
}
}
[RelationshipSchemaName("lk_publisher_modifiedby")]
[AttributeLogicalName("modifiedby")]
public SystemUser lk_publisher_modifiedby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_publisher_modifiedby", new EntityRole?());
}
}
[RelationshipSchemaName("lk_publisherbase_createdonbehalfby")]
[AttributeLogicalName("createdonbehalfby")]
public SystemUser lk_publisherbase_createdonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_publisherbase_createdonbehalfby", new EntityRole?());
}
}
[RelationshipSchemaName("lk_publisherbase_modifiedonbehalfby")]
[AttributeLogicalName("modifiedonbehalfby")]
public SystemUser lk_publisherbase_modifiedonbehalfby
{
get
{
return this.GetRelatedEntity<SystemUser>("lk_publisherbase_modifiedonbehalfby", new EntityRole?());
}
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
public Publisher()
: base("publisher")
{
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged == null)
return;
this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanging(string propertyName)
{
if (this.PropertyChanging == null)
return;
this.PropertyChanging((object) this, new PropertyChangingEventArgs(propertyName));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.Linq.SqlClient {
internal class SqlDeflator {
SqlValueDeflator vDeflator;
SqlColumnDeflator cDeflator;
SqlAliasDeflator aDeflator;
SqlTopSelectDeflator tsDeflator;
SqlDuplicateColumnDeflator dupColumnDeflator;
internal SqlDeflator() {
this.vDeflator = new SqlValueDeflator();
this.cDeflator = new SqlColumnDeflator();
this.aDeflator = new SqlAliasDeflator();
this.tsDeflator = new SqlTopSelectDeflator();
this.dupColumnDeflator = new SqlDuplicateColumnDeflator();
}
internal SqlNode Deflate(SqlNode node) {
node = this.vDeflator.Visit(node);
node = this.cDeflator.Visit(node);
node = this.aDeflator.Visit(node);
node = this.tsDeflator.Visit(node);
node = this.dupColumnDeflator.Visit(node);
return node;
}
// remove references to literal values
class SqlValueDeflator : SqlVisitor {
SelectionDeflator sDeflator;
bool isTopLevel = true;
internal SqlValueDeflator() {
this.sDeflator = new SelectionDeflator();
}
internal override SqlSelect VisitSelect(SqlSelect select) {
if (this.isTopLevel) {
select.Selection = sDeflator.VisitExpression(select.Selection);
}
return select;
}
internal override SqlExpression VisitSubSelect(SqlSubSelect ss) {
bool saveIsTopLevel = this.isTopLevel;
try {
return base.VisitSubSelect(ss);
}
finally {
this.isTopLevel = saveIsTopLevel;
}
}
class SelectionDeflator : SqlVisitor {
internal override SqlExpression VisitColumnRef(SqlColumnRef cref) {
SqlExpression literal = this.GetLiteralValue(cref);
if (literal != null) {
return literal;
}
return cref;
}
private SqlValue GetLiteralValue(SqlExpression expr) {
while (expr != null && expr.NodeType == SqlNodeType.ColumnRef) {
expr = ((SqlColumnRef)expr).Column.Expression;
}
return expr as SqlValue;
}
}
}
// remove unreferenced items in projection list
class SqlColumnDeflator : SqlVisitor {
Dictionary<SqlNode, SqlNode> referenceMap;
bool isTopLevel;
bool forceReferenceAll;
SqlAggregateChecker aggregateChecker;
internal SqlColumnDeflator() {
this.referenceMap = new Dictionary<SqlNode, SqlNode>();
this.aggregateChecker = new SqlAggregateChecker();
this.isTopLevel = true;
}
internal override SqlExpression VisitColumnRef(SqlColumnRef cref) {
this.referenceMap[cref.Column] = cref.Column;
return cref;
}
internal override SqlExpression VisitScalarSubSelect(SqlSubSelect ss) {
bool saveIsTopLevel = this.isTopLevel;
this.isTopLevel = false;
bool saveForceReferenceAll = this.forceReferenceAll;
this.forceReferenceAll = true;
try {
return base.VisitScalarSubSelect(ss);
}
finally {
this.isTopLevel = saveIsTopLevel;
this.forceReferenceAll = saveForceReferenceAll;
}
}
internal override SqlExpression VisitExists(SqlSubSelect ss) {
bool saveIsTopLevel = this.isTopLevel;
this.isTopLevel = false;
try {
return base.VisitExists(ss);
}
finally {
this.isTopLevel = saveIsTopLevel;
}
}
internal override SqlNode VisitUnion(SqlUnion su) {
bool saveForceReferenceAll = this.forceReferenceAll;
this.forceReferenceAll = true;
su.Left = this.Visit(su.Left);
su.Right = this.Visit(su.Right);
this.forceReferenceAll = saveForceReferenceAll;
return su;
}
internal override SqlSelect VisitSelect(SqlSelect select) {
bool saveForceReferenceAll = this.forceReferenceAll;
this.forceReferenceAll = false;
bool saveIsTopLevel = this.isTopLevel;
try {
if (this.isTopLevel) {
// top-level projection references columns!
select.Selection = this.VisitExpression(select.Selection);
}
this.isTopLevel = false;
for (int i = select.Row.Columns.Count - 1; i >= 0; i--) {
SqlColumn c = select.Row.Columns[i];
bool safeToRemove =
!saveForceReferenceAll
&& !this.referenceMap.ContainsKey(c)
// don't remove anything from a distinct select (except maybe a literal value) since it would change the meaning of the comparison
&& !select.IsDistinct
// don't remove an aggregate expression that may be the only expression that forces the grouping (since it would change the cardinality of the results)
&& !(select.GroupBy.Count == 0 && this.aggregateChecker.HasAggregates(c.Expression));
if (safeToRemove) {
select.Row.Columns.RemoveAt(i);
}
else {
this.VisitExpression(c.Expression);
}
}
select.Top = this.VisitExpression(select.Top);
for (int i = select.OrderBy.Count - 1; i >= 0; i--) {
select.OrderBy[i].Expression = this.VisitExpression(select.OrderBy[i].Expression);
}
select.Having = this.VisitExpression(select.Having);
for (int i = select.GroupBy.Count - 1; i >= 0; i--) {
select.GroupBy[i] = this.VisitExpression(select.GroupBy[i]);
}
select.Where = this.VisitExpression(select.Where);
select.From = this.VisitSource(select.From);
}
finally {
this.isTopLevel = saveIsTopLevel;
this.forceReferenceAll = saveForceReferenceAll;
}
return select;
}
internal override SqlSource VisitJoin(SqlJoin join) {
join.Condition = this.VisitExpression(join.Condition);
join.Right = this.VisitSource(join.Right);
join.Left = this.VisitSource(join.Left);
return join;
}
internal override SqlNode VisitLink(SqlLink link) {
// don't visit expansion...
for (int i = 0, n = link.KeyExpressions.Count; i < n; i++) {
link.KeyExpressions[i] = this.VisitExpression(link.KeyExpressions[i]);
}
return link;
}
}
class SqlColumnEqualizer : SqlVisitor {
Dictionary<SqlColumn, SqlColumn> map;
internal SqlColumnEqualizer() {
}
internal void BuildEqivalenceMap(SqlSource scope) {
this.map = new Dictionary<SqlColumn, SqlColumn>();
this.Visit(scope);
}
internal bool AreEquivalent(SqlExpression e1, SqlExpression e2) {
if (SqlComparer.AreEqual(e1, e2))
return true;
SqlColumnRef cr1 = e1 as SqlColumnRef;
SqlColumnRef cr2 = e2 as SqlColumnRef;
if (cr1 != null && cr2 != null) {
SqlColumn c1 = cr1.GetRootColumn();
SqlColumn c2 = cr2.GetRootColumn();
SqlColumn r;
return this.map.TryGetValue(c1, out r) && r == c2;
}
return false;
}
internal override SqlSource VisitJoin(SqlJoin join) {
base.VisitJoin(join);
if (join.Condition != null) {
this.CheckJoinCondition(join.Condition);
}
return join;
}
internal override SqlSelect VisitSelect(SqlSelect select) {
base.VisitSelect(select);
if (select.Where != null) {
this.CheckJoinCondition(select.Where);
}
return select;
}
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification="[....]: Cast is dependent on node type and casts do not happen unecessarily in a single code path.")]
private void CheckJoinCondition(SqlExpression expr) {
switch (expr.NodeType) {
case SqlNodeType.And: {
SqlBinary b = (SqlBinary)expr;
CheckJoinCondition(b.Left);
CheckJoinCondition(b.Right);
break;
}
case SqlNodeType.EQ:
case SqlNodeType.EQ2V: {
SqlBinary b = (SqlBinary)expr;
SqlColumnRef crLeft = b.Left as SqlColumnRef;
SqlColumnRef crRight = b.Right as SqlColumnRef;
if (crLeft != null && crRight != null) {
SqlColumn cLeft = crLeft.GetRootColumn();
SqlColumn cRight = crRight.GetRootColumn();
this.map[cLeft] = cRight;
this.map[cRight] = cLeft;
}
break;
}
}
}
internal override SqlExpression VisitSubSelect(SqlSubSelect ss) {
return ss;
}
}
// remove redundant/trivial aliases
class SqlAliasDeflator : SqlVisitor {
Dictionary<SqlAlias, SqlAlias> removedMap;
internal SqlAliasDeflator() {
this.removedMap = new Dictionary<SqlAlias, SqlAlias>();
}
internal override SqlExpression VisitAliasRef(SqlAliasRef aref) {
SqlAlias alias = aref.Alias;
SqlAlias value;
if (this.removedMap.TryGetValue(alias, out value)) {
throw Error.InvalidReferenceToRemovedAliasDuringDeflation();
}
return aref;
}
internal override SqlExpression VisitColumnRef(SqlColumnRef cref) {
if (cref.Column.Alias != null && this.removedMap.ContainsKey(cref.Column.Alias)) {
SqlColumnRef c = cref.Column.Expression as SqlColumnRef;
if (c != null) {
//The following code checks for cases where there are differences between the type returned
//by a ColumnRef and the column that refers to it. This situation can occur when conversions
//are optimized out of the SQL node tree. As mentioned in the SetClrType comments this is not
//an operation that can have adverse effects and should only be used in limited cases, such as
//this one.
if (c.ClrType != cref.ClrType) {
c.SetClrType(cref.ClrType);
return this.VisitColumnRef(c);
}
}
return c;
}
return cref;
}
internal override SqlSource VisitSource(SqlSource node) {
node = (SqlSource)this.Visit(node);
SqlAlias alias = node as SqlAlias;
if (alias != null) {
SqlSelect sel = alias.Node as SqlSelect;
if (sel != null && this.IsTrivialSelect(sel)) {
this.removedMap[alias] = alias;
node = sel.From;
}
}
return node;
}
internal override SqlSource VisitJoin(SqlJoin join) {
base.VisitJoin(join);
switch (join.JoinType) {
case SqlJoinType.Cross:
case SqlJoinType.Inner:
// reducing either side would effect cardinality of results
break;
case SqlJoinType.LeftOuter:
case SqlJoinType.CrossApply:
case SqlJoinType.OuterApply:
// may reduce to left if no references to the right
if (this.HasEmptySource(join.Right)) {
SqlAlias a = (SqlAlias)join.Right;
this.removedMap[a] = a;
return join.Left;
}
break;
}
return join;
}
private bool IsTrivialSelect(SqlSelect select) {
if (select.OrderBy.Count != 0 ||
select.GroupBy.Count != 0 ||
select.Having != null ||
select.Top != null ||
select.IsDistinct ||
select.Where != null)
return false;
return this.HasTrivialSource(select.From) && this.HasTrivialProjection(select);
}
private bool HasTrivialSource(SqlSource node) {
SqlJoin join = node as SqlJoin;
if (join != null) {
return this.HasTrivialSource(join.Left) &&
this.HasTrivialSource(join.Right);
}
return node is SqlAlias;
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
private bool HasTrivialProjection(SqlSelect select) {
foreach (SqlColumn c in select.Row.Columns) {
if (c.Expression != null && c.Expression.NodeType != SqlNodeType.ColumnRef) {
return false;
}
}
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
private bool HasEmptySource(SqlSource node) {
SqlAlias alias = node as SqlAlias;
if (alias == null) return false;
SqlSelect sel = alias.Node as SqlSelect;
if (sel == null) return false;
return sel.Row.Columns.Count == 0 &&
sel.From == null &&
sel.Where == null &&
sel.GroupBy.Count == 0 &&
sel.Having == null &&
sel.OrderBy.Count == 0;
}
}
// remove duplicate columns from order by and group by lists
class SqlDuplicateColumnDeflator : SqlVisitor
{
SqlColumnEqualizer equalizer = new SqlColumnEqualizer();
internal override SqlSelect VisitSelect(SqlSelect select) {
select.From = this.VisitSource(select.From);
select.Where = this.VisitExpression(select.Where);
for (int i = 0, n = select.GroupBy.Count; i < n; i++)
{
select.GroupBy[i] = this.VisitExpression(select.GroupBy[i]);
}
// remove duplicate group expressions
for (int i = select.GroupBy.Count - 1; i >= 0; i--)
{
for (int j = i - 1; j >= 0; j--)
{
if (SqlComparer.AreEqual(select.GroupBy[i], select.GroupBy[j]))
{
select.GroupBy.RemoveAt(i);
break;
}
}
}
select.Having = this.VisitExpression(select.Having);
for (int i = 0, n = select.OrderBy.Count; i < n; i++)
{
select.OrderBy[i].Expression = this.VisitExpression(select.OrderBy[i].Expression);
}
// remove duplicate order expressions
if (select.OrderBy.Count > 0)
{
this.equalizer.BuildEqivalenceMap(select.From);
for (int i = select.OrderBy.Count - 1; i >= 0; i--)
{
for (int j = i - 1; j >= 0; j--)
{
if (this.equalizer.AreEquivalent(select.OrderBy[i].Expression, select.OrderBy[j].Expression))
{
select.OrderBy.RemoveAt(i);
break;
}
}
}
}
select.Top = this.VisitExpression(select.Top);
select.Row = (SqlRow)this.Visit(select.Row);
select.Selection = this.VisitExpression(select.Selection);
return select;
}
}
// if the top level select is simply a reprojection of the subquery, then remove it,
// pushing any distinct names down
class SqlTopSelectDeflator : SqlVisitor {
internal override SqlSelect VisitSelect(SqlSelect select) {
if (IsTrivialSelect(select)) {
SqlSelect aselect = (SqlSelect)((SqlAlias)select.From).Node;
// build up a column map, so we can rewrite the top-level selection expression
Dictionary<SqlColumn, SqlColumnRef> map = new Dictionary<SqlColumn, SqlColumnRef>();
foreach (SqlColumn c in select.Row.Columns) {
SqlColumnRef cref = (SqlColumnRef)c.Expression;
map.Add(c, cref);
// push the interesting column names down (non null)
if (!string.IsNullOrEmpty(c.Name)) {
cref.Column.Name = c.Name;
}
}
aselect.Selection = new ColumnMapper(map).VisitExpression(select.Selection);
return aselect;
}
return select;
}
private bool IsTrivialSelect(SqlSelect select) {
if (select.OrderBy.Count != 0 ||
select.GroupBy.Count != 0 ||
select.Having != null ||
select.Top != null ||
select.IsDistinct ||
select.Where != null)
return false;
return this.HasTrivialSource(select.From) && this.HasTrivialProjection(select);
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
private bool HasTrivialSource(SqlSource node) {
SqlAlias alias = node as SqlAlias;
if (alias == null) return false;
return alias.Node is SqlSelect;
}
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")]
private bool HasTrivialProjection(SqlSelect select) {
foreach (SqlColumn c in select.Row.Columns) {
if (c.Expression != null && c.Expression.NodeType != SqlNodeType.ColumnRef) {
return false;
}
}
return true;
}
class ColumnMapper : SqlVisitor {
Dictionary<SqlColumn, SqlColumnRef> map;
internal ColumnMapper(Dictionary<SqlColumn, SqlColumnRef> map) {
this.map = map;
}
internal override SqlExpression VisitColumnRef(SqlColumnRef cref) {
SqlColumnRef mapped;
if (this.map.TryGetValue(cref.Column, out mapped)) {
return mapped;
}
return cref;
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BytesRef = Lucene.Net.Util.BytesRef;
using FieldInvertState = Lucene.Net.Index.FieldInvertState;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using SmallSingle = Lucene.Net.Util.SmallSingle;
namespace Lucene.Net.Search.Similarities
{
/*
* 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 subclass of <see cref="Similarity"/> that provides a simplified API for its
/// descendants. Subclasses are only required to implement the <see cref="Score(BasicStats, float, float)"/>
/// and <see cref="ToString()"/> methods. Implementing
/// <see cref="Explain(Explanation, BasicStats, int, float, float)"/> is optional,
/// inasmuch as <see cref="SimilarityBase"/> already provides a basic explanation of the score
/// and the term frequency. However, implementers of a subclass are encouraged to
/// include as much detail about the scoring method as possible.
/// <para/>
/// Note: multi-word queries such as phrase queries are scored in a different way
/// than Lucene's default ranking algorithm: whereas it "fakes" an IDF value for
/// the phrase as a whole (since it does not know it), this class instead scores
/// phrases as a summation of the individual term scores.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class SimilarityBase : Similarity
{
/// <summary>
/// For <see cref="Log2(double)"/>. Precomputed for efficiency reasons. </summary>
private static readonly double LOG_2 = Math.Log(2);
/// <summary>
/// True if overlap tokens (tokens with a position of increment of zero) are
/// discounted from the document's length.
/// </summary>
private bool discountOverlaps = true; // LUCENENET Specific: made private, since it can be get/set through property
/// <summary>
/// Sole constructor. (For invocation by subclass
/// constructors, typically implicit.)
/// </summary>
public SimilarityBase()
{
}
/// <summary>
/// Determines whether overlap tokens (Tokens with
/// 0 position increment) are ignored when computing
/// norm. By default this is <c>true</c>, meaning overlap
/// tokens do not count when computing norms.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <seealso cref="ComputeNorm(FieldInvertState)"/>
public virtual bool DiscountOverlaps
{
get => discountOverlaps;
set => discountOverlaps = value;
}
public override sealed SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats)
{
BasicStats[] stats = new BasicStats[termStats.Length];
for (int i = 0; i < termStats.Length; i++)
{
stats[i] = NewStats(collectionStats.Field, queryBoost);
FillBasicStats(stats[i], collectionStats, termStats[i]);
}
return stats.Length == 1 ? stats[0] : new MultiSimilarity.MultiStats(stats) as SimWeight;
}
/// <summary>
/// Factory method to return a custom stats object </summary>
protected internal virtual BasicStats NewStats(string field, float queryBoost)
{
return new BasicStats(field, queryBoost);
}
/// <summary>
/// Fills all member fields defined in <see cref="BasicStats"/> in <paramref name="stats"/>.
/// Subclasses can override this method to fill additional stats.
/// </summary>
protected internal virtual void FillBasicStats(BasicStats stats, CollectionStatistics collectionStats, TermStatistics termStats)
{
// #positions(field) must be >= #positions(term)
Debug.Assert(collectionStats.SumTotalTermFreq == -1 || collectionStats.SumTotalTermFreq >= termStats.TotalTermFreq);
long numberOfDocuments = collectionStats.MaxDoc;
long docFreq = termStats.DocFreq;
long totalTermFreq = termStats.TotalTermFreq;
// codec does not supply totalTermFreq: substitute docFreq
if (totalTermFreq == -1)
{
totalTermFreq = docFreq;
}
long numberOfFieldTokens;
float avgFieldLength;
long sumTotalTermFreq = collectionStats.SumTotalTermFreq;
if (sumTotalTermFreq <= 0)
{
// field does not exist;
// We have to provide something if codec doesnt supply these measures,
// or if someone omitted frequencies for the field... negative values cause
// NaN/Inf for some scorers.
numberOfFieldTokens = docFreq;
avgFieldLength = 1;
}
else
{
numberOfFieldTokens = sumTotalTermFreq;
avgFieldLength = (float)numberOfFieldTokens / numberOfDocuments;
}
// TODO: add sumDocFreq for field (numberOfFieldPostings)
stats.NumberOfDocuments = numberOfDocuments;
stats.NumberOfFieldTokens = numberOfFieldTokens;
stats.AvgFieldLength = avgFieldLength;
stats.DocFreq = docFreq;
stats.TotalTermFreq = totalTermFreq;
}
/// <summary>
/// Scores the document <c>doc</c>.
/// <para>Subclasses must apply their scoring formula in this class.</para> </summary>
/// <param name="stats"> the corpus level statistics. </param>
/// <param name="freq"> the term frequency. </param>
/// <param name="docLen"> the document length. </param>
/// <returns> the score. </returns>
public abstract float Score(BasicStats stats, float freq, float docLen);
/// <summary>
/// Subclasses should implement this method to explain the score. <paramref name="expl"/>
/// already contains the score, the name of the class and the doc id, as well
/// as the term frequency and its explanation; subclasses can add additional
/// clauses to explain details of their scoring formulae.
/// <para>The default implementation does nothing.</para>
/// </summary>
/// <param name="expl"> the explanation to extend with details. </param>
/// <param name="stats"> the corpus level statistics. </param>
/// <param name="doc"> the document id. </param>
/// <param name="freq"> the term frequency. </param>
/// <param name="docLen"> the document length. </param>
protected internal virtual void Explain(Explanation expl, BasicStats stats, int doc, float freq, float docLen)
{
}
/// <summary>
/// Explains the score. The implementation here provides a basic explanation
/// in the format <em>Score(name-of-similarity, doc=doc-id,
/// freq=term-frequency), computed from:</em>, and
/// attaches the score (computed via the <see cref="Score(BasicStats, float, float)"/>
/// method) and the explanation for the term frequency. Subclasses content with
/// this format may add additional details in
/// <see cref="Explain(Explanation, BasicStats, int, float, float)"/>.
/// </summary>
/// <param name="stats"> the corpus level statistics. </param>
/// <param name="doc"> the document id. </param>
/// <param name="freq"> the term frequency and its explanation. </param>
/// <param name="docLen"> the document length. </param>
/// <returns> the explanation. </returns>
public virtual Explanation Explain(BasicStats stats, int doc, Explanation freq, float docLen)
{
Explanation result = new Explanation();
result.Value = Score(stats, freq.Value, docLen);
result.Description = "score(" + this.GetType().Name + ", doc=" + doc + ", freq=" + freq.Value + "), computed from:";
result.AddDetail(freq);
Explain(result, stats, doc, freq.Value, docLen);
return result;
}
public override SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context)
{
if (stats is MultiSimilarity.MultiStats)
{
// a multi term query (e.g. phrase). return the summation,
// scoring almost as if it were boolean query
SimWeight[] subStats = ((MultiSimilarity.MultiStats)stats).subStats;
SimScorer[] subScorers = new SimScorer[subStats.Length];
for (int i = 0; i < subScorers.Length; i++)
{
BasicStats basicstats = (BasicStats)subStats[i];
subScorers[i] = new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field));
}
return new MultiSimilarity.MultiSimScorer(subScorers);
}
else
{
BasicStats basicstats = (BasicStats)stats;
return new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field));
}
}
/// <summary>
/// Subclasses must override this method to return the name of the <see cref="Similarity"/>
/// and preferably the values of parameters (if any) as well.
/// </summary>
public override abstract string ToString();
// ------------------------------ Norm handling ------------------------------
/// <summary>
/// Norm -> document length map. </summary>
private static readonly float[] NORM_TABLE = LoadNormTable();
private static float[] LoadNormTable() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
float[] normTable = new float[256];
for (int i = 0; i < 256; i++)
{
float floatNorm = SmallSingle.SByte315ToSingle((sbyte)i);
normTable[i] = 1.0f / (floatNorm * floatNorm);
}
return normTable;
}
/// <summary>
/// Encodes the document length in the same way as <see cref="TFIDFSimilarity"/>. </summary>
public override long ComputeNorm(FieldInvertState state)
{
float numTerms;
if (discountOverlaps)
{
numTerms = state.Length - state.NumOverlap;
}
else
{
numTerms = state.Length;
}
return EncodeNormValue(state.Boost, numTerms);
}
/// <summary>
/// Decodes a normalization factor (document length) stored in an index. </summary>
/// <see cref="EncodeNormValue(float,float)"/>
protected internal virtual float DecodeNormValue(byte norm)
{
return NORM_TABLE[norm & 0xFF]; // & 0xFF maps negative bytes to positive above 127
}
/// <summary>
/// Encodes the length to a byte via <see cref="SmallSingle"/>. </summary>
protected internal virtual byte EncodeNormValue(float boost, float length)
{
return SmallSingle.SingleToByte315((boost / (float)Math.Sqrt(length)));
}
// ----------------------------- Static methods ------------------------------
/// <summary>
/// Returns the base two logarithm of <c>x</c>. </summary>
public static double Log2(double x)
{
// Put this to a 'util' class if we need more of these.
return Math.Log(x) / LOG_2;
}
// --------------------------------- Classes ---------------------------------
/// <summary>
/// Delegates the <see cref="Score(int, float)"/> and
/// <see cref="Explain(int, Explanation)"/> methods to
/// <see cref="SimilarityBase.Score(BasicStats, float, float)"/> and
/// <see cref="SimilarityBase.Explain(BasicStats, int, Explanation, float)"/>,
/// respectively.
/// </summary>
private class BasicSimScorer : SimScorer
{
private readonly SimilarityBase outerInstance;
private readonly BasicStats stats;
private readonly NumericDocValues norms;
internal BasicSimScorer(SimilarityBase outerInstance, BasicStats stats, NumericDocValues norms)
{
this.outerInstance = outerInstance;
this.stats = stats;
this.norms = norms;
}
public override float Score(int doc, float freq)
{
// We have to supply something in case norms are omitted
return outerInstance.Score(stats, freq, norms == null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc)));
}
public override Explanation Explain(int doc, Explanation freq)
{
return outerInstance.Explain(stats, doc, freq, norms == null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc)));
}
public override float ComputeSlopFactor(int distance)
{
return 1.0f / (distance + 1);
}
public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload)
{
return 1f;
}
}
}
}
| |
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// MIT, Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Adaptation for high precision colors has been sponsored by
// Liberty Technology Systems, Inc., visit http://lib-sys.com
//
// Liberty Technology Systems, Inc. is the provider of
// PostScript and PDF technology for software developers.
//
//----------------------------------------------------------------------------
using System;
using PixelFarm.Drawing;
using PixelFarm.CpuBlit.Imaging;
using subpix_const = PixelFarm.CpuBlit.Imaging.ImageFilterLookUpTable.ImgSubPixConst;
using filter_const = PixelFarm.CpuBlit.Imaging.ImageFilterLookUpTable.ImgFilterConst;
using CO = PixelFarm.Drawing.Internal.CO;
namespace PixelFarm.CpuBlit.FragmentProcessing
{
public static class ISpanInterpolatorExtensions
{
public static void TranslateBeginCoord(this ISpanInterpolator interpolator,
double inX, double inY,
out int outX, out int outY,
int shift)
{
interpolator.Begin(inX, inY, 1);
interpolator.GetCoord(out int x_hr, out int y_hr);
//get translate version
outX = x_hr >> shift;
outY = y_hr >> shift;
}
public static void SubPixTranslateBeginCoord(this ISpanInterpolator interpolator,
double inX, double inY,
out int outX, out int outY)
{
interpolator.Begin(inX, inY, 1);
interpolator.GetCoord(out int x_hr, out int y_hr);
//get translate version
outX = x_hr >> subpix_const.SHIFT;
outY = y_hr >> subpix_const.SHIFT;
}
public static void SubPixGetTranslatedCoord(this ISpanInterpolator interpolator, out int outX, out int outY)
{
interpolator.GetCoord(out int x_hr, out int y_hr);
outX = x_hr >> subpix_const.SHIFT;
outY = y_hr >> subpix_const.SHIFT;
}
}
// it should be easy to write a 90 rotating or mirroring filter too. LBB 2012/01/14
/// <summary>
/// Nearest Neighbor,StepXBy1
/// </summary>
class ImgSpanGenRGBA_NN_StepXBy1 : ImgSpanGen
{
//NN: nearest neighbor
public ImgSpanGenRGBA_NN_StepXBy1()
{
}
public sealed override void GenerateColors(Drawing.Color[] outputColors, int startIndex, int x, int y, int len)
{
//ISpanInterpolator spanInterpolator = Interpolator;
//spanInterpolator.Begin(x + dx, y + dy, len);
//spanInterpolator.GetCoord(out int x_hr, out int y_hr);
//int x_lr = x_hr >> subpix_const.SHIFT;
//int y_lr = y_hr >> subpix_const.SHIFT;
Interpolator.SubPixTranslateBeginCoord(x + dx, y + dy, out int x_lr, out int y_lr);
ImgSpanGenRGBA_NN.NN_StepXBy1(_bmpSrc, _bmpSrc.GetBufferOffsetXY32(x_lr, y_lr), outputColors, startIndex, len);
}
}
//==============================================span_image_filter_rgba_nn
/// <summary>
/// Nearest Neighbor
/// </summary>
public class ImgSpanGenRGBA_NN : ImgSpanGen
{
bool _noTransformation = false;
public override void Prepare()
{
base.Prepare();
_noTransformation = (base.Interpolator is SpanInterpolatorLinear spanInterpolatorLinear &&
spanInterpolatorLinear.Transformer is VertexProcessing.Affine aff &&
aff.IsIdentity);
}
internal unsafe static void NN_StepXBy1(IBitmapSrc bmpsrc, int srcIndex, Drawing.Color[] outputColors, int dstIndex, int len)
{
using (CpuBlit.TempMemPtr srcBufferPtr = bmpsrc.GetBufferPtr())
{
int* pSource = (int*)srcBufferPtr.Ptr + srcIndex;
do
{
int srcColor = *pSource;
//separate each component
//TODO: review here, color from source buffer
//should be in 'pre-multiplied' format.
//so it should be converted to 'straight' color by call something like ..'FromPreMult()'
outputColors[dstIndex++] = Drawing.Color.FromArgb(
(srcColor >> CO.A_SHIFT) & 0xff, //a
(srcColor >> CO.R_SHIFT) & 0xff, //r
(srcColor >> CO.G_SHIFT) & 0xff, //g
(srcColor >> CO.B_SHIFT) & 0xff);//b
pSource++;//move next
} while (--len != 0);
}
}
public override void GenerateColors(Drawing.Color[] outputColors, int startIndex, int x, int y, int len)
{
if (_noTransformation)
{
//Interpolator.GetCoord(out int x_hr, out int y_hr);
//int x_lr = x_hr >> subpix_const.SHIFT;
//int y_lr = y_hr >> subpix_const.SHIFT;
Interpolator.SubPixTranslateBeginCoord(x + dx, y + dy, out int x_lr, out int y_lr);
NN_StepXBy1(_bmpSrc, _bmpSrc.GetBufferOffsetXY32(x_lr, y_lr), outputColors, startIndex, len);
}
else
{
ISpanInterpolator spanInterpolator = Interpolator;
spanInterpolator.Begin(x + dx, y + dy, len);
unsafe
{
using ( TempMemPtr.FromBmp(_bmpSrc, out int* srcBuffer))
{
//TODO: if no any transformation,=> skip spanInterpolator (see above example)
do
{
//spanInterpolator.GetCoord(out int x_hr, out int y_hr);
//int x_lr = x_hr >> subpix_const.SHIFT;
//int y_lr = y_hr >> subpix_const.SHIFT;
spanInterpolator.SubPixGetTranslatedCoord(out int x_lr, out int y_lr);
int bufferIndex = _bmpSrc.GetBufferOffsetXY32(x_lr, y_lr);
int srcColor = srcBuffer[bufferIndex++];
outputColors[startIndex] = Drawing.Color.FromArgb(
(srcColor >> CO.A_SHIFT) & 0xff, //a
(srcColor >> CO.R_SHIFT) & 0xff, //r
(srcColor >> CO.G_SHIFT) & 0xff, //g
(srcColor >> CO.B_SHIFT) & 0xff);//b
++startIndex;
spanInterpolator.Next();
} while (--len != 0);
}
}
}
}
}
class ImgSpanGenRGBA_BilinearClip : ImgSpanGen
{
bool _noTransformation = false;
public ImgSpanGenRGBA_BilinearClip(Drawing.Color back_color)
{
BackgroundColor = back_color;
}
public override void Prepare()
{
base.Prepare();
_noTransformation = (base.Interpolator is SpanInterpolatorLinear spanInterpolatorLinear &&
spanInterpolatorLinear.Transformer is VertexProcessing.Affine aff &&
aff.IsIdentity);
}
public sealed override void GenerateColors(Drawing.Color[] outputColors, int startIndex, int x, int y, int len)
{
#if DEBUG
int tmp_len = len;
#endif
unsafe
{
//TODO: review here
if (_noTransformation)
{
using (CpuBlit.TempMemPtr.FromBmp(_bmpSrc, out int* srcBuffer))
{
int bufferIndex = _bmpSrc.GetBufferOffsetXY32(x, y);
do
{
//TODO: review here, match component?
//ORDER IS IMPORTANT!
//TODO : use CO (color order instead)
int srcColor = srcBuffer[bufferIndex++];
outputColors[startIndex] = Drawing.Color.FromArgb(
(srcColor >> CO.A_SHIFT) & 0xff, //a
(srcColor >> CO.R_SHIFT) & 0xff, //r
(srcColor >> CO.G_SHIFT) & 0xff, //g
(srcColor >> CO.B_SHIFT) & 0xff);//b
++startIndex;
} while (--len != 0);
}
}
else
{
//Bilinear interpolation, without lookup table
ISpanInterpolator spanInterpolator = base.Interpolator;
using (CpuBlit.TempMemPtr srcBufferPtr = _bmpSrc.GetBufferPtr())
{
int* srcBuffer = (int*)srcBufferPtr.Ptr;
spanInterpolator.Begin(x + base.dx, y + base.dy, len);
//accumulated color component
int acc_r, acc_g, acc_b, acc_a;
Color bgColor = this.BackgroundColor;
int back_r = bgColor.R;
int back_g = bgColor.G;
int back_b = bgColor.B;
int back_a = bgColor.A;
int maxx = _bmpSrc.Width - 1;
int maxy = _bmpSrc.Height - 1;
int srcColor = 0;
do
{
int x_hr;
int y_hr;
spanInterpolator.GetCoord(out x_hr, out y_hr);
x_hr -= base.dxInt;
y_hr -= base.dyInt;
int x_lr = x_hr >> subpix_const.SHIFT;
int y_lr = y_hr >> subpix_const.SHIFT;
int weight;
if (x_lr >= 0 && y_lr >= 0 &&
x_lr < maxx && y_lr < maxy)
{
int bufferIndex = _bmpSrc.GetBufferOffsetXY32(x_lr, y_lr);
//accumulated color components
acc_r =
acc_g =
acc_b =
acc_a = subpix_const.SCALE * subpix_const.SCALE / 2;
x_hr &= subpix_const.MASK;
y_hr &= subpix_const.MASK;
weight = (subpix_const.SCALE - x_hr) * (subpix_const.SCALE - y_hr);
if (weight > BASE_MASK)
{
srcColor = srcBuffer[bufferIndex];
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
weight = (x_hr * (subpix_const.SCALE - y_hr));
if (weight > BASE_MASK)
{
bufferIndex++;
srcColor = srcBuffer[bufferIndex];
//
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
weight = ((subpix_const.SCALE - x_hr) * y_hr);
if (weight > BASE_MASK)
{
++y_lr;
//
bufferIndex = _bmpSrc.GetBufferOffsetXY32(x_lr, y_lr);
srcColor = srcBuffer[bufferIndex];
//
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
weight = (x_hr * y_hr);
if (weight > BASE_MASK)
{
bufferIndex++;
srcColor = srcBuffer[bufferIndex];
//
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
acc_r >>= subpix_const.SHIFT * 2;
acc_g >>= subpix_const.SHIFT * 2;
acc_b >>= subpix_const.SHIFT * 2;
acc_a >>= subpix_const.SHIFT * 2;
}
else
{
if (x_lr < -1 || y_lr < -1 ||
x_lr > maxx || y_lr > maxy)
{
acc_r = back_r;
acc_g = back_g;
acc_b = back_b;
acc_a = back_a;
}
else
{
acc_r =
acc_g =
acc_b =
acc_a = subpix_const.SCALE * subpix_const.SCALE / 2;
x_hr &= subpix_const.MASK;
y_hr &= subpix_const.MASK;
weight = (subpix_const.SCALE - x_hr) * (subpix_const.SCALE - y_hr);
if (weight > BASE_MASK)
{
if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy)
{
srcColor = srcBuffer[_bmpSrc.GetBufferOffsetXY32(x_lr, y_lr)];
//
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
else
{
acc_r += back_r * weight;
acc_g += back_g * weight;
acc_b += back_b * weight;
acc_a += back_a * weight;
}
}
x_lr++;
weight = x_hr * (subpix_const.SCALE - y_hr);
if (weight > BASE_MASK)
{
if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy)
{
srcColor = srcBuffer[_bmpSrc.GetBufferOffsetXY32(x_lr, y_lr)];
//
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
else
{
acc_r += back_r * weight;
acc_g += back_g * weight;
acc_b += back_b * weight;
acc_a += back_a * weight;
}
}
x_lr--;
y_lr++;
weight = (subpix_const.SCALE - x_hr) * y_hr;
if (weight > BASE_MASK)
{
if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy)
{
srcColor = srcBuffer[_bmpSrc.GetBufferOffsetXY32(x_lr, y_lr)];
//
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
else
{
acc_r += back_r * weight;
acc_g += back_g * weight;
acc_b += back_b * weight;
acc_a += back_a * weight;
}
}
x_lr++;
weight = (x_hr * y_hr);
if (weight > BASE_MASK)
{
if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy)
{
srcColor = srcBuffer[_bmpSrc.GetBufferOffsetXY32(x_lr, y_lr)];
//
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
}
else
{
acc_r += back_r * weight;
acc_g += back_g * weight;
acc_b += back_b * weight;
acc_a += back_a * weight;
}
}
acc_r >>= subpix_const.SHIFT * 2;
acc_g >>= subpix_const.SHIFT * 2;
acc_b >>= subpix_const.SHIFT * 2;
acc_a >>= subpix_const.SHIFT * 2;
}
}
#if DEBUG
if (startIndex >= outputColors.Length)
{
}
#endif
outputColors[startIndex] = PixelFarm.Drawing.Color.FromArgb(
(byte)acc_a,
(byte)acc_r,
(byte)acc_g,
(byte)acc_b
);
++startIndex;
spanInterpolator.Next();
} while (--len != 0);
}//using
}//else
}//unsafe
}
}
public class ImgSpanGenRGBA_CustomFilter : ImgSpanGen
{
//from Agg
//span_image_filter_rgba
ImageFilterLookUpTable _lut;
public ImgSpanGenRGBA_CustomFilter()
{
}
public void SetLookupTable(ImageFilterLookUpTable lut)
{
_lut = lut;
}
public override void GenerateColors(Color[] outputColors, int startIndex, int x, int y, int len)
{
ISpanInterpolator spanInterpolator = this.Interpolator;
int acc_r, acc_g, acc_b, acc_a;
int diameter = _lut.Diameter;
int start = _lut.Start;
int[] weight_array = _lut.WeightArray;
int x_count;
int weight_y;
unsafe
{
using (CpuBlit.TempMemPtr srcBufferPtr = _bmpSrc.GetBufferPtr())
{
int* srcBuffer = (int*)srcBufferPtr.Ptr;
spanInterpolator.Begin(x + base.dx, y + base.dy, len);
do
{
spanInterpolator.GetCoord(out x, out y);
x -= base.dxInt;
y -= base.dyInt;
int x_hr = x;
int y_hr = y;
int x_lr = x_hr >> subpix_const.SHIFT;
int y_lr = y_hr >> subpix_const.SHIFT;
//accumualted color components
acc_r =
acc_g =
acc_b =
acc_a = filter_const.SCALE / 2;
int x_fract = x_hr & subpix_const.MASK;
int y_count = diameter;
y_hr = subpix_const.MASK - (y_hr & subpix_const.MASK);
int bufferIndex = _bmpSrc.GetBufferOffsetXY32(x_lr, y_lr);
int tmp_Y = y_lr;
for (; ; )
{
x_count = diameter;
weight_y = weight_array[y_hr];
x_hr = subpix_const.MASK - x_fract;
//-------------------
for (; ; )
{
int weight = (weight_y * weight_array[x_hr] +
filter_const.SCALE / 2) >>
filter_const.SHIFT;
int srcColor = srcBuffer[bufferIndex];
acc_a += weight * ((srcColor >> CO.A_SHIFT) & 0xff); //a
acc_r += weight * ((srcColor >> CO.R_SHIFT) & 0xff); //r
acc_g += weight * ((srcColor >> CO.G_SHIFT) & 0xff); //g
acc_b += weight * ((srcColor >> CO.B_SHIFT) & 0xff); //b
if (--x_count == 0) break; //for
x_hr += subpix_const.SCALE;
bufferIndex++;
}
//-------------------
if (--y_count == 0) break;
y_hr += subpix_const.SCALE;
tmp_Y++; //move down to next row-> and find start bufferIndex
bufferIndex = _bmpSrc.GetBufferOffsetXY32(x_lr, tmp_Y);
}
acc_r >>= filter_const.SHIFT;
acc_g >>= filter_const.SHIFT;
acc_b >>= filter_const.SHIFT;
acc_a >>= filter_const.SHIFT;
unchecked
{
if ((uint)acc_r > BASE_MASK)
{
if (acc_r < 0) acc_r = 0;
if (acc_r > BASE_MASK) acc_r = BASE_MASK;
}
if ((uint)acc_g > BASE_MASK)
{
if (acc_g < 0) acc_g = 0;
if (acc_g > BASE_MASK) acc_g = BASE_MASK;
}
if ((uint)acc_b > BASE_MASK)
{
if (acc_b < 0) acc_b = 0;
if (acc_b > BASE_MASK) acc_b = BASE_MASK;
}
if ((uint)acc_a > BASE_MASK)
{
if (acc_a < 0) acc_a = 0;
if (acc_a > BASE_MASK) acc_a = BASE_MASK;
}
}
outputColors[startIndex] = PixelFarm.Drawing.Color.FromArgb(
(byte)acc_a, //a
(byte)acc_r,
(byte)acc_g,
(byte)acc_b);
startIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
}
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* E-mail: [email protected]
* WWW: http://www.logicmoo.com
* Copyright (C): 2010-2012 LogicMOO Developement
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*********************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using SbsSW.SwiPlCs;
namespace Swicli.Library
{
public partial class PrologCLR
{
static public IDictionary<TKey, TValue> CreatePrologBackedDictionary<TKey, TValue>(PlTerm pred)
{
string p = PredicateName(pred);
return new PrologBackedDictionary<TKey, TValue>(
PredicateModule(pred), p + "_get",
CreatePrologBackedCollection<TKey>(pred),
p + "_set", p + "_remove", p + "_clear");
}
static public ICollection<T> CreatePrologBackedCollection<T>(PlTerm pred)
{
string p = PredicateName(pred);
return new PrologBackedCollection<T>(
PredicateModule(pred), p + "_get",
p + "_add", p + "_remove", p + "_clear");
}
[PrologVisible]
static public bool cliTestPbd(PlTerm pred, PlTerm counted)
{
var id = CreatePrologBackedDictionary<string, object>(pred);
string s = String.Empty;
var enumer = id.GetEnumerator();
while (enumer.MoveNext())
{
var o = enumer.Current;
s += String.Format("{0}={1},", o.Key, o.Value);
}
counted.UnifyAtom(s);
return true;
}
[PrologVisible]
static public bool cliTestPbdt(PlTerm pred, PlTerm counted)
{
var id = CreatePrologBackedDictionary<string, object>(pred);
string s = String.Empty;
AutoResetEvent are = new AutoResetEvent(false);
(new Thread(() =>
{
var enumer = id.GetEnumerator();
while (enumer.MoveNext())
{
var o = enumer.Current;
s += String.Format("{0}={1},", o.Key, o.Value);
}
are.Set();
})).Start();
are.WaitOne();
counted.UnifyAtom(s);
return true;
}
[PrologVisible]
static public bool cliTestPbct(PlTerm pred, PlTerm counted)
{
var id = CreatePrologBackedCollection<object>(pred);
string s = String.Empty;
AutoResetEvent are = new AutoResetEvent(false);
(new Thread(() =>
{
var enumer = id.GetEnumerator();
while (enumer.MoveNext())
{
var o = enumer.Current;
s += String.Format("{0},", o);
}
are.Set();
})).Start();
are.WaitOne();
counted.UnifyAtom(s);
return true;
}
[PrologVisible]
static public bool cliTestPbc(PlTerm pred, PlTerm counted)
{
var id = CreatePrologBackedCollection<object>(pred);
string s = String.Empty;
IEnumerator<object> enumer = id.GetEnumerator();
while (enumer.MoveNext())
{
s += String.Format("{0},", enumer.Current);
}
counted.UnifyAtom(s);
return true;
}
}
public abstract class PrologBacked<TKey, TValue>
{
public void InForiegnFrame(Action action)
{
PrologCLR.RegisterCurrentThread();
uint fid = libpl.PL_open_foreign_frame();
try
{
action();
}
finally
{
// if (fid > 0) libpl.PL_close_foreign_frame(fid);
}
}
public static bool PlCall(string module, string querypred, PlTermV termV)
{
return PrologCLR.PlCall(module, querypred, termV);
}
public static PlTerm KeyToTerm(TKey key)
{
if (key.Equals(default(TValue))) return PlTerm.PlVar();
return PrologCLR.ToProlog(key);
}
public static PlTerm ValueToTerm(TValue value)
{
if (value.Equals(default(TValue))) return PlTerm.PlVar();
return PrologCLR.ToProlog(value);
}
public static PlTermV TermVOf(KeyValuePair<TKey, TValue> item)
{
return new PlTermV(KeyToTerm(item.Key), ValueToTerm(item.Value));
}
protected Exception NewNotImplementedException()
{
throw new NotImplementedException("NewNotImplementedException");
}
public abstract string ToDebugString();
}
public class PrologBackedDictionary<TKey, TValue> : PrologBacked<TKey, TValue>, IDictionary<TKey, TValue>
{
private readonly string _module = null;//"user";
private readonly string _getvalue;
private ICollection<TKey> Keyz;
private readonly Type valueType;
private string _assertPred;
private string _retractPred;
private string _retractall;
private Type keyType;
public PrologBackedDictionary(string module, string get_value, ICollection<TKey> keyz, string assertPred, string retractPred, string retractall)
{
_module = module ?? "user";
_getvalue = get_value;
Keyz = keyz;
_assertPred = assertPred;
_retractPred = retractPred;
_retractall = retractall;
keyType = typeof(TKey);
valueType = typeof(TValue);
}
#region Implementation of IEnumerable
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
PrologCLR.RegisterCurrentThread();
return new PrologBackedDictionaryEnumerator(this);
}
public Dictionary<TKey, TValue> Copy()
{
var copy = new Dictionary<TKey, TValue>();
foreach (var e in this)
{
copy.Add(e.Key,e.Value);
}
return copy;
}
public class PrologBackedDictionaryEnumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
private readonly PrologBackedDictionary<TKey, TValue> _dictionary;
private uint fframe = 0;
private PlTermV termV;
private PlQuery plQuery;
public PrologBackedDictionaryEnumerator(PrologBackedDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
Reset();
}
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (plQuery != null) plQuery.Dispose();
plQuery = null;
if (fframe != 0) libpl.PL_close_foreign_frame(fframe);
fframe = 0;
}
#endregion
#region Implementation of IEnumerator
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created.
/// </exception><filterpriority>2</filterpriority>
public bool MoveNext()
{
if (!plQuery.NextSolution())
{
Dispose();
return false;
}
return true;
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created.
/// </exception><filterpriority>2</filterpriority>
public void Reset()
{
Dispose();
//fframe = libpl.PL_open_foreign_frame();
termV = new PlTermV(2);
plQuery = new PlQuery(_dictionary._module, _dictionary._getvalue, termV);
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
public KeyValuePair<TKey, TValue> Current
{
get
{
return new KeyValuePair<TKey, TValue>(
(TKey)PrologCLR.CastTerm(plQuery.Args[0], _dictionary.keyType),
(TValue)PrologCLR.CastTerm(plQuery.Args[1], _dictionary.valueType));
}
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>
/// The current element in the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The enumerator is positioned before the first element of the collection or after the last element.
/// </exception><filterpriority>2</filterpriority>
object IEnumerator.Current
{
get { return Current; }
}
#endregion
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Implementation of ICollection<KeyValuePair<TKey,TValue>>
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public void Add(KeyValuePair<TKey, TValue> item)
{
if (_assertPred == null) throw new NotSupportedException("add " + this);
InForiegnFrame(() =>
{
PlTerm newPlTermV = PrologCLR.PlC(_getvalue, TermVOf(item));
PlCall(_module, _assertPred, new PlTermV(newPlTermV));
});
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public void Clear()
{
if (_retractall == null) throw new NotSupportedException("clear " + this);
InForiegnFrame(() =>
{
PlTerm newPlTermV = PrologCLR.PlC(_getvalue, new PlTermV(2));
PlCall(_module, _retractall, new PlTermV(newPlTermV));
});
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </param>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
bool found = false;
InForiegnFrame(() =>
{
found = PlCall(_module, _getvalue, TermVOf(item));
});
return found;
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.
/// </param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.
/// </param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.
/// </exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.
/// </exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.
/// -or-
/// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.
/// -or-
/// The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.
/// -or-
/// Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.
/// </exception>
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw NewNotImplementedException();
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
bool removed = false;
InForiegnFrame(() =>
{
PlTerm newPlTermV = PrologCLR.PlC(_getvalue, TermVOf(item));
removed = PlCall(_module, _retractPred, new PlTermV(newPlTermV));
});
return removed;
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get { return Keyz.Count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly
{
get { return _retractPred != null; }
}
#endregion
#region Implementation of IDictionary<TKey,TValue>
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
/// </returns>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
public bool ContainsKey(TKey key)
{
if (Keyz != null) return Keyz.Contains(key);
bool found = false;
InForiegnFrame(() =>
{
found = PlCall(_module, _getvalue, new PlTermV(KeyToTerm(key), PlTerm.PlVar()));
});
return found;
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.
/// </param><param name="value">The object to use as the value of the element to add.
/// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.
/// </exception><exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
public void Add(TKey key, TValue value)
{
Add(new KeyValuePair<TKey, TValue>(key, value));
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <param name="key">The key of the element to remove.
/// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.
/// </exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
public bool Remove(TKey key)
{
if (Keyz != null)
{
if (!Keyz.IsReadOnly) return Keyz.Remove(key);
}
if (_retractPred == null) throw new NotSupportedException("remove " + this);
bool removed = false;
InForiegnFrame(() =>
{
PlTerm newPlTermV = PrologCLR.PlC(_getvalue, KeyToTerm(key), PlTerm.PlVar());
removed = PlCall(_module, _retractPred, new PlTermV(newPlTermV));
});
return removed;
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <param name="key">The key whose value to get.
/// </param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.
/// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.
/// </exception>
public bool TryGetValue(TKey key, out TValue value)
{
TValue value0 = default(TValue);
bool res = false;
InForiegnFrame(() =>
{
PlTerm plTermPlVar = PlTerm.PlVar();
PlTermV newPlTermV = new PlTermV(KeyToTerm(key), plTermPlVar);
res = PlCall(_module, _getvalue, newPlTermV);
if (res)
{
value0 = (TValue)PrologCLR.CastTerm(newPlTermV[1], valueType);
}
else
{
}
});
value = value0;
return res;
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>
/// The element with the specified key.
/// </returns>
/// <param name="key">The key of the element to get or set.
/// </param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.
/// </exception><exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.
/// </exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
public TValue this[TKey key]
{
get
{
TValue tvalue = default(TValue);
InForiegnFrame(() =>
{
PlTerm newPlTermV = PrologCLR.PlC(_getvalue, KeyToTerm(key), PlTerm.PlVar());
bool res = PlCall(_module, _getvalue, new PlTermV(newPlTermV));
if (res)
{
tvalue = (TValue)PrologCLR.CastTerm(newPlTermV.Arg(1), valueType);
}
else
{
// tvalue = default(TValue);
}
});
return tvalue;
}
set
{
Remove(key);
Add(new KeyValuePair<TKey, TValue>(key, value));
}
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<TKey> Keys
{
get { return Keyz; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<TValue> Values
{
get { throw NewNotImplementedException(); }
}
#endregion
#region Overrides of PrologBacked<TKey,TValue>
public override string ToDebugString()
{
string ds = "" + Count;
foreach (var kv in this)
{
ds += "," + kv.Key + "=" + kv.Value;
}
return ds;
}
#endregion
}
public class PrologBackedCollection<T> : PrologBacked<T,object>, ICollection<T>, ICollection
{
private readonly string _module = null;//"user";
private readonly string _querypred;
private readonly Type keyType;
private readonly Type valueType;
private string _assertPred;
private string _retractPred;
private string _retractall;
public PrologBackedCollection(string module, string querypred, string assertPred, string retractPred, string retractall)
{
_module = module ?? "user";
_querypred = querypred;
_assertPred = assertPred;
_retractPred = retractPred;
_retractall = retractall;
keyType = typeof (T);
}
#region ICollection<T> Members
public void Add(T item)
{
if (_assertPred == null) throw new NotSupportedException("add " + this);
InForiegnFrame(() =>
{
PlTerm newPlTermV = PrologCLR.PlC(_querypred, new PlTermV(KeyToTerm(item)));
PlCall(_module, _assertPred, new PlTermV(newPlTermV));
});
}
public void Clear()
{
InForiegnFrame(() =>
{
PlTerm newPlTermV = PrologCLR.PlC(_querypred, new PlTermV(1));
PlCall(_module, _retractall, new PlTermV(newPlTermV));
});
}
public bool Contains(T item)
{
bool found = false;
InForiegnFrame(() =>
{
found = PlCall(_module, _querypred, new PlTermV(KeyToTerm(item)));
});
return found;
}
public void CopyTo(T[] array, int arrayIndex)
{
throw NewNotImplementedException();
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.
/// </param><param name="index">The zero-based index in <paramref name="array"/> at which copying begins.
/// </param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.
/// </exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.
/// </exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.
/// -or-
/// <paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.
/// -or-
/// The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.
/// </exception><exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.
/// </exception><filterpriority>2</filterpriority>
public void CopyTo(Array array, int index)
{
throw NewNotImplementedException();
}
public int Count
{
get
{
var copy = 0;
foreach (var e in this)
{
copy++;
}
return copy;
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <returns>
/// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </returns>
/// <filterpriority>2</filterpriority>
public object SyncRoot
{
get { return this; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>
/// true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false.
/// </returns>
/// <filterpriority>2</filterpriority>
public bool IsSynchronized
{
get { throw NewNotImplementedException(); }
}
public bool IsReadOnly
{
get { return _retractPred == null; }
}
public bool Remove(T item)
{
if (_retractPred == null) throw new NotSupportedException("remove " + this);
bool found = false;
InForiegnFrame(() =>
{
found = PlCall(_module, _retractPred, new PlTermV(KeyToTerm(item)));
});
return found;
}
#endregion
public List<T> Copy()
{
var copy = new List<T>();
foreach (var e in this)
{
copy.Add(e);
}
return copy;
}
public override string ToDebugString()
{
string ds = "" + Count;
foreach (var kv in this)
{
ds += "," + kv;
}
return ds;
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
PrologCLR.RegisterCurrentThread();
return new PrologBackedCollectionEnumerator(this);
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return new PrologBackedCollectionEnumerator(this);
}
public class PrologBackedCollectionEnumerator : IEnumerator<T>
{
private readonly PrologBackedCollection<T> _dictionary;
private uint fframe = 0;
private PlTermV termV;
private PlQuery plQuery;
private bool nonLeft = true;
private object currentValue;
public PrologBackedCollectionEnumerator(PrologBackedCollection<T> dictionary)
{
_dictionary = dictionary;
Reset();
}
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (plQuery != null)
{
plQuery.Dispose();
plQuery = null;
}
nonLeft = true;
currentValue = null;
if (fframe != 0) libpl.PL_close_foreign_frame(fframe);
fframe = 0;
}
#endregion
#region Implementation of IEnumerator
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created.
/// </exception><filterpriority>2</filterpriority>
public bool MoveNext()
{
if(!plQuery.NextSolution())
{
Dispose();
return false;
}
nonLeft = false;
PlTerm plQueryArgs = plQuery.Args[0];
currentValue = PrologCLR.CastTerm(plQueryArgs, _dictionary.keyType); ;
return true;
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created.
/// </exception><filterpriority>2</filterpriority>
public void Reset()
{
Dispose();
fframe = libpl.PL_open_foreign_frame();
termV = new PlTermV(1);
plQuery = new PlQuery(_dictionary._module, _dictionary._querypred, termV);
nonLeft = false;
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
public T Current
{
get
{
if (nonLeft)
{
throw new Exception("no current element");
}
return (T) currentValue;
}
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>
/// The current element in the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The enumerator is positioned before the first element of the collection or after the last element.
/// </exception><filterpriority>2</filterpriority>
object IEnumerator.Current
{
get { return Current; }
}
#endregion
}
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
namespace Tatacoa
{
public abstract class DoIf<A> : Functor<A> {
internal Func<bool> condition = () => false;
internal Func<bool> guard = () => true;
public bool truth {
get {
return condition() && guard();
}
}
public abstract DoIf<B> FMap<B> (Func<A,B> f);
public abstract DoIf<A> FMap (Action<A> f);
public abstract DoIf<A> Do (Func<A> f);
public abstract DoIf<A> Try ();
public abstract DoIf<A> If (Func<bool> cond);
public DoIf<A> If (bool cond) {
return If (() => cond);
}
public abstract DoIf<A> Guard (Func<bool> cond);
public abstract A value {get;}
public abstract bool IsWaiting {get;}
Functor<B> Functor<A>.FMap<B> (Func<A, B> f)
{
throw new System.NotImplementedException ();
}
public Functor<A> XMap (Func<Exception, Exception> fx)
{
throw new NotImplementedException ();
}
public static bool operator true (DoIf<A> m) {
return !m.IsWaiting;
}
public static bool operator false (DoIf<A> m) {
return m.IsWaiting;
}
public static bool operator ! (DoIf<A> m) {
return m.IsWaiting;
}
}
public class Waiting<A> : DoIf<A> {
Func<A> fa;
public Waiting () {
fa = () => {
throw new ArgumentException("Undefined Action");
return default(A);
};
}
public Waiting (Func<A> f) {
fa = f;
}
public Waiting (A a) {
fa = () => a;
}
public Waiting (Func<A> f, Func<bool> cond) {
fa = f;
condition = cond;
}
public Waiting (Func<A> f, Func<bool> cond, Func<bool> guard) {
fa = f;
condition = cond;
this.guard = guard;
}
public Waiting (A a, Func<bool> cond) {
fa = () => a;
condition = cond;
}
public override DoIf<A> Do (Func<A> f) {
this.fa = f;
return Try ();
}
public override DoIf<B> FMap<B> (Func<A, B> f)
{
return new Waiting<B> (() => f (fa ()), condition, guard).Try ();
}
public override DoIf<A> FMap (Action<A> f)
{
return new Waiting<A> (() => f.ToFunc () (fa ()), condition, guard).Try();
}
public override DoIf<A> If (Func<bool> cond)
{
return new Waiting<A> (fa, () => cond() || condition(), guard).Try();
}
public override DoIf<A> Guard (Func<bool> cond)
{
return new Waiting<A> (fa, condition, () => cond () && guard ()).Try();
}
public override DoIf<A> Try ()
{
return truth ? new Done<A>(fa(), condition, guard) as DoIf<A> : this as DoIf<A>;
}
public override A value {
get {
return default(A);
}
}
public override bool IsWaiting {
get {
return true;
}
}
}
public class Done<A> : DoIf<A> {
A a;
public Done (A val) {
a = val;
}
public Done (A val, Func<bool> cond) {
a = val;
condition = cond;
}
public Done (A val, Func<bool> cond, Func<bool> guard) {
a = val;
condition = cond;
this.guard = guard;
}
public override DoIf<B> FMap<B> (Func<A, B> f)
{
return new Waiting<A> (() => a, condition, guard).FMap (f).Try();
}
public override DoIf<A> FMap (Action<A> f)
{
return FMap (f.ToFunc ());
}
public override DoIf<A> Do (Func<A> f) {
return new Waiting<A> (f, condition).Try();
}
public override DoIf<A> Try ()
{
return this;
}
public override DoIf<A> If (Func<bool> cond)
{
return new Done<A> (a, () => cond () || condition (), guard).Try();
}
public override DoIf<A> Guard (Func<bool> cond)
{
return new Done<A> (a, condition, () => cond() && guard()).Try();
}
public override A value {
get {
return a;
}
}
public override bool IsWaiting {
get {
return false;
}
}
}
public abstract class DoIf {
internal Func<bool> condition = () => false;
public bool truth {
get {
return condition();
}
}
public abstract DoIf FMap (Action g);
public abstract DoIf Do (Action g);
public abstract DoIf Try ();
public abstract DoIf If (Func<bool> cond);
public DoIf If (bool cond) {
return If (() => cond);
}
public abstract bool IsWaiting {get;}
public static bool operator true (DoIf m) {
return ! m.IsWaiting;
}
public static bool operator false (DoIf m) {
return m.IsWaiting;
}
public static bool operator ! (DoIf m) {
return m.IsWaiting;
}
}
public class Waiting : DoIf {
Action f;
public Waiting (bool cond) {
f = () => {
throw new ArgumentNullException("Action not defined");
};
condition = () => cond;
}
public Waiting (Action g) {
f = g;
}
public Waiting (Action g, Func<bool> cond) {
f = g;
condition = cond;
}
public override DoIf FMap (Action g)
{
return new Waiting ((g) .o (f), condition).Try ();
}
public override DoIf Do (Action g)
{
f = g;
return Try ();
}
public override DoIf Try ()
{
return truth ? new Done (f).Try() as DoIf : this as DoIf;
}
public override DoIf If (Func<bool> cond)
{
return new Waiting (f, () => cond () || condition ()).Try();
}
public override bool IsWaiting {
get {
return true;
}
}
}
public class Done : DoIf {
public Done (Func<bool> cond){
condition = cond;
}
public Done (Action f) {
f ();
}
public override DoIf Try ()
{
return this;
}
public override DoIf FMap (Action g)
{
return new Waiting (g, condition).Try ();
}
public override DoIf Do (Action g)
{
return new Waiting (g).Try ();
}
public override DoIf If (Func<bool> cond)
{
return new Done (() => cond () || condition ()).Try();
}
public override bool IsWaiting {
get {
return false;
}
}
}
public static partial class Fn {
public static DoIf<A> Do<A> (Func<A> f) {
return new Waiting<A> (f);
}
public static DoIf Do (Action f) {
return new Waiting (f);
}
public static DoIf<A> If<A> (Func<bool> cond) {
return new Waiting<A> ().If (cond);
}
public static DoIf<A> If<A> (bool cond) {
return new Waiting<A> ().If (() => cond);
}
public static DoIf If (Func<bool> cond) {
return new Waiting (cond());
}
public static DoIf If (bool cond) {
return new Waiting (cond);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
namespace System.Text
{
public sealed class DecoderReplacementFallback : DecoderFallback
{
// Our variables
private String _strDefault;
// Construction. Default replacement fallback uses no best fit and ? replacement string
public DecoderReplacementFallback() : this("?")
{
}
public DecoderReplacementFallback(String replacement)
{
if (replacement == null)
throw new ArgumentNullException("replacement");
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
if (Char.IsSurrogate(replacement, i))
{
// High or Low?
if (Char.IsHighSurrogate(replacement, i))
{
// if already had a high one, stop
if (bFoundHigh)
break; // break & throw at the bFoundHIgh below
bFoundHigh = true;
}
else
{
// Low, did we have a high?
if (!bFoundHigh)
{
// Didn't have one, make if fail when we stop
bFoundHigh = true;
break;
}
// Clear flag
bFoundHigh = false;
}
}
// If last was high we're in trouble (not surrogate so not low surrogate, so break)
else if (bFoundHigh)
break;
}
if (bFoundHigh)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "replacement");
_strDefault = replacement;
}
public String DefaultString
{
get
{
return _strDefault;
}
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new DecoderReplacementFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return _strDefault.Length;
}
}
public override bool Equals(Object value)
{
DecoderReplacementFallback that = value as DecoderReplacementFallback;
if (that != null)
{
return (_strDefault == that._strDefault);
}
return (false);
}
public override int GetHashCode()
{
return _strDefault.GetHashCode();
}
}
public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer
{
// Store our default string
private String _strDefault;
private int _fallbackCount = -1;
private int _fallbackIndex = -1;
// Construction
public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback)
{
_strDefault = fallback.DefaultString;
}
// Fallback Methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
// We can't call recursively but others might (note, we don't test on last char!!!)
if (_fallbackCount >= 1)
{
ThrowLastBytesRecursive(bytesUnknown);
}
// Go ahead and get our fallback
if (_strDefault.Length == 0)
return false;
_fallbackCount = _strDefault.Length;
_fallbackIndex = -1;
return true;
}
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_fallbackCount--;
_fallbackIndex++;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_fallbackCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_fallbackCount == int.MaxValue)
{
_fallbackCount = -1;
return '\0';
}
// Now make sure its in the expected range
Contract.Assert(_fallbackIndex < _strDefault.Length && _fallbackIndex >= 0,
"Index exceeds buffer range");
return _strDefault[_fallbackIndex];
}
public override bool MovePrevious()
{
// Back up one, only if we just processed the last character (or earlier)
if (_fallbackCount >= -1 && _fallbackIndex >= 0)
{
_fallbackIndex--;
_fallbackCount++;
return true;
}
// Return false 'cause we couldn't do it.
return false;
}
// How many characters left to output?
public override int Remaining
{
get
{
// Our count is 0 for 1 character left.
return (_fallbackCount < 0) ? 0 : _fallbackCount;
}
}
// Clear the buffer
public override unsafe void Reset()
{
_fallbackCount = -1;
_fallbackIndex = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length
return _strDefault.Length;
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using MindTouch.Data;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Deki.Services {
using Yield = IEnumerator<IYield>;
[DreamService("MindTouch MySql Extension", "Copyright (c) 2006-2010 MindTouch Inc.",
Info = "http://developer.mindtouch.com/App_Catalog/MySql",
SID = new string[] {
"sid://mindtouch.com/2007/06/mysql",
"http://services.mindtouch.com/deki/draft/2007/06/mysql"
}
)]
[DreamServiceConfig("db-server", "string?", "Database host name. (default: localhost)")]
[DreamServiceConfig("db-port", "int?", "Database port. (default: 3306)")]
[DreamServiceConfig("db-catalog", "string", "Database table name.")]
[DreamServiceConfig("db-user", "string", "Database user name.")]
[DreamServiceConfig("db-password", "string", "Password for database user.")]
[DreamServiceConfig("db-options", "string?", "Optional connection string parameters. (default: none)")]
[DreamServiceBlueprint("deki/service-type", "extension")]
[DekiExtLibrary(
Label = "MySql",
Namespace = "mysql",
Description = "This extension contains functions for displaying data from MySQL databases.",
Logo = "$files/mysql-logo.png"
)]
[DekiExtLibraryFiles(Prefix = "MindTouch.Deki.Services.Resources", Filenames = new string[] { "sorttable.js", "mysql-logo.png" })]
public class MySqlService : DekiExtService {
//--- Class Fields ---
private static DataFactory _factory = new DataFactory(MySql.Data.MySqlClient.MySqlClientFactory.Instance, "?");
//--- Fields ---
private DataCatalog _catalog;
//--- Functions ---
[DekiExtFunction(Description = "Show results from a SELECT query as a table.", Transform = "pre")]
public XDoc Table(
[DekiExtParam("SELECT query")] string query
) {
XDoc result = new XDoc("html")
.Start("head")
.Start("script").Attr("type", "text/javascript").Attr("src", Files.At("sorttable.js")).End()
.Start("style").Attr("type", "text/css").Value(@".feedtable {
border:1px solid #999;
line-height:1.5em;
overflow:hidden;
width:100%;
}
.feedtable th {
background-color:#ddd;
border-bottom:1px solid #999;
font-size:14px;
}
.feedtable tr {
background-color:#FFFFFF;
}
.feedtable tr.feedroweven td {
background-color:#ededed;
}").End()
.End()
.Start("body");
result.Start("table").Attr("border", 0).Attr("cellpadding", 0).Attr("cellspacing", 0).Attr("class", "feedtable sortable");
_catalog.NewQuery(query).Execute(delegate(IDataReader reader) {
// capture row columns
result.Start("thead").Start("tr");
int count = reader.FieldCount;
for(int i = 0; i < count; ++i) {
result.Start("th").Elem("strong", reader.GetName(i)).End();
}
result.End().End();
// read records
int rowcount = 0;
result.Start("tbody");
while(reader.Read()) {
result.Start("tr");
result.Attr("class", ((rowcount++ & 1) == 0) ? "feedroweven" : "feedrowodd");
for (int i = 0; i < count; ++i) {
string val = string.Empty;
try {
if (!reader.IsDBNull(i)) {
val = reader.GetValue(i).ToString();
}
} catch { }
result.Elem("td", val);
}
result.End();
}
result.End();
});
result.End().End();
return result;
}
[DekiExtFunction(Description = "Get single value from a SELECT query.")]
public string Value(
[DekiExtParam("SELECT query")] string query
) {
return _catalog.NewQuery(query).Read();
}
[DekiExtFunction(Description = "Collect rows as a list from a SELECT query.")]
public ArrayList List(
[DekiExtParam("SELECT query")] string query,
[DekiExtParam("column name (default: first column)", true)] string column
) {
ArrayList result = new ArrayList();
_catalog.NewQuery(query).Execute(delegate(IDataReader reader) {
int index = (column != null) ? reader.GetOrdinal(column) : 0;
while(reader.Read()) {
result.Add(reader[index]);
}
});
return result;
}
[DekiExtFunction(Description = "Collect all columns from a SELECT query.")]
public Hashtable Record(
[DekiExtParam("SELECT query")] string query
) {
Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase);
_catalog.NewQuery(query).Execute(delegate(IDataReader reader) {
if(reader.Read()) {
for(int i = 0; i < reader.FieldCount; ++i) {
result[reader.GetName(i)] = reader[i];
}
}
});
return result;
}
[DekiExtFunction(Description = "Collect all columns and all rows from a SELECT query.")]
public ArrayList RecordList(
[DekiExtParam("SELECT query")] string query
) {
ArrayList result = new ArrayList();
_catalog.NewQuery(query).Execute(delegate(IDataReader reader) {
string[] columns = null;
while(reader.Read()) {
// read result column names
if(columns == null) {
columns = new string[reader.FieldCount];
for(int i = 0; i < columns.Length; ++i) {
columns[i] = reader.GetName(i);
}
}
// read row
Hashtable row = new Hashtable(StringComparer.OrdinalIgnoreCase);
for(int i = 0; i < reader.FieldCount; ++i) {
row[columns[i]] = reader[i];
}
result.Add(row);
}
});
return result;
}
//--- Methods ---
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
_catalog = new DataCatalog(_factory, config);
result.Return();
}
protected override Yield Stop(Result result) {
_catalog = null;
yield return Coroutine.Invoke(base.Stop, new Result());
result.Return();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SelectionScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
#endregion
namespace Spacewar
{
/// <summary>
/// Represents the ship selection screen
/// </summary>
public class SelectionScreen : Screen
{
private static string selectionTexture = @"textures\ship_select_FINAL";
private Vector4 white = new Vector4(1f, 1f, 1f, 1f);
private SceneItem[] ships = new SceneItem[2];
private int[] selectedShip = new int[] { 0, 0 };
private int[] selectedSkin = new int[] { 0, 0 };
private bool player1Ready = false;
private bool player2Ready = false;
private Cue menuMusic;
/// <summary>
/// Creates a new selection screen. Plays the music and initializes the models
/// </summary>
public SelectionScreen(Game game)
: base(game)
{
//Start menu music
menuMusic = Sound.Play(Sounds.MenuMusic);
ships[0] = new SceneItem(game, new EvolvedShape(game, EvolvedShapes.Ship, PlayerIndex.One, selectedShip[0], selectedSkin[0], LightingType.Menu), new Vector3(-120, 0, 0));
ships[0].Scale = new Vector3(.05f, .05f, .05f);
scene.Add(ships[0]);
ships[1] = new SceneItem(game, new EvolvedShape(game, EvolvedShapes.Ship, PlayerIndex.Two, selectedShip[1], selectedSkin[1], LightingType.Menu), new Vector3(120, 0, 0));
ships[1].Scale = new Vector3(.05f, .05f, .05f);
scene.Add(ships[1]);
}
/// <summary>
/// Updates the scene, handles the input
/// </summary>
/// <param name="time">Current game time</param>
/// <param name="elapsedTime">Elapsed time since last update</param>
/// <returns>New gamestate if required or GameState.None</returns>
public override GameState Update(TimeSpan time, TimeSpan elapsedTime)
{
//A button makes a player ready. B button makes a player not ready
if ((XInputHelper.GamePads[PlayerIndex.One].APressed) || (!XInputHelper.GamePads[PlayerIndex.One].State.IsConnected && SpacewarGame.CurrentPlatform != PlatformID.Win32NT))
player1Ready = true;
if ((XInputHelper.GamePads[PlayerIndex.Two].APressed) || (!XInputHelper.GamePads[PlayerIndex.Two].State.IsConnected && SpacewarGame.CurrentPlatform != PlatformID.Win32NT))
player2Ready = true;
if (XInputHelper.GamePads[PlayerIndex.One].BPressed)
player1Ready = false;
if (XInputHelper.GamePads[PlayerIndex.Two].BPressed)
player2Ready = false;
for (int player = 0; player < 2; player++)
{
if ((!player1Ready && player == 0) || (!player2Ready && player == 1))
{
int ship = selectedShip[player];
int skin = selectedSkin[player];
if (XInputHelper.GamePads[(PlayerIndex)player].UpPressed)
selectedShip[player] += 5; //Wrap around
if (XInputHelper.GamePads[(PlayerIndex)player].DownPressed)
selectedShip[player]++;
if (XInputHelper.GamePads[(PlayerIndex)player].LeftPressed)
selectedSkin[player] += 5; //This will wraparound
if (XInputHelper.GamePads[(PlayerIndex)player].RightPressed)
selectedSkin[player]++;
//Make selections wrap around
selectedShip[player] = selectedShip[player] % 3;
selectedSkin[player] = selectedSkin[player] % 3;
//If anything's change then load the new ship/skin
if ((ship != selectedShip[player]) || (skin != selectedSkin[player]))
{
Sound.PlayCue(Sounds.MenuScroll);
ships[player].ShapeItem = new EvolvedShape(GameInstance, EvolvedShapes.Ship, (PlayerIndex)player, selectedShip[player], selectedSkin[player], LightingType.Menu);
}
}
}
//Spin the Ships
for (int i = 0; i < 2; i++)
{
//(i * 2 -1) makes player 2 spin the other way
ships[i].Rotation = new Vector3(-.3f, (float)time.TotalSeconds * (i * 2 - 1), 0);
}
//Update the Scene
base.Update(time, elapsedTime);
//Play the next level when both players are ready
if (player1Ready && player2Ready)
{
//Set global ship and skins
for (int i = 0; i < 2; i++)
{
SpacewarGame.Players[i].ShipClass = (ShipClass)selectedShip[i];
SpacewarGame.Players[i].Skin = selectedSkin[i];
}
Shutdown();
return GameState.PlayEvolved;
}
else
{
return GameState.None;
}
}
/// <summary>
/// Tidy up anything that needs tidying
/// </summary>
public override void Shutdown()
{
//Stop menu music
Sound.Stop(menuMusic);
base.Shutdown();
}
/// <summary>
/// Renders the screen
/// </summary>
public override void Render()
{
IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)GameInstance.Services.GetService(typeof(IGraphicsDeviceService));
GraphicsDevice device = graphicsService.GraphicsDevice;
Texture2D mainTexture = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + selectionTexture);
SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque);
//Sprites will always be at the back.
device.DepthStencilState = DepthStencilState.DepthRead;
//Main background
SpriteBatch.Draw(mainTexture, Vector2.Zero, new Rectangle(0, 0, 1280, 720), Color.White);
SpriteBatch.End();
//New sprite to ensure they are drawn on top
SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend);
//Ready buttons
if (player1Ready)
{
SpriteBatch.Draw(mainTexture, new Vector2(50, 610), new Rectangle(960, 1095, 190, 80), Color.White);
//grey out ships & skins
SpriteBatch.Draw(mainTexture, new Vector2(10, 127), new Rectangle(594, 911, 290, 112), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(10, 239), new Rectangle(594, 1050, 290, 180), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(10, 419), new Rectangle(10, 1200, 290, 140), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(331, 573), new Rectangle(960, 911, 68, 70), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(399, 573), new Rectangle(1040, 911, 68, 70), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(467, 573), new Rectangle(1120, 911, 68, 70), Color.White);
}
else
{
//P1 ship & skins
switch (selectedShip[0])
{
case 0:
SpriteBatch.Draw(mainTexture, new Vector2(10, 127), new Rectangle(10, 730, 290, 112), Color.White);
break;
case 1:
SpriteBatch.Draw(mainTexture, new Vector2(10, 239), new Rectangle(10, 860, 290, 180), Color.White);
break;
case 2:
SpriteBatch.Draw(mainTexture, new Vector2(10, 419), new Rectangle(10, 1050, 290, 140), Color.White);
break;
}
switch (selectedSkin[0])
{
case 0:
SpriteBatch.Draw(mainTexture, new Vector2(331, 573), new Rectangle(960, 730, 68, 70), Color.White);
break;
case 1:
SpriteBatch.Draw(mainTexture, new Vector2(399, 573), new Rectangle(1040, 730, 68, 70), Color.White);
break;
case 2:
SpriteBatch.Draw(mainTexture, new Vector2(467, 573), new Rectangle(1120, 730, 68, 70), Color.White);
break;
}
}
if (player2Ready)
{
SpriteBatch.Draw(mainTexture, new Vector2(1040, 610), new Rectangle(960, 1200, 190, 80), Color.White);
//grey out ships & skins
SpriteBatch.Draw(mainTexture, new Vector2(960, 127), new Rectangle(594, 1290, 290, 112), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(1040, 239), new Rectangle(332, 1050, 225, 180), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(1040, 419), new Rectangle(331, 1290, 225, 140), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(745, 573), new Rectangle(960, 1000, 68, 70), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(813, 573), new Rectangle(1040, 1000, 68, 70), Color.White);
SpriteBatch.Draw(mainTexture, new Vector2(881, 573), new Rectangle(1120, 1000, 68, 70), Color.White);
}
else
{
//p2 ships & skins
switch (selectedShip[1])
{
case 0:
SpriteBatch.Draw(mainTexture, new Vector2(960, 127), new Rectangle(331, 730, 290, 112), Color.White);
break;
case 1:
SpriteBatch.Draw(mainTexture, new Vector2(1040, 239), new Rectangle(331, 860, 225, 180), Color.White);
break;
case 2:
SpriteBatch.Draw(mainTexture, new Vector2(1040, 419), new Rectangle(700, 730, 225, 140), Color.White);
break;
}
switch (selectedSkin[1])
{
case 0:
SpriteBatch.Draw(mainTexture, new Vector2(745, 573), new Rectangle(960, 820, 68, 70), Color.White);
break;
case 1:
SpriteBatch.Draw(mainTexture, new Vector2(813, 573), new Rectangle(1040, 820, 68, 70), Color.White);
break;
case 2:
SpriteBatch.Draw(mainTexture, new Vector2(881, 573), new Rectangle(1120, 820, 68, 70), Color.White);
break;
}
}
SpriteBatch.End();
//Ship names
Font.Begin();
Font.Draw(FontStyle.ShipNames, 331, 500, selectedShip[0].ToString(), new Vector4(.2f, .89f, 1, 1));
Font.Draw(FontStyle.ShipNames, 745, 500, selectedShip[1].ToString(), new Vector4(1, .733f, .392f, 1));
Font.End();
base.Render();
}
public override void OnCreateDevice()
{
base.OnCreateDevice();
ships[0].ShapeItem.OnCreateDevice();
ships[1].ShapeItem.OnCreateDevice();
}
}
}
| |
// Copyright (c) "Neo4j"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Neo4j.Driver.IntegrationTests.Direct
{
public class TransactionIT : DirectDriverTestBase
{
private IDriver Driver => Server.Driver;
public TransactionIT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture)
{
}
[RequireServerFact]
public async Task ShouldRetry()
{
var session = Driver.AsyncSession();
try
{
var timer = Stopwatch.StartNew();
var exc = await Record.ExceptionAsync(() =>
session.WriteTransactionAsync(tx =>
throw new SessionExpiredException($"Failed at {timer.Elapsed}")));
timer.Stop();
exc.Should().BeOfType<ServiceUnavailableException>()
.Which.InnerException.Should().BeOfType<AggregateException>()
.Which.InnerExceptions.Should().NotBeEmpty().And.AllBeOfType<SessionExpiredException>();
timer.Elapsed.Should().BeGreaterThan(TimeSpan.FromSeconds(30));
}
finally
{
await session.CloseAsync();
}
}
[RequireServerFact]
public async Task ShouldCommitTransactionByDefault()
{
var session = Driver.AsyncSession();
try
{
var createResult =
await session.WriteTransactionAsync(tx =>
tx.RunAndSingleAsync("CREATE (n) RETURN count(n)", null));
// the read operation should see the commited write tx
var matchResult =
await session.ReadTransactionAsync(tx =>
tx.RunAndSingleAsync("MATCH (n) RETURN count(n)", null));
createResult.Should().BeEquivalentTo(matchResult);
}
finally
{
await session.CloseAsync();
}
}
[RequireServerFact]
public async Task ShouldNotCommitTransaction()
{
var session = Driver.AsyncSession();
try
{
var createResult = await session.WriteTransactionAsync(async tx =>
{
var result = await tx.RunAndSingleAsync("CREATE (n) RETURN count(n)", null, r => r[0].As<int>());
await tx.RollbackAsync();
return result;
});
// the read operation should not see the rolled back write tx
var matchResult =
await session.ReadTransactionAsync(tx =>
tx.RunAndSingleAsync("MATCH (n) RETURN count(n)", null, r => r[0].As<int>()));
createResult.Should().Be(matchResult + 1);
}
finally
{
await session.CloseAsync();
}
}
[RequireServerFact]
public async Task ShouldNotCommitIfError()
{
var session = Driver.AsyncSession();
try
{
var exc = await Record.ExceptionAsync(() => session.WriteTransactionAsync(async tx =>
{
await tx.RunAsync("CREATE (n) RETURN count(n)");
throw new ProtocolException("Broken");
}));
exc.Should().NotBeNull();
// the read operation should not see the rolled back write tx
var matchResult =
await session.ReadTransactionAsync(tx =>
tx.RunAndSingleAsync("MATCH (n) RETURN count(n)", null, r => r[0].As<int>()));
matchResult.Should().Be(0);
}
finally
{
await session.CloseAsync();
}
}
[RequireServerFact]
public async Task KeysShouldBeAvailableAfterRun()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor = await txc.RunAsync("RETURN 1 As X");
var keys = await cursor.KeysAsync();
keys.Should().HaveCount(1);
keys.Should().Contain("X");
await txc.CommitAsync();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task KeysShouldBeAvailableAfterRunAndResultConsumption()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor = await txc.RunAsync("RETURN 1 As X");
var keys = await cursor.KeysAsync();
keys.Should().BeEquivalentTo("X");
await cursor.ConsumeAsync();
keys = await cursor.KeysAsync();
keys.Should().BeEquivalentTo("X");
await txc.CommitAsync();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task KeysShouldBeAvailableAfterConsecutiveRun()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor1 = await txc.RunAsync("RETURN 1 As X");
var cursor2 = await txc.RunAsync("RETURN 1 As Y");
var keys1 = await cursor1.KeysAsync();
keys1.Should().BeEquivalentTo("X");
var keys2 = await cursor2.KeysAsync();
keys2.Should().BeEquivalentTo("Y");
await txc.CommitAsync();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task KeysShouldBeAvailableAfterConsecutiveRunAndResultConsumption()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor1 = await txc.RunAsync("RETURN 1 As X");
var cursor2 = await txc.RunAsync("RETURN 1 As Y");
var keys1 = await cursor1.KeysAsync();
keys1.Should().BeEquivalentTo("X");
var keys2 = await cursor2.KeysAsync();
keys2.Should().BeEquivalentTo("Y");
await cursor1.ConsumeAsync();
await cursor2.ConsumeAsync();
keys1 = await cursor1.KeysAsync();
keys1.Should().BeEquivalentTo("X");
keys2 = await cursor2.KeysAsync();
keys2.Should().BeEquivalentTo("Y");
await txc.CommitAsync();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task KeysShouldBeAvailableAfterConsecutiveRunNoOrder()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor1 = await txc.RunAsync("RETURN 1 As X");
var cursor2 = await txc.RunAsync("RETURN 1 As Y");
var keys2 = await cursor2.KeysAsync();
keys2.Should().BeEquivalentTo("Y");
var keys1 = await cursor1.KeysAsync();
keys1.Should().BeEquivalentTo("X");
await txc.CommitAsync();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task KeysShouldBeAvailableAfterConsecutiveRunAndResultConsumptionNoOrder()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor1 = await txc.RunAsync("RETURN 1 As X");
var cursor2 = await txc.RunAsync("RETURN 1 As Y");
var keys2 = await cursor2.KeysAsync();
keys2.Should().BeEquivalentTo("Y");
var keys1 = await cursor1.KeysAsync();
keys1.Should().BeEquivalentTo("X");
await cursor2.ConsumeAsync();
await cursor1.ConsumeAsync();
keys2 = await cursor2.KeysAsync();
keys2.Should().BeEquivalentTo("Y");
keys1 = await cursor1.KeysAsync();
keys1.Should().BeEquivalentTo("X");
await txc.CommitAsync();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task ShouldNotBeAbleToAccessRecordsAfterRollback()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor = await txc.RunAsync("RETURN 1 As X");
await txc.RollbackAsync();
var error = await Record.ExceptionAsync(async () => await cursor.ToListAsync());
error.Should().BeOfType<ResultConsumedException>();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task ShouldNotBeAbleToAccessRecordsAfterCommit()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor = await txc.RunAsync("RETURN 1 As X");
await txc.CommitAsync();
var error = await Record.ExceptionAsync(async () => await cursor.ToListAsync());
error.Should().BeOfType<ResultConsumedException>();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task ShouldNotBeAbleToAccessRecordsAfterSummary()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken))
{
var session = driver.AsyncSession();
try
{
var txc = await session.BeginTransactionAsync();
var cursor = await txc.RunAsync("RETURN 1 As X");
await cursor.ConsumeAsync();
var error = await Record.ExceptionAsync(async () => await cursor.ToListAsync());
error.Should().BeOfType<ResultConsumedException>();
await txc.RollbackAsync();
}
finally
{
await session.CloseAsync();
}
}
}
[RequireServerFact]
public async Task ShouldBeAbleToRunNestedQueries()
{
using (var driver = GraphDatabase.Driver(ServerEndPoint, AuthToken, o => o.WithFetchSize(2)))
{
const int size = 1024;
var session = driver.AsyncSession(o => o.WithFetchSize(5));
try
{
var txc1 = await session.BeginTransactionAsync();
var cursor1 = await txc1.RunAsync("UNWIND range(1, $size) AS x RETURN x", new {size});
await cursor1.ForEachAsync(async r =>
await txc1.RunAsync("UNWIND $x AS id CREATE (n:Node {id: id}) RETURN n.id",
new {x = r["x"].As<int>()}));
var count = await (await txc1.RunAsync("MATCH (n:Node) RETURN count(n)")).SingleAsync();
count[0].As<int>().Should().Be(size);
await txc1.RollbackAsync();
}
finally
{
await session.CloseAsync();
}
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LambdaModuloTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloDecimalTest(bool useInterpreter)
{
decimal[] values = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloDoubleTest(bool useInterpreter)
{
double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloFloatTest(bool useInterpreter)
{
float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloIntTest(bool useInterpreter)
{
int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloLongTest(bool useInterpreter)
{
long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloShortTest(bool useInterpreter)
{
short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloUIntTest(bool useInterpreter)
{
uint[] values = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloULongTest(bool useInterpreter)
{
ulong[] values = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloUShortTest(bool useInterpreter)
{
ushort[] values = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private enum ResultType
{
Success,
DivideByZero,
Overflow
}
#region Verify decimal
private static void VerifyModuloDecimal(decimal a, decimal b, bool useInterpreter)
{
bool divideByZero;
decimal expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(decimal), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal), "p1");
// verify with parameters supplied
Expression<Func<decimal>> e1 =
Expression.Lambda<Func<decimal>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<decimal, decimal, Func<decimal>>> e2 =
Expression.Lambda<Func<decimal, decimal, Func<decimal>>>(
Expression.Lambda<Func<decimal>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal, decimal, Func<decimal>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<decimal, decimal, decimal>>> e3 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal, decimal> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<decimal, decimal, decimal>>> e4 =
Expression.Lambda<Func<Func<decimal, decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal, decimal, decimal>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<decimal, Func<decimal, decimal>>> e5 =
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal, Func<decimal, decimal>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<decimal, decimal>>> e6 =
Expression.Lambda<Func<Func<decimal, decimal>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal, Func<decimal, decimal>>>(
Expression.Lambda<Func<decimal, decimal>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal, decimal> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify double
private static void VerifyModuloDouble(double a, double b, bool useInterpreter)
{
double expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(double), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double), "p1");
// verify with parameters supplied
Expression<Func<double>> e1 =
Expression.Lambda<Func<double>>(
Expression.Invoke(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))
}),
Enumerable.Empty<ParameterExpression>());
Func<double> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<double, double, Func<double>>> e2 =
Expression.Lambda<Func<double, double, Func<double>>>(
Expression.Lambda<Func<double>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double, double, Func<double>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<double, double, double>>> e3 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double, double, double> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<double, double, double>>> e4 =
Expression.Lambda<Func<Func<double, double, double>>>(
Expression.Lambda<Func<double, double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double, double, double>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<double, Func<double, double>>> e5 =
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double, Func<double, double>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<double, double>>> e6 =
Expression.Lambda<Func<Func<double, double>>>(
Expression.Invoke(
Expression.Lambda<Func<double, Func<double, double>>>(
Expression.Lambda<Func<double, double>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double)) }),
Enumerable.Empty<ParameterExpression>());
Func<double, double> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify float
private static void VerifyModuloFloat(float a, float b, bool useInterpreter)
{
float expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(float), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float), "p1");
// verify with parameters supplied
Expression<Func<float>> e1 =
Expression.Lambda<Func<float>>(
Expression.Invoke(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))
}),
Enumerable.Empty<ParameterExpression>());
Func<float> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<float, float, Func<float>>> e2 =
Expression.Lambda<Func<float, float, Func<float>>>(
Expression.Lambda<Func<float>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float, float, Func<float>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<float, float, float>>> e3 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float, float, float> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<float, float, float>>> e4 =
Expression.Lambda<Func<Func<float, float, float>>>(
Expression.Lambda<Func<float, float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float, float, float>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<float, Func<float, float>>> e5 =
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float, Func<float, float>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<float, float>>> e6 =
Expression.Lambda<Func<Func<float, float>>>(
Expression.Invoke(
Expression.Lambda<Func<float, Func<float, float>>>(
Expression.Lambda<Func<float, float>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float)) }),
Enumerable.Empty<ParameterExpression>());
Func<float, float> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify int
private static void VerifyModuloInt(int a, int b, bool useInterpreter)
{
ResultType outcome;
int expected = 0;
if (b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == int.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(int), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int), "p1");
// verify with parameters supplied
Expression<Func<int>> e1 =
Expression.Lambda<Func<int>>(
Expression.Invoke(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))
}),
Enumerable.Empty<ParameterExpression>());
Func<int> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<int, int, Func<int>>> e2 =
Expression.Lambda<Func<int, int, Func<int>>>(
Expression.Lambda<Func<int>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int, int, Func<int>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<int, int, int>>> e3 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int, int, int> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<int, int, int>>> e4 =
Expression.Lambda<Func<Func<int, int, int>>>(
Expression.Lambda<Func<int, int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int, int, int>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<int, Func<int, int>>> e5 =
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int, Func<int, int>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<int, int>>> e6 =
Expression.Lambda<Func<Func<int, int>>>(
Expression.Invoke(
Expression.Lambda<Func<int, Func<int, int>>>(
Expression.Lambda<Func<int, int>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int)) }),
Enumerable.Empty<ParameterExpression>());
Func<int, int> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify long
private static void VerifyModuloLong(long a, long b, bool useInterpreter)
{
ResultType outcome;
long expected = 0;
if (b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == long.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(long), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long), "p1");
// verify with parameters supplied
Expression<Func<long>> e1 =
Expression.Lambda<Func<long>>(
Expression.Invoke(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))
}),
Enumerable.Empty<ParameterExpression>());
Func<long> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<long, long, Func<long>>> e2 =
Expression.Lambda<Func<long, long, Func<long>>>(
Expression.Lambda<Func<long>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long, long, Func<long>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<long, long, long>>> e3 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long, long, long> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<long, long, long>>> e4 =
Expression.Lambda<Func<Func<long, long, long>>>(
Expression.Lambda<Func<long, long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long, long, long>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<long, Func<long, long>>> e5 =
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long, Func<long, long>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<long, long>>> e6 =
Expression.Lambda<Func<Func<long, long>>>(
Expression.Invoke(
Expression.Lambda<Func<long, Func<long, long>>>(
Expression.Lambda<Func<long, long>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long)) }),
Enumerable.Empty<ParameterExpression>());
Func<long, long> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify short
private static void VerifyModuloShort(short a, short b, bool useInterpreter)
{
bool divideByZero;
short expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = (short)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(short), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short), "p1");
// verify with parameters supplied
Expression<Func<short>> e1 =
Expression.Lambda<Func<short>>(
Expression.Invoke(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))
}),
Enumerable.Empty<ParameterExpression>());
Func<short> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<short, short, Func<short>>> e2 =
Expression.Lambda<Func<short, short, Func<short>>>(
Expression.Lambda<Func<short>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short, short, Func<short>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<short, short, short>>> e3 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short, short, short> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<short, short, short>>> e4 =
Expression.Lambda<Func<Func<short, short, short>>>(
Expression.Lambda<Func<short, short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short, short, short>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<short, Func<short, short>>> e5 =
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short, Func<short, short>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<short, short>>> e6 =
Expression.Lambda<Func<Func<short, short>>>(
Expression.Invoke(
Expression.Lambda<Func<short, Func<short, short>>>(
Expression.Lambda<Func<short, short>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short)) }),
Enumerable.Empty<ParameterExpression>());
Func<short, short> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify uint
private static void VerifyModuloUInt(uint a, uint b, bool useInterpreter)
{
bool divideByZero;
uint expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(uint), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint), "p1");
// verify with parameters supplied
Expression<Func<uint>> e1 =
Expression.Lambda<Func<uint>>(
Expression.Invoke(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<uint, uint, Func<uint>>> e2 =
Expression.Lambda<Func<uint, uint, Func<uint>>>(
Expression.Lambda<Func<uint>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint, uint, Func<uint>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<uint, uint, uint>>> e3 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint, uint> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<uint, uint, uint>>> e4 =
Expression.Lambda<Func<Func<uint, uint, uint>>>(
Expression.Lambda<Func<uint, uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint, uint, uint>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<uint, Func<uint, uint>>> e5 =
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint, Func<uint, uint>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<uint, uint>>> e6 =
Expression.Lambda<Func<Func<uint, uint>>>(
Expression.Invoke(
Expression.Lambda<Func<uint, Func<uint, uint>>>(
Expression.Lambda<Func<uint, uint>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint, uint> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ulong
private static void VerifyModuloULong(ulong a, ulong b, bool useInterpreter)
{
bool divideByZero;
ulong expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(ulong), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong), "p1");
// verify with parameters supplied
Expression<Func<ulong>> e1 =
Expression.Lambda<Func<ulong>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ulong, ulong, Func<ulong>>> e2 =
Expression.Lambda<Func<ulong, ulong, Func<ulong>>>(
Expression.Lambda<Func<ulong>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong, ulong, Func<ulong>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ulong, ulong, ulong>>> e3 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong, ulong> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ulong, ulong, ulong>>> e4 =
Expression.Lambda<Func<Func<ulong, ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong, ulong, ulong>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ulong, Func<ulong, ulong>>> e5 =
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong, Func<ulong, ulong>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ulong, ulong>>> e6 =
Expression.Lambda<Func<Func<ulong, ulong>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong, Func<ulong, ulong>>>(
Expression.Lambda<Func<ulong, ulong>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong, ulong> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ushort
private static void VerifyModuloUShort(ushort a, ushort b, bool useInterpreter)
{
bool divideByZero;
ushort expected;
if (b == 0)
{
divideByZero = true;
expected = 0;
}
else
{
divideByZero = false;
expected = (ushort)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(ushort), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort), "p1");
// verify with parameters supplied
Expression<Func<ushort>> e1 =
Expression.Lambda<Func<ushort>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ushort, ushort, Func<ushort>>> e2 =
Expression.Lambda<Func<ushort, ushort, Func<ushort>>>(
Expression.Lambda<Func<ushort>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort, ushort, Func<ushort>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ushort, ushort, ushort>>> e3 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort, ushort> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ushort, ushort, ushort>>> e4 =
Expression.Lambda<Func<Func<ushort, ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort, ushort, ushort>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ushort, Func<ushort, ushort>>> e5 =
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort, Func<ushort, ushort>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ushort, ushort>>> e6 =
Expression.Lambda<Func<Func<ushort, ushort>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort, Func<ushort, ushort>>>(
Expression.Lambda<Func<ushort, ushort>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort, ushort> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#endregion
}
}
| |
//
// TrackActions.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Widgets;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.ServiceStack;
using Banshee.Widgets;
using Banshee.Gui;
using Banshee.Gui.Dialogs;
using Banshee.Gui.Widgets;
using Hyena.Data;
namespace Banshee.Gui
{
public class TrackActions : BansheeActionGroup
{
private RatingActionProxy rating_proxy;
private static readonly string [] require_selection_actions = new string [] {
"TrackPropertiesAction", "AddToPlaylistAction",
"RemoveTracksAction", "RemoveTracksFromLibraryAction", "OpenContainingFolderAction",
"DeleteTracksFromDriveAction", "RateTracksAction", "SelectNoneAction", "PlayTrack"
};
private static readonly string [] disable_for_filter_actions = new string [] {
"SelectAllAction", "SelectNoneAction", "SearchMenuAction",
// FIXME should be able to do this, just need to implement it
"RateTracksAction"
};
private Hyena.Collections.Selection filter_selection = new Hyena.Collections.Selection ();
private bool filter_focused;
public bool FilterFocused {
get { return filter_focused; }
set {
if (filter_focused == value)
return;
filter_focused = value;
if (value) {
Selection = filter_selection;
SuppressSelectActions ();
} else {
Selection = current_source.TrackModel.Selection;
UnsuppressSelectActions ();
}
UpdateActions ();
OnSelectionChanged ();
}
}
public event EventHandler SelectionChanged;
public Hyena.Collections.Selection Selection { get; private set; }
public ModelSelection<TrackInfo> SelectedTracks {
get {
return FilterFocused
? new ModelSelection<TrackInfo> (current_source.TrackModel, Selection)
: current_source.TrackModel.SelectedItems;
}
}
public TrackActions () : base ("Track")
{
Add (new ActionEntry [] {
new ActionEntry("TrackContextMenuAction", null,
String.Empty, null, null, OnTrackContextMenu),
new ActionEntry("SelectAllAction", null,
Catalog.GetString("Select _All"), "<control>A",
Catalog.GetString("Select all tracks"), OnSelectAll),
new ActionEntry("SelectNoneAction", null,
Catalog.GetString("Select _None"), "<control><shift>A",
Catalog.GetString("Unselect all tracks"), OnSelectNone),
new ActionEntry ("TrackEditorAction", Stock.Edit,
Catalog.GetString ("_Edit Track Information"), "E",
Catalog.GetString ("Edit information on selected tracks"), OnTrackEditor),
new ActionEntry ("TrackPropertiesAction", Stock.Properties,
Catalog.GetString ("Properties"), "",
Catalog.GetString ("View information on selected tracks"), OnTrackProperties),
new ActionEntry ("PlayTrack", null,
Catalog.GetString ("_Play"), "",
Catalog.GetString ("Play the selected item"), OnPlayTrack),
new ActionEntry ("AddToPlaylistAction", null,
Catalog.GetString ("Add _to Playlist"), "",
Catalog.GetString ("Append selected items to playlist or create new playlist from selection"),
OnAddToPlaylistMenu),
new ActionEntry ("AddToNewPlaylistAction", Stock.New,
Catalog.GetString ("New Playlist"), null,
Catalog.GetString ("Create new playlist from selected tracks"),
OnAddToNewPlaylist),
new ActionEntry ("RemoveTracksAction", Stock.Remove,
Catalog.GetString ("_Remove"), "Delete",
Catalog.GetString ("Remove selected track(s) from this source"), OnRemoveTracks),
new ActionEntry ("RemoveTracksFromLibraryAction", null,
Catalog.GetString ("Remove From _Library"), "",
Catalog.GetString ("Remove selected track(s) from library"), OnRemoveTracksFromLibrary),
new ActionEntry ("OpenContainingFolderAction", null,
Catalog.GetString ("_Open Containing Folder"), "",
Catalog.GetString ("Open the folder that contains the selected item"), OnOpenContainingFolder),
new ActionEntry ("DeleteTracksFromDriveAction", null,
Catalog.GetString ("_Delete From Drive"), "",
Catalog.GetString ("Permanently delete selected item(s) from medium"), OnDeleteTracksFromDrive),
new ActionEntry ("RateTracksAction", null,
String.Empty, null, null, OnRateTracks),
new ActionEntry ("SearchMenuAction", Stock.Find,
Catalog.GetString ("_Search"), null,
Catalog.GetString ("Search for items matching certain criteria"), null),
new ActionEntry ("SearchForSameAlbumAction", null,
Catalog.GetString ("By Matching _Album"), "",
Catalog.GetString ("Search all songs of this album"), OnSearchForSameAlbum),
new ActionEntry ("SearchForSameArtistAction", null,
Catalog.GetString ("By Matching A_rtist"), "",
Catalog.GetString ("Search all songs of this artist"), OnSearchForSameArtist),
});
Actions.UIManager.ActionsChanged += HandleActionsChanged;
Actions.GlobalActions["EditMenuAction"].Activated += HandleEditMenuActivated;
ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged;
this["AddToPlaylistAction"].HideIfEmpty = false;
this["PlayTrack"].StockId = Gtk.Stock.MediaPlay;
}
#region State Event Handlers
private ITrackModelSource current_source;
private void HandleActiveSourceChanged (SourceEventArgs args)
{
FilterFocused = false;
if (current_source != null && current_source.TrackModel != null) {
current_source.TrackModel.Reloaded -= OnReloaded;
current_source.TrackModel.Selection.Changed -= HandleSelectionChanged;
current_source = null;
}
ITrackModelSource new_source = ActiveSource as ITrackModelSource;
if (new_source != null) {
new_source.TrackModel.Selection.Changed += HandleSelectionChanged;
new_source.TrackModel.Reloaded += OnReloaded;
current_source = new_source;
Selection = new_source.TrackModel.Selection;
}
ThreadAssist.ProxyToMain (UpdateActions);
}
private void OnReloaded (object sender, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
UpdateActions ();
});
}
private void HandleActionsChanged (object sender, EventArgs args)
{
if (Actions.UIManager.GetAction ("/MainMenu/EditMenu") != null) {
rating_proxy = new RatingActionProxy (Actions.UIManager, this["RateTracksAction"]);
rating_proxy.AddPath ("/MainMenu/EditMenu", "AddToPlaylist");
rating_proxy.AddPath ("/TrackContextMenu", "AddToPlaylist");
Actions.UIManager.ActionsChanged -= HandleActionsChanged;
}
}
private void HandleSelectionChanged (object sender, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
OnSelectionChanged ();
UpdateActions ();
});
}
private void HandleEditMenuActivated (object sender, EventArgs args)
{
ResetRating ();
}
private void OnSelectionChanged ()
{
EventHandler handler = SelectionChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
#endregion
#region Utility Methods
private bool select_actions_suppressed = false;
private void SuppressSelectActions ()
{
if (!select_actions_suppressed) {
this ["SelectAllAction"].DisconnectAccelerator ();
this ["SelectNoneAction"].DisconnectAccelerator ();
select_actions_suppressed = true;
}
}
private void UnsuppressSelectActions ()
{
if (select_actions_suppressed) {
this ["SelectAllAction"].ConnectAccelerator ();
this ["SelectNoneAction"].ConnectAccelerator ();
select_actions_suppressed = false;
}
}
public void UpdateActions ()
{
Source source = ServiceManager.SourceManager.ActiveSource;
if (source == null) {
Sensitive = Visible = false;
return;
}
bool in_database = source is DatabaseSource;
PrimarySource primary_source = (source as PrimarySource) ?? (source.Parent as PrimarySource);
var track_source = source as ITrackModelSource;
if (track_source != null) {
if (FilterFocused) {
if (Selection == filter_selection) {
filter_selection.MaxIndex = track_source.TrackModel.Selection.MaxIndex;
filter_selection.Clear (false);
filter_selection.SelectAll ();
} else {
Log.Error ("Filter focused, but selection is not filter selection!");
Console.WriteLine (System.Environment.StackTrace);
}
}
var selection = Selection;
int count = selection.Count;
Sensitive = Visible = true;
bool has_selection = count > 0;
bool has_single_selection = count == 1;
foreach (string action in require_selection_actions) {
this[action].Sensitive = has_selection;
}
UpdateActions (source.CanSearch && !FilterFocused, has_single_selection,
"SearchMenuAction", "SearchForSameArtistAction", "SearchForSameAlbumAction"
);
this["SelectAllAction"].Sensitive = track_source.Count > 0 && !selection.AllSelected;
UpdateAction ("RemoveTracksAction", track_source.CanRemoveTracks, has_selection, source);
UpdateAction ("DeleteTracksFromDriveAction", track_source.CanDeleteTracks, has_selection, source);
//if it can delete tracks, most likely it can open their folder
UpdateAction ("OpenContainingFolderAction", track_source.CanDeleteTracks, has_single_selection, source);
UpdateAction ("RemoveTracksFromLibraryAction", source.Parent is LibrarySource, has_selection, null);
UpdateAction ("TrackPropertiesAction", source.HasViewableTrackProperties, has_selection, source);
UpdateAction ("TrackEditorAction", source.HasEditableTrackProperties, has_selection, source);
UpdateAction ("RateTracksAction", source.HasEditableTrackProperties, has_selection, null);
UpdateAction ("AddToPlaylistAction", in_database && primary_source != null &&
primary_source.SupportsPlaylists && !primary_source.PlaylistsReadOnly, has_selection, null);
if (primary_source != null &&
!(primary_source is LibrarySource) &&
primary_source.StorageName != null) {
this["DeleteTracksFromDriveAction"].Label = String.Format (
Catalog.GetString ("_Delete From \"{0}\""), primary_source.StorageName);
}
if (FilterFocused) {
UpdateActions (false, false, disable_for_filter_actions);
}
} else {
Sensitive = Visible = false;
}
}
private void ResetRating ()
{
if (current_source != null) {
int rating = 0;
// If there is only one track, get the preset rating
if (Selection.Count == 1) {
foreach (TrackInfo track in SelectedTracks) {
rating = track.Rating;
}
}
rating_proxy.Reset (rating);
}
}
#endregion
#region Action Handlers
private void OnSelectAll (object o, EventArgs args)
{
if (current_source != null)
current_source.TrackModel.Selection.SelectAll ();
}
private void OnSelectNone (object o, EventArgs args)
{
if (current_source != null)
current_source.TrackModel.Selection.Clear ();
}
private void OnTrackContextMenu (object o, EventArgs args)
{
ResetRating ();
UpdateActions ();
ShowContextMenu ("/TrackContextMenu");
}
private bool RunSourceOverrideHandler (string sourceOverrideHandler)
{
Source source = current_source as Source;
InvokeHandler handler = source != null
? source.GetInheritedProperty<InvokeHandler> (sourceOverrideHandler)
: null;
if (handler != null) {
handler ();
return true;
}
return false;
}
private void OnTrackProperties (object o, EventArgs args)
{
if (current_source != null && !RunSourceOverrideHandler ("TrackPropertiesActionHandler")) {
var s = current_source as Source;
var readonly_tabs = s != null && !s.HasEditableTrackProperties;
TrackEditor.TrackEditorDialog.RunView (current_source.TrackModel, Selection, readonly_tabs);
}
}
private void OnTrackEditor (object o, EventArgs args)
{
if (current_source != null && !RunSourceOverrideHandler ("TrackEditorActionHandler")) {
TrackEditor.TrackEditorDialog.RunEdit (current_source.TrackModel, Selection);
}
}
private void OnPlayTrack (object o, EventArgs args)
{
var source = ServiceManager.SourceManager.ActiveSource as ITrackModelSource;
if (source != null) {
var track = source.TrackModel [FilterFocused ? 0 : source.TrackModel.Selection.FocusedIndex];
if (track.HasAttribute (TrackMediaAttributes.ExternalResource)) {
System.Diagnostics.Process.Start (track.Uri);
} else {
ServiceManager.PlaybackController.Source = source;
ServiceManager.PlayerEngine.OpenPlay (track);
}
}
}
// Called when the Add to Playlist action is highlighted.
// Generates the menu of playlists to which you can add the selected tracks.
private void OnAddToPlaylistMenu (object o, EventArgs args)
{
Source active_source = ServiceManager.SourceManager.ActiveSource;
List<Source> children;
lock (ActivePrimarySource.Children) {
children = new List<Source> (ActivePrimarySource.Children);
}
// TODO find just the menu that was activated instead of modifying all proxies
foreach (Widget proxy_widget in (o as Gtk.Action).Proxies) {
MenuItem menu = proxy_widget as MenuItem;
if (menu == null)
continue;
Menu submenu = new Menu ();
menu.Submenu = submenu;
submenu.Append (this ["AddToNewPlaylistAction"].CreateMenuItem ());
bool separator_added = false;
foreach (Source child in children) {
PlaylistSource playlist = child as PlaylistSource;
if (playlist != null) {
if (!separator_added) {
submenu.Append (new SeparatorMenuItem ());
separator_added = true;
}
PlaylistMenuItem item = new PlaylistMenuItem (playlist);
item.Image = new Gtk.Image ("playlist-source", IconSize.Menu);
item.Activated += OnAddToExistingPlaylist;
item.Sensitive = playlist != active_source;
submenu.Append (item);
}
}
submenu.ShowAll ();
}
}
private void OnAddToNewPlaylist (object o, EventArgs args)
{
// TODO generate name based on the track selection, or begin editing it
PlaylistSource playlist = new PlaylistSource (Catalog.GetString ("New Playlist"), ActivePrimarySource);
playlist.Save ();
playlist.PrimarySource.AddChildSource (playlist);
AddToPlaylist (playlist);
}
private void OnAddToExistingPlaylist (object o, EventArgs args)
{
AddToPlaylist (((PlaylistMenuItem)o).Playlist);
}
private void AddToPlaylist (PlaylistSource playlist)
{
if (!FilterFocused) {
playlist.AddSelectedTracks (ActiveSource);
} else {
playlist.AddAllTracks (ActiveSource);
}
}
private void OnRemoveTracks (object o, EventArgs args)
{
ITrackModelSource source = ActiveSource as ITrackModelSource;
if (!ConfirmRemove (source, false, Selection.Count))
return;
if (source != null && source.CanRemoveTracks) {
source.RemoveTracks (Selection);
}
}
private void OnRemoveTracksFromLibrary (object o, EventArgs args)
{
ITrackModelSource source = ActiveSource as ITrackModelSource;
if (source != null) {
LibrarySource library = source.Parent as LibrarySource;
if (library != null) {
if (!ConfirmRemove (library, false, Selection.Count)) {
return;
}
ThreadAssist.SpawnFromMain (delegate {
library.RemoveTracks (source.TrackModel as DatabaseTrackListModel, Selection);
});
}
}
}
private void OnOpenContainingFolder (object o, EventArgs args)
{
var source = ActiveSource as ITrackModelSource;
if (source == null || source.TrackModel == null)
return;
var items = SelectedTracks;
if (items == null || items.Count != 1) {
Log.Error ("Could not open containing folder");
return;
}
foreach (var track in items) {
var path = System.IO.Path.GetDirectoryName (track.Uri.AbsolutePath);
if (Banshee.IO.Directory.Exists (path)) {
System.Diagnostics.Process.Start (path);
return;
}
}
var md = new HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
DialogFlags.DestroyWithParent, MessageType.Warning,
ButtonsType.None, Catalog.GetString ("The folder could not be found."),
Catalog.GetString ("Please check that the track's location is accessible by the system.")
);
md.AddButton ("gtk-ok", ResponseType.Ok, true);
try {
md.Run ();
} finally {
md.Destroy ();
}
}
private void OnDeleteTracksFromDrive (object o, EventArgs args)
{
ITrackModelSource source = ActiveSource as ITrackModelSource;
if (!ConfirmRemove (source, true, Selection.Count))
return;
if (source != null && source.CanDeleteTracks) {
source.DeleteTracks (Selection);
}
}
// FIXME filter
private void OnRateTracks (object o, EventArgs args)
{
ThreadAssist.SpawnFromMain (delegate {
(ActiveSource as DatabaseSource).RateSelectedTracks (rating_proxy.LastRating);
});
}
private void OnSearchForSameArtist (object o, EventArgs args)
{
if (current_source != null) {
foreach (TrackInfo track in current_source.TrackModel.SelectedItems) {
if (!String.IsNullOrEmpty (track.ArtistName)) {
ActiveSource.FilterQuery = BansheeQuery.ArtistField.ToTermString (":", track.ArtistName);
}
break;
}
}
}
private void OnSearchForSameAlbum (object o, EventArgs args)
{
if (current_source != null) {
foreach (TrackInfo track in current_source.TrackModel.SelectedItems) {
if (!String.IsNullOrEmpty (track.AlbumTitle)) {
ActiveSource.FilterQuery = BansheeQuery.AlbumField.ToTermString (":", track.AlbumTitle);
}
break;
}
}
}
#endregion
private static bool ConfirmRemove (ITrackModelSource source, bool delete, int selCount)
{
if (!source.ConfirmRemoveTracks) {
return true;
}
bool ret = false;
string header = null;
string message = null;
string button_label = null;
if (delete) {
header = String.Format (
Catalog.GetPluralString (
"Are you sure you want to permanently delete this item?",
"Are you sure you want to permanently delete the selected {0} items?", selCount
), selCount
);
message = Catalog.GetString ("If you delete the selection, it will be permanently lost.");
button_label = "gtk-delete";
} else {
header = String.Format (Catalog.GetString ("Remove selection from {0}?"), source.Name);
message = String.Format (
Catalog.GetPluralString (
"Are you sure you want to remove the selected item from your {1}?",
"Are you sure you want to remove the selected {0} items from your {1}?", selCount
), selCount, source.GenericName
);
button_label = "gtk-remove";
}
HigMessageDialog md = new HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
DialogFlags.DestroyWithParent, delete ? MessageType.Warning : MessageType.Question,
ButtonsType.None, header, message
);
// Delete from Disk defaults to Cancel and the others to OK/Confirm.
md.AddButton ("gtk-cancel", ResponseType.No, delete);
md.AddButton (button_label, ResponseType.Yes, !delete);
try {
if (md.Run () == (int) ResponseType.Yes) {
ret = true;
}
} finally {
md.Destroy ();
}
return ret;
}
public static bool ConfirmRemove (string header)
{
string message = Catalog.GetString ("Are you sure you want to continue?");
bool remove_tracks = false;
ThreadAssist.BlockingProxyToMain (() => {
var md = new HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
DialogFlags.DestroyWithParent, MessageType.Warning,
ButtonsType.None, header, message
);
md.AddButton ("gtk-cancel", ResponseType.No, true);
md.AddButton (Catalog.GetString ("Remove tracks"), ResponseType.Yes, false);
try {
if (md.Run () == (int) ResponseType.Yes) {
remove_tracks = true;
}
} finally {
md.Destroy ();
}
});
return remove_tracks;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace System.ServiceModel.Dispatcher
{
internal class ImmutableDispatchRuntime
{
readonly private int _correlationCount;
readonly private ConcurrencyBehavior _concurrency;
readonly private IDemuxer _demuxer;
readonly private ErrorBehavior _error;
private readonly bool _enableFaults;
private InstanceBehavior _instance;
private readonly bool _manualAddressing;
private readonly ThreadBehavior _thread;
private readonly bool _validateMustUnderstand;
private readonly bool _sendAsynchronously;
private readonly MessageRpcProcessor _processMessage1;
private readonly MessageRpcProcessor _processMessage11;
private readonly MessageRpcProcessor _processMessage2;
private readonly MessageRpcProcessor _processMessage3;
private readonly MessageRpcProcessor _processMessage31;
private readonly MessageRpcProcessor _processMessage4;
private readonly MessageRpcProcessor _processMessage41;
private readonly MessageRpcProcessor _processMessage5;
private readonly MessageRpcProcessor _processMessage6;
private readonly MessageRpcProcessor _processMessage7;
private readonly MessageRpcProcessor _processMessage8;
private readonly MessageRpcProcessor _processMessage9;
private readonly MessageRpcProcessor _processMessageCleanup;
private readonly MessageRpcProcessor _processMessageCleanupError;
private static AsyncCallback s_onReplyCompleted = Fx.ThunkCallback(new AsyncCallback(OnReplyCompletedCallback));
internal ImmutableDispatchRuntime(DispatchRuntime dispatch)
{
_concurrency = new ConcurrencyBehavior(dispatch);
_error = new ErrorBehavior(dispatch.ChannelDispatcher);
_enableFaults = dispatch.EnableFaults;
_instance = new InstanceBehavior(dispatch, this);
_manualAddressing = dispatch.ManualAddressing;
_thread = new ThreadBehavior(dispatch);
_sendAsynchronously = dispatch.ChannelDispatcher.SendAsynchronously;
_correlationCount = dispatch.MaxParameterInspectors;
DispatchOperationRuntime unhandled = new DispatchOperationRuntime(dispatch.UnhandledDispatchOperation, this);
ActionDemuxer demuxer = new ActionDemuxer();
for (int i = 0; i < dispatch.Operations.Count; i++)
{
DispatchOperation operation = dispatch.Operations[i];
DispatchOperationRuntime operationRuntime = new DispatchOperationRuntime(operation, this);
demuxer.Add(operation.Action, operationRuntime);
}
demuxer.SetUnhandled(unhandled);
_demuxer = demuxer;
_processMessage1 = ProcessMessage1;
_processMessage11 = ProcessMessage11;
_processMessage2 = ProcessMessage2;
_processMessage3 = ProcessMessage3;
_processMessage31 = ProcessMessage31;
_processMessage4 = ProcessMessage4;
_processMessage41 = ProcessMessage41;
_processMessage5 = ProcessMessage5;
_processMessage6 = ProcessMessage6;
_processMessage7 = ProcessMessage7;
_processMessage8 = ProcessMessage8;
_processMessage9 = ProcessMessage9;
_processMessageCleanup = ProcessMessageCleanup;
_processMessageCleanupError = ProcessMessageCleanupError;
}
internal int CorrelationCount
{
get { return _correlationCount; }
}
internal bool EnableFaults
{
get { return _enableFaults; }
}
internal bool ManualAddressing
{
get { return _manualAddressing; }
}
internal bool ValidateMustUnderstand
{
get { return _validateMustUnderstand; }
}
internal void AfterReceiveRequest(ref MessageRpc rpc)
{
// IDispatchMessageInspector would normally be called here. That interface isn't in contract.
}
private void Reply(ref MessageRpc rpc)
{
rpc.RequestContextThrewOnReply = true;
rpc.SuccessfullySendReply = false;
try
{
rpc.RequestContext.Reply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime());
rpc.RequestContextThrewOnReply = false;
rpc.SuccessfullySendReply = true;
if (WcfEventSource.Instance.DispatchMessageStopIsEnabled())
{
WcfEventSource.Instance.DispatchMessageStop(rpc.EventTraceActivity);
}
}
catch (CommunicationException e)
{
_error.HandleError(e);
}
catch (TimeoutException e)
{
_error.HandleError(e);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!_error.HandleError(e))
{
rpc.RequestContextThrewOnReply = true;
rpc.CanSendReply = false;
}
}
}
private void BeginReply(ref MessageRpc rpc)
{
bool success = false;
try
{
IResumeMessageRpc resume = rpc.Pause();
rpc.AsyncResult = rpc.RequestContext.BeginReply(rpc.Reply, rpc.ReplyTimeoutHelper.RemainingTime(),
s_onReplyCompleted, resume);
success = true;
if (rpc.AsyncResult.CompletedSynchronously)
{
rpc.UnPause();
}
}
catch (CommunicationException e)
{
_error.HandleError(e);
}
catch (TimeoutException e)
{
_error.HandleError(e);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (!_error.HandleError(e))
{
rpc.RequestContextThrewOnReply = true;
rpc.CanSendReply = false;
}
}
finally
{
if (!success)
{
rpc.UnPause();
}
}
}
internal bool Dispatch(ref MessageRpc rpc, bool isOperationContextSet)
{
rpc.ErrorProcessor = _processMessage8;
rpc.NextProcessor = _processMessage1;
return rpc.Process(isOperationContextSet);
}
private bool EndReply(ref MessageRpc rpc)
{
bool success = false;
try
{
rpc.RequestContext.EndReply(rpc.AsyncResult);
rpc.RequestContextThrewOnReply = false;
success = true;
if (WcfEventSource.Instance.DispatchMessageStopIsEnabled())
{
WcfEventSource.Instance.DispatchMessageStop(rpc.EventTraceActivity);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
return success;
}
private void SetActivityIdOnThread(ref MessageRpc rpc)
{
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
{
// Propogate the ActivityId to the service operation
EventTraceActivityHelper.SetOnThread(rpc.EventTraceActivity);
}
}
private void TransferChannelFromPendingList(ref MessageRpc rpc)
{
if (rpc.Channel.IsPending)
{
rpc.Channel.IsPending = false;
ChannelDispatcher channelDispatcher = rpc.Channel.ChannelDispatcher;
IInstanceContextProvider provider = _instance.InstanceContextProvider;
if (!InstanceContextProviderBase.IsProviderSessionful(provider) &&
!InstanceContextProviderBase.IsProviderSingleton(provider))
{
IChannel proxy = rpc.Channel.Proxy as IChannel;
if (!rpc.InstanceContext.IncomingChannels.Contains(proxy))
{
channelDispatcher.Channels.Add(proxy);
}
}
channelDispatcher.PendingChannels.Remove(rpc.Channel.Binder.Channel);
}
}
private void AddMessageProperties(Message message, OperationContext context, ServiceChannel replyChannel)
{
if (context.InternalServiceChannel == replyChannel)
{
if (context.HasOutgoingMessageHeaders)
{
message.Headers.CopyHeadersFrom(context.OutgoingMessageHeaders);
}
if (context.HasOutgoingMessageProperties)
{
message.Properties.MergeProperties(context.OutgoingMessageProperties);
}
}
}
private static void OnReplyCompletedCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
IResumeMessageRpc resume = result.AsyncState as IResumeMessageRpc;
if (resume == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SRServiceModel.SFxInvalidAsyncResultState0);
}
resume.Resume(result);
}
private void PrepareReply(ref MessageRpc rpc)
{
RequestContext context = rpc.OperationContext.RequestContext;
Exception exception = null;
bool thereIsAnUnhandledException = false;
if (!rpc.Operation.IsOneWay)
{
if ((context != null) && (rpc.Reply != null))
{
try
{
rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
thereIsAnUnhandledException = !_error.HandleError(e);
exception = e;
}
}
}
if (rpc.Operation.IsOneWay)
{
rpc.CanSendReply = false;
}
if (!rpc.Operation.IsOneWay && (context != null) && (rpc.Reply != null))
{
if (exception != null)
{
// We don't call ProvideFault again, since we have already passed the
// point where SFx addresses the reply, and it is reasonable for
// ProvideFault to expect that SFx will address the reply. Instead
// we always just do 'internal server error' processing.
rpc.Error = exception;
_error.ProvideOnlyFaultOfLastResort(ref rpc);
try
{
rpc.CanSendReply = PrepareAndAddressReply(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
}
else if ((exception != null) && thereIsAnUnhandledException)
{
rpc.Abort();
}
}
private bool PrepareAndAddressReply(ref MessageRpc rpc)
{
bool canSendReply = true;
if (!_manualAddressing)
{
if (!object.ReferenceEquals(rpc.RequestID, null))
{
System.ServiceModel.Channels.RequestReplyCorrelator.PrepareReply(rpc.Reply, rpc.RequestID);
}
if (!rpc.Channel.HasSession)
{
canSendReply = System.ServiceModel.Channels.RequestReplyCorrelator.AddressReply(rpc.Reply, rpc.ReplyToInfo);
}
}
AddMessageProperties(rpc.Reply, rpc.OperationContext, rpc.Channel);
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && rpc.EventTraceActivity != null)
{
rpc.Reply.Properties[EventTraceActivity.Name] = rpc.EventTraceActivity;
}
return canSendReply;
}
internal DispatchOperationRuntime GetOperation(ref Message message)
{
return _demuxer.GetOperation(ref message);
}
private interface IDemuxer
{
DispatchOperationRuntime GetOperation(ref Message request);
}
internal bool IsConcurrent(ref MessageRpc rpc)
{
return _concurrency.IsConcurrent(ref rpc);
}
internal void ProcessMessage1(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage11;
if (!rpc.IsPaused)
{
ProcessMessage11(ref rpc);
}
}
internal void ProcessMessage11(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage2;
if (rpc.Operation.IsOneWay)
{
rpc.RequestContext.Reply(null);
rpc.OperationContext.RequestContext = null;
}
else
{
if (!rpc.Channel.IsReplyChannel &&
((object)rpc.RequestID == null) &&
(rpc.Operation.Action != MessageHeaders.WildcardAction))
{
CommunicationException error = new CommunicationException(SRServiceModel.SFxOneWayMessageToTwoWayMethod0);
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
if (!_manualAddressing)
{
EndpointAddress replyTo = rpc.ReplyToInfo.ReplyTo;
if (replyTo != null && replyTo.IsNone && rpc.Channel.IsReplyChannel)
{
CommunicationException error = new CommunicationException(SRServiceModel.SFxRequestReplyNone);
throw TraceUtility.ThrowHelperError(error, rpc.Request);
}
}
}
if (_concurrency.IsConcurrent(ref rpc))
{
rpc.Channel.IncrementActivity();
rpc.SuccessfullyIncrementedActivity = true;
}
_instance.EnsureInstanceContext(ref rpc);
this.TransferChannelFromPendingList(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage2(ref rpc);
}
}
private void ProcessMessage2(ref MessageRpc rpc)
{
// Run dispatch message inspectors
rpc.NextProcessor = _processMessage3;
this.AfterReceiveRequest(ref rpc);
_concurrency.LockInstance(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage3(ref rpc);
}
}
private void ProcessMessage3(ref MessageRpc rpc)
{
// Manage transactions, can likely go away
rpc.NextProcessor = _processMessage31;
rpc.SuccessfullyLockedInstance = true;
if (!rpc.IsPaused)
{
this.ProcessMessage31(ref rpc);
}
}
private void ProcessMessage31(ref MessageRpc rpc)
{
// More transaction stuff, can likely go away
rpc.NextProcessor = _processMessage4;
if (!rpc.IsPaused)
{
this.ProcessMessage4(ref rpc);
}
}
private void ProcessMessage4(ref MessageRpc rpc)
{
// Bind request to synchronization context if needed
rpc.NextProcessor = _processMessage41;
try
{
_thread.BindThread(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
}
if (!rpc.IsPaused)
{
this.ProcessMessage41(ref rpc);
}
}
private void ProcessMessage41(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage5;
// This needs to happen after LockInstance--LockInstance guarantees
// in-order delivery, so we can't receive the next message until we
// have acquired the lock.
//
// This also needs to happen after BindThread, since
// running on UI thread should guarantee in-order delivery if
// the SynchronizationContext is single threaded.
if (_concurrency.IsConcurrent(ref rpc))
{
rpc.EnsureReceive();
}
_instance.EnsureServiceInstance(ref rpc);
if (!rpc.IsPaused)
{
this.ProcessMessage5(ref rpc);
}
}
private void ProcessMessage5(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage6;
bool success = false;
try
{
// If async call completes in sync, it tells us through the gate below
rpc.PrepareInvokeContinueGate();
SetActivityIdOnThread(ref rpc);
rpc.Operation.InvokeBegin(ref rpc);
success = true;
}
finally
{
try
{
if (rpc.IsPaused)
{
// Check if the callback produced the async result and set it back on the RPC on this stack
// and proceed only if the gate was signaled by the callback and completed synchronously
if (rpc.UnlockInvokeContinueGate(out rpc.AsyncResult))
{
rpc.UnPause();
}
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (success && !rpc.IsPaused)
{
throw;
}
_error.HandleError(e);
}
}
// Proceed if rpc is unpaused and invoke begin was successful.
if (!rpc.IsPaused)
{
this.ProcessMessage6(ref rpc);
}
}
private void ProcessMessage6(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage7;
try
{
_thread.BindEndThread(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(e.Message, e);
}
if (!rpc.IsPaused)
{
this.ProcessMessage7(ref rpc);
}
}
private void ProcessMessage7(ref MessageRpc rpc)
{
rpc.NextProcessor = null;
rpc.Operation.InvokeEnd(ref rpc);
// this never pauses
this.ProcessMessage8(ref rpc);
}
private void ProcessMessage8(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessage9;
try
{
_error.ProvideMessageFault(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
this.PrepareReply(ref rpc);
if (rpc.CanSendReply)
{
rpc.ReplyTimeoutHelper = new TimeoutHelper(rpc.Channel.OperationTimeout);
}
if (!rpc.IsPaused)
{
this.ProcessMessage9(ref rpc);
}
}
private void ProcessMessage9(ref MessageRpc rpc)
{
rpc.NextProcessor = _processMessageCleanup;
if (rpc.CanSendReply)
{
if (rpc.Reply != null)
{
TraceUtility.MessageFlowAtMessageSent(rpc.Reply, rpc.EventTraceActivity);
}
if (_sendAsynchronously)
{
this.BeginReply(ref rpc);
}
else
{
this.Reply(ref rpc);
}
}
if (!rpc.IsPaused)
{
this.ProcessMessageCleanup(ref rpc);
}
}
private void ProcessMessageCleanup(ref MessageRpc rpc)
{
Fx.Assert(
!object.ReferenceEquals(rpc.ErrorProcessor, _processMessageCleanupError),
"ProcessMessageCleanup run twice on the same MessageRpc!");
rpc.ErrorProcessor = _processMessageCleanupError;
bool replyWasSent = false;
if (rpc.CanSendReply)
{
if (_sendAsynchronously)
{
replyWasSent = this.EndReply(ref rpc);
}
else
{
replyWasSent = rpc.SuccessfullySendReply;
}
}
try
{
try
{
if (rpc.DidDeserializeRequestBody)
{
rpc.Request.Close();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
rpc.DisposeParameters(false); //Dispose all input/output/return parameters
if (rpc.FaultInfo.IsConsideredUnhandled)
{
if (!replyWasSent)
{
rpc.AbortRequestContext();
rpc.AbortChannel();
}
else
{
rpc.CloseRequestContext();
rpc.CloseChannel();
}
rpc.AbortInstanceContext();
}
else
{
if (rpc.RequestContextThrewOnReply)
{
rpc.AbortRequestContext();
}
else
{
rpc.CloseRequestContext();
}
}
if ((rpc.Reply != null) && (rpc.Reply != rpc.ReturnParameter))
{
try
{
rpc.Reply.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
if ((rpc.FaultInfo.Fault != null) && (rpc.FaultInfo.Fault.State != MessageState.Closed))
{
// maybe ProvideFault gave a Message, but then BeforeSendReply replaced it
// in that case, we need to close the one from ProvideFault
try
{
rpc.FaultInfo.Fault.Close();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
try
{
rpc.OperationContext.FireOperationCompleted();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
_instance.AfterReply(ref rpc, _error);
if (rpc.SuccessfullyLockedInstance)
{
try
{
_concurrency.UnlockInstance(ref rpc);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
Fx.Assert("Exceptions should be caught by callee");
rpc.InstanceContext.FaultInternal();
_error.HandleError(e);
}
}
if (rpc.SuccessfullyIncrementedActivity)
{
try
{
rpc.Channel.DecrementActivity();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
_error.HandleError(e);
}
}
}
finally
{
if (rpc.Activity != null && DiagnosticUtility.ShouldUseActivity)
{
rpc.Activity.Stop();
}
}
_error.HandleError(ref rpc);
}
private void ProcessMessageCleanupError(ref MessageRpc rpc)
{
_error.HandleError(ref rpc);
}
private class ActionDemuxer : IDemuxer
{
private readonly HybridDictionary _map;
private DispatchOperationRuntime _unhandled;
internal ActionDemuxer()
{
_map = new HybridDictionary();
}
internal void Add(string action, DispatchOperationRuntime operation)
{
if (_map.Contains(action))
{
DispatchOperationRuntime existingOperation = (DispatchOperationRuntime)_map[action];
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxActionDemuxerDuplicate, existingOperation.Name, operation.Name, action)));
}
_map.Add(action, operation);
}
internal void SetUnhandled(DispatchOperationRuntime operation)
{
_unhandled = operation;
}
public DispatchOperationRuntime GetOperation(ref Message request)
{
string action = request.Headers.Action;
if (action == null)
{
action = MessageHeaders.WildcardAction;
}
DispatchOperationRuntime operation = (DispatchOperationRuntime)_map[action];
if (operation != null)
{
return operation;
}
return _unhandled;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="EventLogEntry.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Diagnostics {
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Globalization;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>
/// <see cref='System.Diagnostics.EventLogEntry'/>
/// encapsulates a single record in the NT event log.
/// </para>
/// </devdoc>
[
ToolboxItem(false),
DesignTimeVisible(false),
Serializable,
]
public sealed class EventLogEntry : Component, ISerializable {
internal byte[] dataBuf;
internal int bufOffset;
private EventLogInternal owner;
private string category;
private string message;
// make sure only others in this package can create us
internal EventLogEntry(byte[] buf, int offset, EventLogInternal log) {
this.dataBuf = buf;
this.bufOffset = offset;
this.owner = log;
GC.SuppressFinalize(this);
}
/// <devdoc>
/// </devdoc>
/// <internalonly/>
private EventLogEntry(SerializationInfo info, StreamingContext context) {
dataBuf = (byte[])info.GetValue("DataBuffer", typeof(byte[]));
string logName = info.GetString("LogName");
string machineName = info.GetString("MachineName");
owner = new EventLogInternal(logName, machineName, "");
GC.SuppressFinalize(this);
}
/// <devdoc>
/// <para>
/// Gets the name of the computer on which this entry was generated.
///
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryMachineName)]
public string MachineName {
get {
// first skip over the source name
int pos = bufOffset + FieldOffsets.RAWDATA;
while (CharFrom(dataBuf, pos) != '\0')
pos += 2;
pos += 2;
char ch = CharFrom(dataBuf, pos);
StringBuilder buf = new StringBuilder();
while (ch != '\0') {
buf.Append(ch);
pos += 2;
ch = CharFrom(dataBuf, pos);
}
return buf.ToString();
}
}
/// <devdoc>
/// <para>
/// Gets the binary data associated with the entry.
///
/// </para>
/// </devdoc>
[
MonitoringDescription(SR.LogEntryData)
]
public byte[] Data {
get {
int dataLen = IntFrom(dataBuf, bufOffset + FieldOffsets.DATALENGTH);
byte[] data = new byte[dataLen];
Array.Copy(dataBuf, bufOffset + IntFrom(dataBuf, bufOffset + FieldOffsets.DATAOFFSET),
data, 0, dataLen);
return data;
}
}
/*
/// <summary>
/// <para>
/// Copies the binary data in the <see cref='System.Diagnostics.EventLogEntry.Data'/> member into an
/// array.
/// </para>
/// </summary>
/// <returns>
/// <para>
/// An array of type <see cref='System.Byte'/>.
/// </para>
/// </returns>
/// <keyword term=''/>
public Byte[] getDataBytes() {
Byte[] data = new Byte[rec.dataLength];
for (int i = 0; i < data.Length; i++)
data[i] = new Byte(rec.buf[i]);
return data;
}
*/
/// <devdoc>
/// <para>
/// Gets the index of this entry in the event
/// log.
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryIndex)]
public int Index {
get {
return IntFrom(dataBuf, bufOffset + FieldOffsets.RECORDNUMBER);
}
}
/// <devdoc>
/// <para>
/// Gets the text associated with the <see cref='System.Diagnostics.EventLogEntry.CategoryNumber'/> for this entry.
///
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryCategory)]
public string Category {
get {
if (category == null) {
string dllName = GetMessageLibraryNames("CategoryMessageFile");
string cat = owner.FormatMessageWrapper(dllName, (uint) CategoryNumber, null);
if (cat == null)
category = "(" + CategoryNumber.ToString(CultureInfo.CurrentCulture) + ")";
else
category = cat;
}
return category;
}
}
/// <devdoc>
/// <para>
/// Gets the application-specific category number for this entry
///
/// </para>
/// </devdoc>
[
MonitoringDescription(SR.LogEntryCategoryNumber)
]
public short CategoryNumber {
get {
return ShortFrom(dataBuf, bufOffset + FieldOffsets.EVENTCATEGORY);
}
}
/// <devdoc>
/// <para>
/// Gets the application-specific event indentifier of this entry.
///
/// </para>
/// </devdoc>
[
MonitoringDescription(SR.LogEntryEventID),
Obsolete("This property has been deprecated. Please use System.Diagnostics.EventLogEntry.InstanceId instead. http://go.microsoft.com/fwlink/?linkid=14202")
]
public int EventID {
get {
// Apparently the top 2 bits of this number are not
// always 0. Strip them so the number looks nice to the user.
// The problem is, if the user were to want to call FormatMessage(),
// they'd need these two bits.
return IntFrom(dataBuf, bufOffset + FieldOffsets.EVENTID) & 0x3FFFFFFF;
}
}
/// <devdoc>
/// <para>
///
/// Gets the type
/// of this entry.
///
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryEntryType)]
public EventLogEntryType EntryType {
get {
return(EventLogEntryType) ShortFrom(dataBuf, bufOffset + FieldOffsets.EVENTTYPE);
}
}
/// <devdoc>
/// <para>
/// Gets the localized message corresponding to this event entry.
///
/// </para>
/// </devdoc>
[
MonitoringDescription(SR.LogEntryMessage),
Editor("System.ComponentModel.Design.BinaryEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing)
]
public string Message {
get {
if (message == null) {
string dllNames = GetMessageLibraryNames("EventMessageFile");
int msgId = IntFrom(dataBuf, bufOffset + FieldOffsets.EVENTID);
string msg = owner.FormatMessageWrapper(dllNames, (uint)msgId, ReplacementStrings);
if (msg == null) {
StringBuilder msgBuf = new StringBuilder(SR.GetString(SR.MessageNotFormatted, msgId, Source));
string[] strings = ReplacementStrings;
for (int i = 0; i < strings.Length; i++) {
if (i != 0)
msgBuf.Append(", ");
msgBuf.Append("'");
msgBuf.Append(strings[i]);
msgBuf.Append("'");
}
msg = msgBuf.ToString();
}
else
msg = ReplaceMessageParameters( msg, ReplacementStrings );
message = msg;
}
return message;
}
}
/// <devdoc>
/// <para>
/// Gets the name of the application that generated this event.
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntrySource)]
public string Source {
get {
StringBuilder buf = new StringBuilder();
int pos = bufOffset + FieldOffsets.RAWDATA;
char ch = CharFrom(dataBuf, pos);
while (ch != '\0') {
buf.Append(ch);
pos += 2;
ch = CharFrom(dataBuf, pos);
}
return buf.ToString();
}
}
/// <devdoc>
/// <para>
/// Gets the replacement strings
/// associated with the entry.
///
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryReplacementStrings)]
public string[] ReplacementStrings {
get {
string[] strings = new string[ShortFrom(dataBuf, bufOffset + FieldOffsets.NUMSTRINGS)];
int i = 0;
int bufpos = bufOffset + IntFrom(dataBuf, bufOffset + FieldOffsets.STRINGOFFSET);
StringBuilder buf = new StringBuilder();
while (i < strings.Length) {
char ch = CharFrom(dataBuf, bufpos);
if (ch != '\0')
buf.Append(ch);
else {
strings[i] = buf.ToString();
i++;
buf = new StringBuilder();
}
bufpos += 2;
}
return strings;
}
}
[
MonitoringDescription(SR.LogEntryResourceId),
ComVisible(false)
]
public Int64 InstanceId {
get {
return (UInt32)IntFrom(dataBuf, bufOffset + FieldOffsets.EVENTID);
}
}
#if false
internal string StringsBuffer {
get {
StringBuilder buf = new StringBuilder();
int bufpos = bufOffset + IntFrom(dataBuf, bufOffset + FieldOffsets.STRINGOFFSET);
int i = 0;
int numStrings = ShortFrom(dataBuf, bufOffset + FieldOffsets.NUMSTRINGS);
while (i < numStrings) {
char ch = CharFrom(dataBuf, bufpos);
buf.Append(ch);
bufpos += 2;
if (ch == '\0')
i++;
}
return buf.ToString();
}
}
#endif
/// <devdoc>
/// <para>
/// Gets the time at which this event was generated, in local time.
///
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryTimeGenerated)]
public DateTime TimeGenerated {
get {
return beginningOfTime.AddSeconds(IntFrom(dataBuf, bufOffset + FieldOffsets.TIMEGENERATED)).ToLocalTime();
}
}
/// <devdoc>
/// <para>
/// Gets
/// the time at which this event was written to the log, in local time.
///
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryTimeWritten)]
public DateTime TimeWritten {
get {
return beginningOfTime.AddSeconds(IntFrom(dataBuf, bufOffset + FieldOffsets.TIMEWRITTEN)).ToLocalTime();
}
}
/// <devdoc>
/// <para>
/// Gets the name
/// of the user responsible for this event.
/// </para>
/// </devdoc>
[MonitoringDescription(SR.LogEntryUserName)]
public string UserName {
get {
int sidLen = IntFrom(dataBuf, bufOffset + FieldOffsets.USERSIDLENGTH);
if (sidLen == 0)
return null;
byte[] sid = new byte[sidLen];
Array.Copy(dataBuf, bufOffset + IntFrom(dataBuf, bufOffset + FieldOffsets.USERSIDOFFSET),
sid, 0, sid.Length);
int userNameLen = 256;
int domainNameLen = 256;
int sidNameUse = 0;
StringBuilder bufUserName = new StringBuilder(userNameLen);
StringBuilder bufDomainName = new StringBuilder(domainNameLen);
StringBuilder retUserName = new StringBuilder();
if(UnsafeNativeMethods.LookupAccountSid(MachineName, sid, bufUserName, ref userNameLen, bufDomainName, ref domainNameLen, ref sidNameUse) != 0) {
retUserName.Append(bufDomainName.ToString());
retUserName.Append("\\");
retUserName.Append(bufUserName.ToString());
}
return retUserName.ToString();
}
}
private char CharFrom(byte[] buf, int offset) {
return(char) ShortFrom(buf, offset);
}
/// <devdoc>
/// <para>
/// Performs a comparison between two event log entries.
///
/// </para>
/// </devdoc>
public bool Equals(EventLogEntry otherEntry) {
if (otherEntry == null)
return false;
int ourLen = IntFrom(dataBuf, bufOffset + FieldOffsets.LENGTH);
int theirLen = IntFrom(otherEntry.dataBuf, otherEntry.bufOffset + FieldOffsets.LENGTH);
if (ourLen != theirLen) {
return false;
}
int min = bufOffset;
int max = bufOffset + ourLen;
int j = otherEntry.bufOffset;
for (int i = min; i < max; i++, j++)
if (dataBuf[i] != otherEntry.dataBuf[j]) {
return false;
}
return true;
}
private int IntFrom(byte[] buf, int offset) {
// assumes Little Endian byte order.
return(unchecked((int)0xFF000000) & (buf[offset+3] << 24)) | (0xFF0000 & (buf[offset+2] << 16)) |
(0xFF00 & (buf[offset+1] << 8)) | (0xFF & (buf[offset]));
}
// Replacing parameters '%n' in formated message using 'ParameterMessageFile' registry key.
internal string ReplaceMessageParameters( String msg, string[] insertionStrings ) {
int percentIdx = msg.IndexOf('%');
if ( percentIdx < 0 )
return msg; // no '%' at all
int startCopyIdx = 0; // start idx of last [....] msg chars to copy
int msgLength = msg.Length;
StringBuilder buf = new StringBuilder();
string paramDLLNames = GetMessageLibraryNames("ParameterMessageFile");
while ( percentIdx >= 0 ) {
string param = null;
// Convert numeric string after '%' to paramMsgID number.
int lasNumIdx = percentIdx + 1;
while ( lasNumIdx < msgLength && Char.IsDigit(msg, lasNumIdx) )
lasNumIdx++;
uint paramMsgID = 0;
// If we can't parse it, leave the paramMsgID as zero. We'll skip the replacement and just put
// the %xxxx into the final message.
if (lasNumIdx != percentIdx + 1 )
UInt32.TryParse( msg.Substring(percentIdx + 1, lasNumIdx - percentIdx - 1), out paramMsgID);
if ( paramMsgID != 0 )
param = owner.FormatMessageWrapper( paramDLLNames, paramMsgID, insertionStrings);
if ( param != null ) {
if ( percentIdx > startCopyIdx )
buf.Append(msg, startCopyIdx, percentIdx - startCopyIdx); // original chars from msg
buf.Append(param);
startCopyIdx = lasNumIdx;
}
percentIdx = msg.IndexOf('%', percentIdx + 1);
}
if ( msgLength - startCopyIdx > 0 )
buf.Append(msg, startCopyIdx, msgLength - startCopyIdx); // last span of original msg
return buf.ToString();
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static RegistryKey GetSourceRegKey(string logName, string source, string machineName) {
RegistryKey eventKey = null;
RegistryKey logKey = null;
try {
eventKey = EventLog.GetEventLogRegKey(machineName, false);
if (eventKey == null)
return null;
if (logName == null)
logKey = eventKey.OpenSubKey("Application", /*writable*/false);
else
logKey = eventKey.OpenSubKey(logName, /*writable*/false);
if (logKey == null)
return null;
return logKey.OpenSubKey(source, /*writable*/false);
}
finally {
if (eventKey != null) eventKey.Close();
if (logKey != null) logKey.Close();
}
}
// ------------------------------------------------------------------------------
// Returns DLL names list.
// libRegKey can be: "EventMessageFile", "CategoryMessageFile", "ParameterMessageFile"
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private string GetMessageLibraryNames(string libRegKey ) {
// get the value stored in the registry
string fileName = null;
RegistryKey regKey = null;
try {
regKey = GetSourceRegKey(owner.Log, Source, owner.MachineName);
if (regKey != null) {
fileName = (string)regKey.GetValue(libRegKey);
}
}
finally {
if (regKey != null)
regKey.Close();
}
if (fileName == null)
return null;
// convert any absolute paths on a remote machine to use the \\MACHINENAME\DRIVELETTER$ shares
// so we pick up message dlls from the remote machine.
if (owner.MachineName != ".") {
string[] fileNames = fileName.Split(';');
StringBuilder result = new StringBuilder();
for (int i = 0; i < fileNames.Length; i++) {
if (fileNames[i].Length >= 2 && fileNames[i][1] == ':') {
result.Append(@"\\");
result.Append(owner.MachineName);
result.Append(@"\");
result.Append(fileNames[i][0]);
result.Append("$");
result.Append(fileNames[i], 2, fileNames[i].Length - 2);
result.Append(';');
}
}
if (result.Length == 0) {
return null;
} else {
return result.ToString(0, result.Length - 1); // Chop of last ";"
}
}
else {
return fileName;
}
}
private short ShortFrom(byte[] buf, int offset) {
// assumes little Endian byte order.
return(short) ((0xFF00 & (buf[offset+1] << 8)) | (0xFF & buf[offset]));
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Saves an entry as a stream of data.
/// </para>
/// </devdoc>
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
int len = IntFrom(dataBuf, bufOffset + FieldOffsets.LENGTH);
byte[] buf = new byte[len];
Array.Copy(dataBuf, bufOffset, buf, 0, len);
info.AddValue("DataBuffer", buf, typeof(byte[]));
info.AddValue("LogName", owner.Log);
info.AddValue("MachineName", owner.MachineName);
}
/// <devdoc>
/// Stores the offsets from the beginning of the record to fields within the record.
/// </devdoc>
private static class FieldOffsets {
/** int */
internal const int LENGTH = 0;
/** int */
internal const int RESERVED = 4;
/** int */
internal const int RECORDNUMBER = 8;
/** int */
internal const int TIMEGENERATED = 12;
/** int */
internal const int TIMEWRITTEN = 16;
/** int */
internal const int EVENTID = 20;
/** short */
internal const int EVENTTYPE = 24;
/** short */
internal const int NUMSTRINGS = 26;
/** short */
internal const int EVENTCATEGORY = 28;
/** short */
internal const int RESERVEDFLAGS = 30;
/** int */
internal const int CLOSINGRECORDNUMBER = 32;
/** int */
internal const int STRINGOFFSET = 36;
/** int */
internal const int USERSIDLENGTH = 40;
/** int */
internal const int USERSIDOFFSET = 44;
/** int */
internal const int DATALENGTH = 48;
/** int */
internal const int DATAOFFSET = 52;
/** bytes */
internal const int RAWDATA = 56;
}
// times in the struct are # seconds from midnight 1/1/1970.
private static readonly DateTime beginningOfTime = new DateTime(1970, 1, 1, 0, 0, 0);
// offsets in the struct are specified from the beginning, but we have to reference
// them from the beginning of the array. This is the size of the members before that.
private const int OFFSETFIXUP = 4+4+4+4+4+4+2+2+2+2+4+4+4+4+4+4;
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using Amazon.ElasticTranscoder;
using Amazon.ElasticTranscoder.Model;
namespace Amazon.ElasticTranscoder
{
/// <summary>
/// Interface for accessing AmazonElasticTranscoder.
///
/// AWS Elastic Transcoder Service <para>The AWS Elastic Transcoder Service.</para>
/// </summary>
public interface AmazonElasticTranscoder : IDisposable
{
#region UpdatePipelineStatus
/// <summary>
/// <para>The UpdatePipelineStatus operation pauses or reactivates a pipeline, so that the pipeline stops or restarts the processing of
/// jobs.</para> <para>Changing the pipeline status is useful if you want to cancel one or more jobs. You can't cancel jobs after Elastic
/// Transcoder has started processing them; if you pause the pipeline to which you submitted the jobs, you have more time to get the job IDs for
/// the jobs that you want to cancel, and to send a CancelJob request. </para>
/// </summary>
///
/// <param name="updatePipelineStatusRequest">Container for the necessary parameters to execute the UpdatePipelineStatus service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the UpdatePipelineStatus service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="ResourceInUseException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
UpdatePipelineStatusResponse UpdatePipelineStatus(UpdatePipelineStatusRequest updatePipelineStatusRequest);
/// <summary>
/// Initiates the asynchronous execution of the UpdatePipelineStatus operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.UpdatePipelineStatus"/>
/// </summary>
///
/// <param name="updatePipelineStatusRequest">Container for the necessary parameters to execute the UpdatePipelineStatus operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndUpdatePipelineStatus operation.</returns>
IAsyncResult BeginUpdatePipelineStatus(UpdatePipelineStatusRequest updatePipelineStatusRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdatePipelineStatus operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.UpdatePipelineStatus"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdatePipelineStatus.</param>
///
/// <returns>Returns a UpdatePipelineStatusResult from AmazonElasticTranscoder.</returns>
UpdatePipelineStatusResponse EndUpdatePipelineStatus(IAsyncResult asyncResult);
#endregion
#region UpdatePipelineNotifications
/// <summary>
/// <para>With the UpdatePipelineNotifications operation, you can update Amazon Simple Notification Service (Amazon SNS) notifications for a
/// pipeline.</para> <para>When you update notifications for a pipeline, Elastic Transcoder returns the values that you specified in the
/// request.</para>
/// </summary>
///
/// <param name="updatePipelineNotificationsRequest">Container for the necessary parameters to execute the UpdatePipelineNotifications service
/// method on AmazonElasticTranscoder.</param>
///
/// <returns>The response from the UpdatePipelineNotifications service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="ResourceInUseException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
UpdatePipelineNotificationsResponse UpdatePipelineNotifications(UpdatePipelineNotificationsRequest updatePipelineNotificationsRequest);
/// <summary>
/// Initiates the asynchronous execution of the UpdatePipelineNotifications operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.UpdatePipelineNotifications"/>
/// </summary>
///
/// <param name="updatePipelineNotificationsRequest">Container for the necessary parameters to execute the UpdatePipelineNotifications operation
/// on AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndUpdatePipelineNotifications operation.</returns>
IAsyncResult BeginUpdatePipelineNotifications(UpdatePipelineNotificationsRequest updatePipelineNotificationsRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdatePipelineNotifications operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.UpdatePipelineNotifications"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdatePipelineNotifications.</param>
///
/// <returns>Returns a UpdatePipelineNotificationsResult from AmazonElasticTranscoder.</returns>
UpdatePipelineNotificationsResponse EndUpdatePipelineNotifications(IAsyncResult asyncResult);
#endregion
#region ReadJob
/// <summary>
/// <para>The ReadJob operation returns detailed information about a job.</para>
/// </summary>
///
/// <param name="readJobRequest">Container for the necessary parameters to execute the ReadJob service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the ReadJob service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ReadJobResponse ReadJob(ReadJobRequest readJobRequest);
/// <summary>
/// Initiates the asynchronous execution of the ReadJob operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ReadJob"/>
/// </summary>
///
/// <param name="readJobRequest">Container for the necessary parameters to execute the ReadJob operation on AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndReadJob
/// operation.</returns>
IAsyncResult BeginReadJob(ReadJobRequest readJobRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ReadJob operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ReadJob"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginReadJob.</param>
///
/// <returns>Returns a ReadJobResult from AmazonElasticTranscoder.</returns>
ReadJobResponse EndReadJob(IAsyncResult asyncResult);
#endregion
#region ListJobsByStatus
/// <summary>
/// <para>The ListJobsByStatus operation gets a list of jobs that have a specified status. The response body contains one element for each job
/// that satisfies the search criteria.</para>
/// </summary>
///
/// <param name="listJobsByStatusRequest">Container for the necessary parameters to execute the ListJobsByStatus service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the ListJobsByStatus service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ListJobsByStatusResponse ListJobsByStatus(ListJobsByStatusRequest listJobsByStatusRequest);
/// <summary>
/// Initiates the asynchronous execution of the ListJobsByStatus operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListJobsByStatus"/>
/// </summary>
///
/// <param name="listJobsByStatusRequest">Container for the necessary parameters to execute the ListJobsByStatus operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListJobsByStatus
/// operation.</returns>
IAsyncResult BeginListJobsByStatus(ListJobsByStatusRequest listJobsByStatusRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListJobsByStatus operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListJobsByStatus"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListJobsByStatus.</param>
///
/// <returns>Returns a ListJobsByStatusResult from AmazonElasticTranscoder.</returns>
ListJobsByStatusResponse EndListJobsByStatus(IAsyncResult asyncResult);
#endregion
#region ReadPreset
/// <summary>
/// <para>The ReadPreset operation gets detailed information about a preset.</para>
/// </summary>
///
/// <param name="readPresetRequest">Container for the necessary parameters to execute the ReadPreset service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the ReadPreset service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ReadPresetResponse ReadPreset(ReadPresetRequest readPresetRequest);
/// <summary>
/// Initiates the asynchronous execution of the ReadPreset operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ReadPreset"/>
/// </summary>
///
/// <param name="readPresetRequest">Container for the necessary parameters to execute the ReadPreset operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndReadPreset
/// operation.</returns>
IAsyncResult BeginReadPreset(ReadPresetRequest readPresetRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ReadPreset operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ReadPreset"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginReadPreset.</param>
///
/// <returns>Returns a ReadPresetResult from AmazonElasticTranscoder.</returns>
ReadPresetResponse EndReadPreset(IAsyncResult asyncResult);
/// <summary>
/// <para>The ReadPreset operation gets detailed information about a preset.</para>
/// </summary>
///
/// <returns>The response from the ReadPreset service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ReadPresetResponse ReadPreset();
#endregion
#region CreatePipeline
/// <summary>
/// <para>The CreatePipeline operation creates a pipeline with settings that you specify.</para>
/// </summary>
///
/// <param name="createPipelineRequest">Container for the necessary parameters to execute the CreatePipeline service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the CreatePipeline service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="AccessDeniedException"/>
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="LimitExceededException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
CreatePipelineResponse CreatePipeline(CreatePipelineRequest createPipelineRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreatePipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CreatePipeline"/>
/// </summary>
///
/// <param name="createPipelineRequest">Container for the necessary parameters to execute the CreatePipeline operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreatePipeline
/// operation.</returns>
IAsyncResult BeginCreatePipeline(CreatePipelineRequest createPipelineRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreatePipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CreatePipeline"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreatePipeline.</param>
///
/// <returns>Returns a CreatePipelineResult from AmazonElasticTranscoder.</returns>
CreatePipelineResponse EndCreatePipeline(IAsyncResult asyncResult);
#endregion
#region CancelJob
/// <summary>
/// <para>The CancelJob operation cancels an unfinished job.</para> <para><b>NOTE:</b>You can only cancel a job that has a status of Submitted.
/// To prevent a pipeline from starting to process a job while you're getting the job identifier, use UpdatePipelineStatus to temporarily pause
/// the pipeline.</para>
/// </summary>
///
/// <param name="cancelJobRequest">Container for the necessary parameters to execute the CancelJob service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the CancelJob service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="ResourceInUseException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
CancelJobResponse CancelJob(CancelJobRequest cancelJobRequest);
/// <summary>
/// Initiates the asynchronous execution of the CancelJob operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CancelJob"/>
/// </summary>
///
/// <param name="cancelJobRequest">Container for the necessary parameters to execute the CancelJob operation on AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCancelJob
/// operation.</returns>
IAsyncResult BeginCancelJob(CancelJobRequest cancelJobRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CancelJob operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CancelJob"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCancelJob.</param>
///
/// <returns>Returns a CancelJobResult from AmazonElasticTranscoder.</returns>
CancelJobResponse EndCancelJob(IAsyncResult asyncResult);
#endregion
#region UpdatePipeline
/// <summary>
/// </summary>
///
/// <param name="updatePipelineRequest">Container for the necessary parameters to execute the UpdatePipeline service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the UpdatePipeline service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="AccessDeniedException"/>
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="ResourceInUseException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
UpdatePipelineResponse UpdatePipeline(UpdatePipelineRequest updatePipelineRequest);
/// <summary>
/// Initiates the asynchronous execution of the UpdatePipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.UpdatePipeline"/>
/// </summary>
///
/// <param name="updatePipelineRequest">Container for the necessary parameters to execute the UpdatePipeline operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdatePipeline
/// operation.</returns>
IAsyncResult BeginUpdatePipeline(UpdatePipelineRequest updatePipelineRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdatePipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.UpdatePipeline"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdatePipeline.</param>
///
/// <returns>Returns a UpdatePipelineResult from AmazonElasticTranscoder.</returns>
UpdatePipelineResponse EndUpdatePipeline(IAsyncResult asyncResult);
#endregion
#region ListPresets
/// <summary>
/// <para>The ListPresets operation gets a list of the default presets included with Elastic Transcoder and the presets that you've added in an
/// AWS region.</para>
/// </summary>
///
/// <param name="listPresetsRequest">Container for the necessary parameters to execute the ListPresets service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the ListPresets service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ListPresetsResponse ListPresets(ListPresetsRequest listPresetsRequest);
/// <summary>
/// Initiates the asynchronous execution of the ListPresets operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListPresets"/>
/// </summary>
///
/// <param name="listPresetsRequest">Container for the necessary parameters to execute the ListPresets operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListPresets
/// operation.</returns>
IAsyncResult BeginListPresets(ListPresetsRequest listPresetsRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListPresets operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListPresets"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListPresets.</param>
///
/// <returns>Returns a ListPresetsResult from AmazonElasticTranscoder.</returns>
ListPresetsResponse EndListPresets(IAsyncResult asyncResult);
/// <summary>
/// <para>The ListPresets operation gets a list of the default presets included with Elastic Transcoder and the presets that you've added in an
/// AWS region.</para>
/// </summary>
///
/// <returns>The response from the ListPresets service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ListPresetsResponse ListPresets();
#endregion
#region DeletePipeline
/// <summary>
/// <para>The DeletePipeline operation removes a pipeline.</para> <para> You can only delete a pipeline that has never been used or that is not
/// currently in use (doesn't contain any active jobs). If the pipeline is currently in use, <c>DeletePipeline</c> returns an error. </para>
/// </summary>
///
/// <param name="deletePipelineRequest">Container for the necessary parameters to execute the DeletePipeline service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the DeletePipeline service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="ResourceInUseException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
DeletePipelineResponse DeletePipeline(DeletePipelineRequest deletePipelineRequest);
/// <summary>
/// Initiates the asynchronous execution of the DeletePipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.DeletePipeline"/>
/// </summary>
///
/// <param name="deletePipelineRequest">Container for the necessary parameters to execute the DeletePipeline operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeletePipeline
/// operation.</returns>
IAsyncResult BeginDeletePipeline(DeletePipelineRequest deletePipelineRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeletePipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.DeletePipeline"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeletePipeline.</param>
///
/// <returns>Returns a DeletePipelineResult from AmazonElasticTranscoder.</returns>
DeletePipelineResponse EndDeletePipeline(IAsyncResult asyncResult);
#endregion
#region TestRole
/// <summary>
/// <para>The TestRole operation tests the IAM role used to create the pipeline.</para> <para>The <c>TestRole</c> action lets you determine
/// whether the IAM role you are using has sufficient permissions to let Elastic Transcoder perform tasks associated with the transcoding
/// process. The action attempts to assume the specified IAM role, checks read access to the input and output buckets, and tries to send a test
/// notification to Amazon SNS topics that you specify.</para>
/// </summary>
///
/// <param name="testRoleRequest">Container for the necessary parameters to execute the TestRole service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the TestRole service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
TestRoleResponse TestRole(TestRoleRequest testRoleRequest);
/// <summary>
/// Initiates the asynchronous execution of the TestRole operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.TestRole"/>
/// </summary>
///
/// <param name="testRoleRequest">Container for the necessary parameters to execute the TestRole operation on AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTestRole
/// operation.</returns>
IAsyncResult BeginTestRole(TestRoleRequest testRoleRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the TestRole operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.TestRole"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTestRole.</param>
///
/// <returns>Returns a TestRoleResult from AmazonElasticTranscoder.</returns>
TestRoleResponse EndTestRole(IAsyncResult asyncResult);
#endregion
#region ListPipelines
/// <summary>
/// <para>The ListPipelines operation gets a list of the pipelines associated with the current AWS account.</para>
/// </summary>
///
/// <param name="listPipelinesRequest">Container for the necessary parameters to execute the ListPipelines service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the ListPipelines service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ListPipelinesResponse ListPipelines(ListPipelinesRequest listPipelinesRequest);
/// <summary>
/// Initiates the asynchronous execution of the ListPipelines operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListPipelines"/>
/// </summary>
///
/// <param name="listPipelinesRequest">Container for the necessary parameters to execute the ListPipelines operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListPipelines
/// operation.</returns>
IAsyncResult BeginListPipelines(ListPipelinesRequest listPipelinesRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListPipelines operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListPipelines"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListPipelines.</param>
///
/// <returns>Returns a ListPipelinesResult from AmazonElasticTranscoder.</returns>
ListPipelinesResponse EndListPipelines(IAsyncResult asyncResult);
/// <summary>
/// <para>The ListPipelines operation gets a list of the pipelines associated with the current AWS account.</para>
/// </summary>
///
/// <returns>The response from the ListPipelines service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ListPipelinesResponse ListPipelines();
#endregion
#region ReadPipeline
/// <summary>
/// <para>The ReadPipeline operation gets detailed information about a pipeline.</para>
/// </summary>
///
/// <param name="readPipelineRequest">Container for the necessary parameters to execute the ReadPipeline service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the ReadPipeline service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ReadPipelineResponse ReadPipeline(ReadPipelineRequest readPipelineRequest);
/// <summary>
/// Initiates the asynchronous execution of the ReadPipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ReadPipeline"/>
/// </summary>
///
/// <param name="readPipelineRequest">Container for the necessary parameters to execute the ReadPipeline operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndReadPipeline
/// operation.</returns>
IAsyncResult BeginReadPipeline(ReadPipelineRequest readPipelineRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ReadPipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ReadPipeline"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginReadPipeline.</param>
///
/// <returns>Returns a ReadPipelineResult from AmazonElasticTranscoder.</returns>
ReadPipelineResponse EndReadPipeline(IAsyncResult asyncResult);
/// <summary>
/// <para>The ReadPipeline operation gets detailed information about a pipeline.</para>
/// </summary>
///
/// <returns>The response from the ReadPipeline service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ReadPipelineResponse ReadPipeline();
#endregion
#region CreatePreset
/// <summary>
/// <para>The CreatePreset operation creates a preset with settings that you specify.</para> <para><b>IMPORTANT:</b>Elastic Transcoder checks
/// the CreatePreset settings to ensure that they meet Elastic Transcoder requirements and to determine whether they comply with H.264
/// standards. If your settings are not valid for Elastic Transcoder, Elastic Transcoder returns an HTTP 400 response (ValidationException) and
/// does not create the preset. If the settings are valid for Elastic Transcoder but aren't strictly compliant with the H.264 standard, Elastic
/// Transcoder creates the preset and returns a warning message in the response. This helps you determine whether your settings comply with the
/// H.264 standard while giving you greater flexibility with respect to the video that Elastic Transcoder produces.</para> <para>Elastic
/// Transcoder uses the H.264 video-compression format. For more information, see the International Telecommunication Union publication
/// <i>Recommendation ITU-T H.264: Advanced video coding for generic audiovisual services</i> .</para>
/// </summary>
///
/// <param name="createPresetRequest">Container for the necessary parameters to execute the CreatePreset service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the CreatePreset service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="LimitExceededException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
CreatePresetResponse CreatePreset(CreatePresetRequest createPresetRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreatePreset operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CreatePreset"/>
/// </summary>
///
/// <param name="createPresetRequest">Container for the necessary parameters to execute the CreatePreset operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreatePreset
/// operation.</returns>
IAsyncResult BeginCreatePreset(CreatePresetRequest createPresetRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreatePreset operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CreatePreset"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreatePreset.</param>
///
/// <returns>Returns a CreatePresetResult from AmazonElasticTranscoder.</returns>
CreatePresetResponse EndCreatePreset(IAsyncResult asyncResult);
#endregion
#region DeletePreset
/// <summary>
/// <para>The DeletePreset operation removes a preset that you've added in an AWS region.</para> <para><b>NOTE:</b> You can't delete the default
/// presets that are included with Elastic Transcoder. </para>
/// </summary>
///
/// <param name="deletePresetRequest">Container for the necessary parameters to execute the DeletePreset service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the DeletePreset service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
DeletePresetResponse DeletePreset(DeletePresetRequest deletePresetRequest);
/// <summary>
/// Initiates the asynchronous execution of the DeletePreset operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.DeletePreset"/>
/// </summary>
///
/// <param name="deletePresetRequest">Container for the necessary parameters to execute the DeletePreset operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeletePreset
/// operation.</returns>
IAsyncResult BeginDeletePreset(DeletePresetRequest deletePresetRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeletePreset operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.DeletePreset"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeletePreset.</param>
///
/// <returns>Returns a DeletePresetResult from AmazonElasticTranscoder.</returns>
DeletePresetResponse EndDeletePreset(IAsyncResult asyncResult);
#endregion
#region CreateJob
/// <summary>
/// <para> When you create a job, Elastic Transcoder returns JSON data that includes the values that you specified plus information about the
/// job that is created. </para> <para>If you have specified more than one output for your jobs (for example, one output for the Kindle Fire and
/// another output for the Apple iPhone 4s), you currently must use the Elastic Transcoder API to list the jobs (as opposed to the AWS
/// Console).</para>
/// </summary>
///
/// <param name="createJobRequest">Container for the necessary parameters to execute the CreateJob service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the CreateJob service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="LimitExceededException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
CreateJobResponse CreateJob(CreateJobRequest createJobRequest);
/// <summary>
/// Initiates the asynchronous execution of the CreateJob operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CreateJob"/>
/// </summary>
///
/// <param name="createJobRequest">Container for the necessary parameters to execute the CreateJob operation on AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateJob
/// operation.</returns>
IAsyncResult BeginCreateJob(CreateJobRequest createJobRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateJob operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.CreateJob"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateJob.</param>
///
/// <returns>Returns a CreateJobResult from AmazonElasticTranscoder.</returns>
CreateJobResponse EndCreateJob(IAsyncResult asyncResult);
#endregion
#region ListJobsByPipeline
/// <summary>
/// <para>The ListJobsByPipeline operation gets a list of the jobs currently in a pipeline.</para> <para>Elastic Transcoder returns all of the
/// jobs currently in the specified pipeline. The response body contains one element for each job that satisfies the search criteria.</para>
/// </summary>
///
/// <param name="listJobsByPipelineRequest">Container for the necessary parameters to execute the ListJobsByPipeline service method on
/// AmazonElasticTranscoder.</param>
///
/// <returns>The response from the ListJobsByPipeline service method, as returned by AmazonElasticTranscoder.</returns>
///
/// <exception cref="ResourceNotFoundException"/>
/// <exception cref="AccessDeniedException"/>
/// <exception cref="InternalServiceException"/>
/// <exception cref="ValidationException"/>
/// <exception cref="IncompatibleVersionException"/>
ListJobsByPipelineResponse ListJobsByPipeline(ListJobsByPipelineRequest listJobsByPipelineRequest);
/// <summary>
/// Initiates the asynchronous execution of the ListJobsByPipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListJobsByPipeline"/>
/// </summary>
///
/// <param name="listJobsByPipelineRequest">Container for the necessary parameters to execute the ListJobsByPipeline operation on
/// AmazonElasticTranscoder.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking
/// EndListJobsByPipeline operation.</returns>
IAsyncResult BeginListJobsByPipeline(ListJobsByPipelineRequest listJobsByPipelineRequest, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListJobsByPipeline operation.
/// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.ListJobsByPipeline"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListJobsByPipeline.</param>
///
/// <returns>Returns a ListJobsByPipelineResult from AmazonElasticTranscoder.</returns>
ListJobsByPipelineResponse EndListJobsByPipeline(IAsyncResult asyncResult);
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using Chutzpah.Models;
using Chutzpah.Wrappers;
namespace Chutzpah
{
public interface IChutzpahTestSettingsService
{
/// <summary>
/// Find and reads a chutzpah test settings file given a direcotry. If none is found a default settings object is created
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
ChutzpahTestSettingsFile FindSettingsFile(string directory, ChutzpahSettingsFileEnvironments environments = null);
void ClearCache();
}
public class ChutzpahTestSettingsService : IChutzpahTestSettingsService
{
/// <summary>
/// Cache settings file
/// </summary>
private static readonly ConcurrentDictionary<string, ChutzpahTestSettingsFile> ChutzpahSettingsFileCache =
new ConcurrentDictionary<string, ChutzpahTestSettingsFile>(StringComparer.OrdinalIgnoreCase);
private readonly IFileProbe fileProbe;
private readonly IJsonSerializer serializer;
private readonly IFileSystemWrapper fileSystem;
public ChutzpahTestSettingsService(IFileProbe fileProbe, IJsonSerializer serializer, IFileSystemWrapper fileSystem)
{
this.fileProbe = fileProbe;
this.serializer = serializer;
this.fileSystem = fileSystem;
}
/// <summary>
/// Find and reads a chutzpah test settings file given a direcotry. If none is found a default settings object is created
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
///
public ChutzpahTestSettingsFile FindSettingsFile(string directory, ChutzpahSettingsFileEnvironments environments = null)
{
if (string.IsNullOrEmpty(directory)) return ChutzpahTestSettingsFile.Default;
directory = directory.TrimEnd('/', '\\');
ChutzpahTestSettingsFile settings;
if (!ChutzpahSettingsFileCache.TryGetValue(directory, out settings))
{
ChutzpahSettingsFileEnvironment environment = null;
if (environments != null)
{
environment = environments.GetSettingsFileEnvironment(directory);
}
return FindSettingsFile(directory, environment).InheritFromDefault();
}
else
{
return settings;
}
}
private ChutzpahTestSettingsFile FindSettingsFile(string directory, ChutzpahSettingsFileEnvironment environment)
{
if (string.IsNullOrEmpty(directory)) return ChutzpahTestSettingsFile.Default;
directory = directory.TrimEnd('/', '\\');
ChutzpahTestSettingsFile settings;
if (!ChutzpahSettingsFileCache.TryGetValue(directory, out settings))
{
var testSettingsFilePath = fileProbe.FindTestSettingsFile(directory);
if (string.IsNullOrEmpty(testSettingsFilePath))
{
ChutzpahTracer.TraceInformation("Chutzpah.json file not found given starting directoy {0}", directory);
settings = ChutzpahTestSettingsFile.Default;
}
else if (!ChutzpahSettingsFileCache.TryGetValue(testSettingsFilePath, out settings))
{
ChutzpahTracer.TraceInformation("Chutzpah.json file found at {0} given starting directoy {1}", testSettingsFilePath, directory);
settings = serializer.DeserializeFromFile<ChutzpahTestSettingsFile>(testSettingsFilePath);
if (settings == null)
{
settings = ChutzpahTestSettingsFile.Default;
}
else
{
settings.IsDefaultSettings = false;
}
settings.SettingsFileDirectory = Path.GetDirectoryName(testSettingsFilePath);
var chutzpahVariables = BuildChutzpahReplacementVariables(testSettingsFilePath, environment, settings);
ResolveTestHarnessDirectory(settings, chutzpahVariables);
ResolveAMDBaseUrl(settings, chutzpahVariables);
ResolveBatchCompileConfiguration(settings, chutzpahVariables);
ProcessPathSettings(settings, chutzpahVariables);
ProcessInheritance(environment, settings, chutzpahVariables);
// Add a mapping in the cache for the directory that contains the test settings file
ChutzpahSettingsFileCache.TryAdd(settings.SettingsFileDirectory, settings);
}
// Add mapping in the cache for the original directory tried to skip needing to traverse the tree again
ChutzpahSettingsFileCache.TryAdd(directory, settings);
}
return settings;
}
private void ProcessInheritance(ChutzpahSettingsFileEnvironment environment, ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables)
{
if (settings.InheritFromParent || !string.IsNullOrEmpty(settings.InheritFromPath))
{
if (string.IsNullOrEmpty(settings.InheritFromPath))
{
ChutzpahTracer.TraceInformation("Searching for parent Chutzpah.json to inherit from");
settings.InheritFromPath = Path.GetDirectoryName(settings.SettingsFileDirectory);
}
else
{
ChutzpahTracer.TraceInformation("Searching for Chutzpah.json to inherit from at {0}", settings.InheritFromPath);
string settingsToInherit = ExpandVariable(chutzpahVariables, settings.InheritFromPath);
if (settingsToInherit.EndsWith(Constants.SettingsFileName, StringComparison.OrdinalIgnoreCase))
{
settingsToInherit = Path.GetDirectoryName(settingsToInherit);
}
settingsToInherit = ResolveFolderPath(settings, settingsToInherit);
settings.InheritFromPath = settingsToInherit;
}
var parentSettingsFile = FindSettingsFile(settings.InheritFromPath, environment);
if (!parentSettingsFile.IsDefaultSettings)
{
ChutzpahTracer.TraceInformation("Found parent Chutzpah.json in directory {0}", parentSettingsFile.SettingsFileDirectory);
settings.InheritFrom(parentSettingsFile);
}
else
{
ChutzpahTracer.TraceInformation("Could not find a parent Chutzpah.json");
}
}
}
public void ClearCache()
{
ChutzpahTracer.TraceInformation("Chutzpah.json file cache cleared");
ChutzpahSettingsFileCache.Clear();
}
private void ResolveTestHarnessDirectory(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables)
{
if (settings.TestHarnessLocationMode == TestHarnessLocationMode.Custom)
{
if (settings.TestHarnessDirectory != null)
{
string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.TestHarnessDirectory));
settings.TestHarnessDirectory = absoluteFilePath;
}
if (settings.TestHarnessDirectory == null)
{
settings.TestHarnessLocationMode = TestHarnessLocationMode.TestFileAdjacent;
ChutzpahTracer.TraceWarning("Unable to find custom test harness directory at {0}", settings.TestHarnessDirectory);
}
}
}
private void ResolveAMDBaseUrl(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables)
{
if (!string.IsNullOrEmpty(settings.AMDBaseUrl))
{
string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.AMDBaseUrl));
settings.AMDBaseUrl = absoluteFilePath;
if (string.IsNullOrEmpty(settings.AMDBaseUrl))
{
ChutzpahTracer.TraceWarning("Unable to find AMDBaseUrl at {0}", settings.AMDBaseUrl);
}
}
if (!string.IsNullOrEmpty(settings.AMDAppDirectory))
{
string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.AMDAppDirectory));
settings.AMDAppDirectory = absoluteFilePath;
if (string.IsNullOrEmpty(settings.AMDAppDirectory))
{
ChutzpahTracer.TraceWarning("Unable to find AMDAppDirectory at {0}", settings.AMDAppDirectory);
}
}
// Legacy AMDBasePath property
if (!string.IsNullOrEmpty(settings.AMDBasePath))
{
string absoluteFilePath = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.AMDBasePath));
settings.AMDBasePath = absoluteFilePath;
if (string.IsNullOrEmpty(settings.AMDBasePath))
{
ChutzpahTracer.TraceWarning("Unable to find AMDBasePath at {0}", settings.AMDBasePath);
}
}
}
private void ProcessPathSettings(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables)
{
var i = 0;
foreach (var test in settings.Tests)
{
test.SettingsFileDirectory = settings.SettingsFileDirectory;
test.Path = ExpandVariable(chutzpahVariables, test.Path);
for (i = 0; i < test.Includes.Count; i++)
{
test.Includes[i] = ExpandVariable(chutzpahVariables, test.Includes[i]);
}
for (i = 0; i < test.Excludes.Count; i++)
{
test.Excludes[i] = ExpandVariable(chutzpahVariables, test.Excludes[i]);
}
}
foreach (var reference in settings.References)
{
reference.SettingsFileDirectory = settings.SettingsFileDirectory;
reference.Path = ExpandVariable(chutzpahVariables, reference.Path);
for (i = 0; i < reference.Includes.Count; i++)
{
reference.Includes[i] = ExpandVariable(chutzpahVariables, reference.Includes[i]);
}
for (i = 0; i < reference.Excludes.Count; i++)
{
reference.Excludes[i] = ExpandVariable(chutzpahVariables, reference.Excludes[i]);
}
}
foreach (var transform in settings.Transforms)
{
transform.SettingsFileDirectory = settings.SettingsFileDirectory;
transform.Path = ExpandVariable(chutzpahVariables, transform.Path);
}
}
private void ResolveBatchCompileConfiguration(ChutzpahTestSettingsFile settings, IDictionary<string, string> chutzpahVariables)
{
if (settings.Compile != null)
{
settings.Compile.SettingsFileDirectory = settings.SettingsFileDirectory;
settings.Compile.Extensions = settings.Compile.Extensions ?? new List<string>();
// If the mode is executable then set its properties
if (settings.Compile.Mode == BatchCompileMode.Executable)
{
if (string.IsNullOrEmpty(settings.Compile.Executable))
{
throw new ArgumentException("Executable path must be passed for compile setting");
}
settings.Compile.Executable = ResolveFilePath(settings, ExpandVariable(chutzpahVariables, settings.Compile.Executable));
settings.Compile.Arguments = ExpandVariable(chutzpahVariables, settings.Compile.Arguments);
settings.Compile.WorkingDirectory = ResolveFolderPath(settings, settings.Compile.WorkingDirectory);
// Default timeout to 5 minutes if missing
settings.Compile.Timeout = settings.Compile.Timeout.HasValue ? settings.Compile.Timeout.Value : 1000 * 60 * 5;
}
// These settings might be needed in either External
settings.Compile.SourceDirectory = ResolveFolderPath(settings, settings.Compile.SourceDirectory);
settings.Compile.OutDirectory = ResolveFolderPath(settings, ExpandVariable(chutzpahVariables, settings.Compile.OutDirectory), true);
}
}
/// <summary>
/// Resolved a path relative to the settings file if it is not absolute
/// </summary>
private string ResolveFolderPath(ChutzpahTestSettingsFile settings, string path, bool createIfNeeded = false)
{
string relativeLocationPath = Path.Combine(settings.SettingsFileDirectory, path ?? "");
string absoluteFilePath = fileProbe.FindFolderPath(relativeLocationPath);
if (createIfNeeded && absoluteFilePath == null)
{
fileSystem.CreateDirectory(relativeLocationPath);
absoluteFilePath = fileProbe.FindFolderPath(relativeLocationPath);
}
return absoluteFilePath;
}
private string ResolveFilePath(ChutzpahTestSettingsFile settings, string path)
{
string relativeLocationPath = Path.Combine(settings.SettingsFileDirectory, path ?? "");
string absoluteFilePath = fileProbe.FindFilePath(relativeLocationPath);
return absoluteFilePath;
}
private string ExpandVariable(IDictionary<string, string> chutzpahCompileVariables, string str)
{
return ExpandChutzpahVariables(chutzpahCompileVariables, Environment.ExpandEnvironmentVariables(str ?? ""));
}
private string ExpandChutzpahVariables(IDictionary<string, string> chutzpahCompileVariables, string str)
{
if (str == null)
{
return null;
}
return chutzpahCompileVariables.Aggregate(str, (current, pair) => current.Replace(pair.Key, pair.Value));
}
private IDictionary<string, string> BuildChutzpahReplacementVariables(string settingsFilePath, ChutzpahSettingsFileEnvironment environment, ChutzpahTestSettingsFile settings)
{
IDictionary<string, string> chutzpahVariables = new Dictionary<string, string>();
var clrDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
var msbuildExe = Path.Combine(clrDir, "msbuild.exe");
var powershellExe = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"windowspowershell\v1.0\powershell.exe");
AddChutzpahVariable(chutzpahVariables, "chutzpahsettingsdir", settings.SettingsFileDirectory);
AddChutzpahVariable(chutzpahVariables, "clrdir", clrDir);
AddChutzpahVariable(chutzpahVariables, "msbuildexe", msbuildExe);
AddChutzpahVariable(chutzpahVariables, "powershellexe", powershellExe);
// This is not needed but it is a nice alias
AddChutzpahVariable(chutzpahVariables, "cmdexe", Environment.ExpandEnvironmentVariables("%comspec%"));
if (environment != null)
{
// See if we have a settingsfileenvironment set and if so add its properties as chutzpah settings file variables
var props = environment.Properties;
foreach (var prop in props)
{
AddChutzpahVariable(chutzpahVariables, prop.Name, prop.Value);
}
}
return chutzpahVariables;
}
private void AddChutzpahVariable(IDictionary<string, string> chutzpahCompileVariables, string name, string value)
{
name = string.Format("%{0}%", name);
chutzpahCompileVariables[name] = value;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Cuyahoga.Core.Domain;
using Cuyahoga.Web.UI;
using Cuyahoga.Modules.Downloads.Domain;
namespace Cuyahoga.Modules.Downloads.Web
{
/// <summary>
/// Summary description for EditFile.
/// </summary>
public class EditFile : ModuleAdminBasePage
{
private DownloadsModule _downloadsModule;
private int _fileId;
private File _file;
protected System.Web.UI.WebControls.Button btnSave;
protected System.Web.UI.WebControls.Button btnDelete;
protected System.Web.UI.WebControls.Panel pnlFileName;
protected System.Web.UI.HtmlControls.HtmlInputFile filUpload;
protected System.Web.UI.WebControls.Button btnUpload;
protected System.Web.UI.WebControls.RequiredFieldValidator rfvFile;
protected System.Web.UI.WebControls.Button btnCancel;
protected System.Web.UI.WebControls.Repeater rptRoles;
protected Cuyahoga.ServerControls.Calendar calDatePublished;
protected System.Web.UI.WebControls.TextBox txtTitle;
protected System.Web.UI.WebControls.RequiredFieldValidator rfvDatePublished;
protected System.Web.UI.WebControls.TextBox txtFile;
private void Page_Load(object sender, System.EventArgs e)
{
// The base page has already created the module, we only have to cast it here to the right type.
this._downloadsModule = base.Module as DownloadsModule;
this._fileId = Int32.Parse(Request.QueryString["FileId"]);
if (this._fileId > 0)
{
this._file = this._downloadsModule.GetFileById(this._fileId);
if (! this.IsPostBack)
{
BindFile();
}
this.btnDelete.Visible = true;
this.btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?');");
}
else
{
// It is possible that a new file is already uploaded and in the database. The
// tempFileId parameter in the viewstate should indicate this.
if (ViewState["tempFileId"] != null)
{
int tempFileId = (int)ViewState["tempFileId"];
this._file = this._downloadsModule.GetFileById(tempFileId);
}
else
{
// New file.
this._file = new File();
// Copy roles that have view rights from parent section.
foreach (Permission permission in this._downloadsModule.Section.SectionPermissions)
{
this._file.AllowedRoles.Add(permission.Role);
}
this.calDatePublished.SelectedDate = DateTime.Now;
}
this.btnDelete.Visible = false;
}
if (! this.IsPostBack)
{
BindRoles();
}
}
private void BindFile()
{
this.txtFile.Text = this._file.FilePath;
this.txtTitle.Text = this._file.Title;
this.calDatePublished.SelectedDate = this._file.DatePublished;
}
private void BindRoles()
{
// Get roles via SectionPermissions of the section.
this.rptRoles.DataSource = base.Section.SectionPermissions;
this.rptRoles.DataBind();
}
private string CreateServerFilename(string clientFilename)
{
if (clientFilename.LastIndexOf(System.IO.Path.DirectorySeparatorChar) > -1)
{
return clientFilename.Substring(clientFilename.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1);
}
else
{
return clientFilename;
}
}
private void SetRoles()
{
this._file.AllowedRoles.Clear();
foreach (RepeaterItem ri in rptRoles.Items)
{
// HACK: RoleId is stored in the ViewState because the repeater doesn't have a DataKeys property.
// Another HACK: we're only using the role id's to save database roundtrips.
CheckBox chkRole = (CheckBox)ri.FindControl("chkRole");
if (chkRole.Checked)
{
int roleId = (int)this.ViewState[ri.ClientID];
Role role = (Role)base.CoreRepository.GetObjectById(typeof(Role), roleId);
this._file.AllowedRoles.Add(role);
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
this.rptRoles.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptRoles_ItemDataBound);
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnUpload_Click(object sender, System.EventArgs e)
{
HttpPostedFile postedFile = this.filUpload.PostedFile;
if (postedFile.ContentLength > 0)
{
this._file.Title = this.txtTitle.Text;
this._file.DatePublished = this.calDatePublished.SelectedDate;
this._file.FilePath = CreateServerFilename(postedFile.FileName);
this._file.ContentType = postedFile.ContentType;
this._file.Size = postedFile.ContentLength;
this._file.Publisher = (User)this.User.Identity;
this._file.Section = base.Section;
string fullFilePath = this._downloadsModule.FileDir + System.IO.Path.DirectorySeparatorChar + this._file.FilePath;
// Save the file
try
{
this._downloadsModule.SaveFile(this._file, postedFile.InputStream);
if (this._fileId <= 0 && this._file.Id > 0)
{
// This appears to be a new file. Store the id of the file in the viewstate
// so the file can be deleted if the user decides to cancel.
ViewState["tempFileId"] = this._file.Id;
}
BindFile();
}
catch (Exception ex)
{
// Something went wrong
ShowError("Error saving the file: " + fullFilePath + " " + ex.ToString());
}
}
}
private void btnSave_Click(object sender, System.EventArgs e)
{
if (this.IsValid)
{
this._file.Publisher = this.User.Identity as User;
this._file.Title = this.txtTitle.Text;
this._file.DatePublished = calDatePublished.SelectedDate;
SetRoles();
try
{
// Only save meta data.
this._downloadsModule.SaveFileInfo(this._file);
Context.Response.Redirect("EditDownloads.aspx" + base.GetBaseQueryString());
}
catch (Exception ex)
{
ShowError("Error saving file: " + ex.Message);
}
}
}
private void btnDelete_Click(object sender, System.EventArgs e)
{
try
{
this._downloadsModule.DeleteFile(this._file);
Context.Response.Redirect("EditDownloads.aspx" + base.GetBaseQueryString());
}
catch (Exception ex)
{
ShowError("Error deleting file: " + ex.Message);
}
}
private void btnCancel_Click(object sender, System.EventArgs e)
{
// Check if there is a new file pending. This has to be deleted
if (ViewState["tempFileId"] != null)
{
this._downloadsModule.DeleteFile(this._file);
}
Context.Response.Redirect("EditDownloads.aspx" + base.GetBaseQueryString());
}
private void rptRoles_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Header)
{
SectionPermission permission = e.Item.DataItem as SectionPermission;
Role role = permission.Role;
if (role != null)
{
CheckBox chkRole = (CheckBox)e.Item.FindControl("chkRole");
chkRole.Checked = this._file.IsDownloadAllowed(role);
// Add RoleId to the ViewState with the ClientID of the repeateritem as key.
this.ViewState[e.Item.ClientID] = role.Id;
}
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Old SKGS Schools
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SKGS_OLD : EduHubEntity
{
#region Navigation Property Cache
private SKGS Cache_NEW_SCHOOL_SKGS;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// School ID
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string SCHOOL { get; internal set; }
/// <summary>
/// School Name
/// [Alphanumeric (40)]
/// </summary>
public string NAME { get; internal set; }
/// <summary>
/// New School ID*DJB - Map to new SKGS values
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string NEW_SCHOOL { get; internal set; }
/// <summary>
/// School type: Primary, Secondary, Special, etc
/// [Alphanumeric (33)]
/// </summary>
public string SCHOOL_TYPE { get; internal set; }
/// <summary>
/// School type: Government, Private, etc
/// [Uppercase Alphanumeric (2)]
/// </summary>
public string ENTITY { get; internal set; }
/// <summary>
/// DEET-defined school ID
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string SCHOOL_ID { get; internal set; }
/// <summary>
/// (Was SCHOOL_CAMPUS) Campus number
/// [Uppercase Alphanumeric (2)]
/// </summary>
public string SCHOOL_NUMBER { get; internal set; }
/// <summary>
/// Campus type: Primary, etc
/// [Alphanumeric (33)]
/// </summary>
public string CAMPUS_TYPE { get; internal set; }
/// <summary>
/// Campus name
/// [Alphanumeric (40)]
/// </summary>
public string CAMPUS_NAME { get; internal set; }
/// <summary>
/// Region
/// </summary>
public short? REGION { get; internal set; }
/// <summary>
/// Name of Region
/// [Alphanumeric (30)]
/// </summary>
public string REGION_NAME { get; internal set; }
/// <summary>
/// Two address lines
/// [Alphanumeric (30)]
/// </summary>
public string ADDRESS01 { get; internal set; }
/// <summary>
/// Two address lines
/// [Alphanumeric (30)]
/// </summary>
public string ADDRESS02 { get; internal set; }
/// <summary>
/// Suburb name
/// [Alphanumeric (30)]
/// </summary>
public string SUBURB { get; internal set; }
/// <summary>
/// State code
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string STATE { get; internal set; }
/// <summary>
/// Postcode
/// [Alphanumeric (4)]
/// </summary>
public string POSTCODE { get; internal set; }
/// <summary>
/// Phone no
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string TELEPHONE { get; internal set; }
/// <summary>
/// Fax no
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string FAX { get; internal set; }
/// <summary>
/// Two address lines
/// [Alphanumeric (30)]
/// </summary>
public string MAILING_ADDRESS01 { get; internal set; }
/// <summary>
/// Two address lines
/// [Alphanumeric (30)]
/// </summary>
public string MAILING_ADDRESS02 { get; internal set; }
/// <summary>
/// Suburb name for Mailing
/// [Alphanumeric (30)]
/// </summary>
public string MAILING_SUBURB { get; internal set; }
/// <summary>
/// State code for Mailing
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string MAILING_STATE { get; internal set; }
/// <summary>
/// Postcode for Mailing
/// [Alphanumeric (4)]
/// </summary>
public string MAILING_POSTCODE { get; internal set; }
/// <summary>
/// Two address lines for Delivery
/// [Alphanumeric (30)]
/// </summary>
public string DELIVERY_ADDRESS01 { get; internal set; }
/// <summary>
/// Two address lines for Delivery
/// [Alphanumeric (30)]
/// </summary>
public string DELIVERY_ADDRESS02 { get; internal set; }
/// <summary>
/// Suburb name for Delivery
/// [Alphanumeric (30)]
/// </summary>
public string DELIVERY_SUBURB { get; internal set; }
/// <summary>
/// State code for Delivery
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string DELIVERY_STATE { get; internal set; }
/// <summary>
/// Postcode for Delivery
/// [Alphanumeric (4)]
/// </summary>
public string DELIVERY_POSTCODE { get; internal set; }
/// <summary>
/// Phone no. for Delivery
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string DELIVERY_TELEPHONE { get; internal set; }
/// <summary>
/// Fax no for Delivery
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string DELIVERY_FAX { get; internal set; }
/// <summary>
/// (Was E_MAIL_ADDRESS) E-mail address
/// [Alphanumeric (255)]
/// </summary>
public string E_MAIL { get; internal set; }
/// <summary>
/// Internet address
/// [Alphanumeric (255)]
/// </summary>
public string INTERNET_ADDRESS { get; internal set; }
/// <summary>
/// CASES 21 release no
/// [Uppercase Alphanumeric (12)]
/// </summary>
public string CASES21_RELEASE { get; internal set; }
/// <summary>
/// Melway, VicRoads, Country Fire Authority, etc
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string MAP_TYPE { get; internal set; }
/// <summary>
/// Map no
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string MAP_NUM { get; internal set; }
/// <summary>
/// Horizontal grid reference
/// [Uppercase Alphanumeric (2)]
/// </summary>
public string X_AXIS { get; internal set; }
/// <summary>
/// Vertical grid reference
/// [Uppercase Alphanumeric (2)]
/// </summary>
public string Y_AXIS { get; internal set; }
/// <summary>
/// School Principal's Title: Mr, Mrs, etc
/// [Titlecase (4)]
/// </summary>
public string SCH_PRINCIPAL_SALUTATION { get; internal set; }
/// <summary>
/// School Principal's First Name
/// [Titlecase (20)]
/// </summary>
public string SCH_PRINCIPAL_FIRST_NAME { get; internal set; }
/// <summary>
/// School Principal's Surname
/// [Uppercase Alphanumeric (30)]
/// </summary>
public string SCH_PRINCIPAL_SURNAME { get; internal set; }
/// <summary>
/// School Principal's Phone no
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string SCH_PRINCIPAL_TELEPHONE { get; internal set; }
/// <summary>
/// Campus Principal's title: Mr, Mrs, etc
/// [Titlecase (4)]
/// </summary>
public string SALUTATION { get; internal set; }
/// <summary>
/// Campus Principal's surname
/// [Uppercase Alphanumeric (30)]
/// </summary>
public string SURNAME { get; internal set; }
/// <summary>
/// Campus Principal's first given name
/// [Titlecase (20)]
/// </summary>
public string FIRST_NAME { get; internal set; }
/// <summary>
/// School closed? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CLOSED { get; internal set; }
/// <summary>
/// Concurrent enrolment Y/N
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CONCURRENT_ENROL { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// SKGS (Schools) related entity by [SKGS_OLD.NEW_SCHOOL]->[SKGS.SCHOOL]
/// New School ID*DJB - Map to new SKGS values
/// </summary>
public SKGS NEW_SCHOOL_SKGS
{
get
{
if (NEW_SCHOOL == null)
{
return null;
}
if (Cache_NEW_SCHOOL_SKGS == null)
{
Cache_NEW_SCHOOL_SKGS = Context.SKGS.FindBySCHOOL(NEW_SCHOOL);
}
return Cache_NEW_SCHOOL_SKGS;
}
}
#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.Threading;
using System.Transactions.Diagnostics;
namespace System.Transactions
{
// Base class for all durable enlistment states
internal abstract class DurableEnlistmentState : EnlistmentState
{
// Double-checked locking pattern requires volatile for read/write synchronization
private static volatile DurableEnlistmentActive s_durableEnlistmentActive;
private static volatile DurableEnlistmentAborting s_durableEnlistmentAborting;
private static volatile DurableEnlistmentCommitting s_durableEnlistmentCommitting;
private static volatile DurableEnlistmentDelegated s_durableEnlistmentDelegated;
private static volatile DurableEnlistmentEnded s_durableEnlistmentEnded;
// Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
private static object s_classSyncObject;
internal static DurableEnlistmentActive DurableEnlistmentActive
{
get
{
if (s_durableEnlistmentActive == null)
{
lock (ClassSyncObject)
{
if (s_durableEnlistmentActive == null)
{
DurableEnlistmentActive temp = new DurableEnlistmentActive();
s_durableEnlistmentActive = temp;
}
}
}
return s_durableEnlistmentActive;
}
}
protected static DurableEnlistmentAborting DurableEnlistmentAborting
{
get
{
if (s_durableEnlistmentAborting == null)
{
lock (ClassSyncObject)
{
if (s_durableEnlistmentAborting == null)
{
DurableEnlistmentAborting temp = new DurableEnlistmentAborting();
s_durableEnlistmentAborting = temp;
}
}
}
return s_durableEnlistmentAborting;
}
}
protected static DurableEnlistmentCommitting DurableEnlistmentCommitting
{
get
{
if (s_durableEnlistmentCommitting == null)
{
lock (ClassSyncObject)
{
if (s_durableEnlistmentCommitting == null)
{
DurableEnlistmentCommitting temp = new DurableEnlistmentCommitting();
s_durableEnlistmentCommitting = temp;
}
}
}
return s_durableEnlistmentCommitting;
}
}
protected static DurableEnlistmentDelegated DurableEnlistmentDelegated
{
get
{
if (s_durableEnlistmentDelegated == null)
{
lock (ClassSyncObject)
{
if (s_durableEnlistmentDelegated == null)
{
DurableEnlistmentDelegated temp = new DurableEnlistmentDelegated();
s_durableEnlistmentDelegated = temp;
}
}
}
return s_durableEnlistmentDelegated;
}
}
protected static DurableEnlistmentEnded DurableEnlistmentEnded
{
get
{
if (s_durableEnlistmentEnded == null)
{
lock (ClassSyncObject)
{
if (s_durableEnlistmentEnded == null)
{
DurableEnlistmentEnded temp = new DurableEnlistmentEnded();
s_durableEnlistmentEnded = temp;
}
}
}
return s_durableEnlistmentEnded;
}
}
// Helper object for static synchronization
private static object ClassSyncObject
{
get
{
if (s_classSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_classSyncObject, o, null);
}
return s_classSyncObject;
}
}
}
// Active state for a durable enlistment. In this state the transaction can be aborted
// asynchronously by calling abort.
internal class DurableEnlistmentActive : DurableEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
// Yeah it's active
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// Mark the enlistment as done.
DurableEnlistmentEnded.EnterState(enlistment);
}
internal override void InternalAborted(InternalEnlistment enlistment)
{
// Transition to the aborting state
DurableEnlistmentAborting.EnterState(enlistment);
}
internal override void ChangeStateCommitting(InternalEnlistment enlistment)
{
// Transition to the committing state
DurableEnlistmentCommitting.EnterState(enlistment);
}
internal override void ChangeStatePromoted(InternalEnlistment enlistment, IPromotedEnlistment promotedEnlistment)
{
// Save the promoted enlistment because future notifications must be sent here.
enlistment.PromotedEnlistment = promotedEnlistment;
// The transaction is being promoted promote the enlistment as well
EnlistmentStatePromoted.EnterState(enlistment);
}
internal override void ChangeStateDelegated(InternalEnlistment enlistment)
{
// This is a valid state transition.
DurableEnlistmentDelegated.EnterState(enlistment);
}
}
// Aborting state for a durable enlistment. In this state the transaction has been aborted,
// by someone other than the enlistment.
//
internal class DurableEnlistmentAborting : DurableEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
Monitor.Exit(enlistment.Transaction);
try
{
if (DiagnosticTrace.Verbose)
{
EnlistmentNotificationCallTraceRecord.Trace(SR.TraceSourceLtm,
enlistment.EnlistmentTraceId, NotificationCall.Rollback);
}
// Send the Rollback notification to the enlistment
if (enlistment.SinglePhaseNotification != null)
{
enlistment.SinglePhaseNotification.Rollback(enlistment.SinglePhaseEnlistment);
}
else
{
enlistment.PromotableSinglePhaseNotification.Rollback(enlistment.SinglePhaseEnlistment);
}
}
finally
{
Monitor.Enter(enlistment.Transaction);
}
}
internal override void Aborted(InternalEnlistment enlistment, Exception e)
{
if (enlistment.Transaction._innerException == null)
{
enlistment.Transaction._innerException = e;
}
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
}
}
// Committing state is when SPC has been sent to an enlistment but no response
// has been received.
//
internal class DurableEnlistmentCommitting : DurableEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
bool spcCommitted = false;
// Set the enlistment state
enlistment.State = this;
Monitor.Exit(enlistment.Transaction);
try
{
if (DiagnosticTrace.Verbose)
{
EnlistmentNotificationCallTraceRecord.Trace(SR.TraceSourceLtm,
enlistment.EnlistmentTraceId, NotificationCall.SinglePhaseCommit);
}
// Send the Commit notification to the enlistment
if (enlistment.SinglePhaseNotification != null)
{
enlistment.SinglePhaseNotification.SinglePhaseCommit(enlistment.SinglePhaseEnlistment);
}
else
{
enlistment.PromotableSinglePhaseNotification.SinglePhaseCommit(enlistment.SinglePhaseEnlistment);
}
spcCommitted = true;
}
finally
{
if (!spcCommitted)
{
enlistment.SinglePhaseEnlistment.InDoubt();
}
Monitor.Enter(enlistment.Transaction);
}
}
internal override void EnlistmentDone(InternalEnlistment enlistment)
{
// EnlistmentDone should be treated the same as Committed from this state.
// This eliminates a race between the SPC call and the EnlistmentDone call.
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
// Make the transaction commit
enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction);
}
internal override void Committed(InternalEnlistment enlistment)
{
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
// Make the transaction commit
enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction);
}
internal override void Aborted(InternalEnlistment enlistment, Exception e)
{
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
// Start the transaction aborting
enlistment.Transaction.State.ChangeStateTransactionAborted(enlistment.Transaction, e);
}
internal override void InDoubt(InternalEnlistment enlistment, Exception e)
{
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
if (enlistment.Transaction._innerException == null)
{
enlistment.Transaction._innerException = e;
}
// Make the transaction in dobut
enlistment.Transaction.State.InDoubtFromEnlistment(enlistment.Transaction);
}
}
// Delegated state for a durable enlistment represents an enlistment that was
// origionally a PromotableSinglePhaseEnlisment that where promotion has happened.
// These enlistments don't need to participate in the commit process anymore.
internal class DurableEnlistmentDelegated : DurableEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
// At this point the durable enlistment should have someone to forward to.
Debug.Assert(enlistment.PromotableSinglePhaseNotification != null);
}
internal override void Committed(InternalEnlistment enlistment)
{
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
// Change the transaction to committed.
enlistment.Transaction.State.ChangeStatePromotedCommitted(enlistment.Transaction);
}
internal override void Aborted(InternalEnlistment enlistment, Exception e)
{
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
if (enlistment.Transaction._innerException == null)
{
enlistment.Transaction._innerException = e;
}
// Start the transaction aborting
enlistment.Transaction.State.ChangeStatePromotedAborted(enlistment.Transaction);
}
internal override void InDoubt(InternalEnlistment enlistment, Exception e)
{
// Transition to the ended state
DurableEnlistmentEnded.EnterState(enlistment);
if (enlistment.Transaction._innerException == null)
{
enlistment.Transaction._innerException = e;
}
// Tell the transaction that the enlistment is InDoubt. Note that
// for a transaction that has been delegated and then promoted there
// are two chances to get a better answer than indoubt. So it may be that
// the TM will have a better answer.
enlistment.Transaction.State.InDoubtFromEnlistment(enlistment.Transaction);
}
}
// Ended state is the state that is entered when the durable enlistment has committed,
// aborted, or said read only for an enlistment. At this point there are no valid
// operations on the enlistment.
internal class DurableEnlistmentEnded : DurableEnlistmentState
{
internal override void EnterState(InternalEnlistment enlistment)
{
// Set the enlistment state
enlistment.State = this;
}
internal override void InternalAborted(InternalEnlistment enlistment)
{
// From the Aborting state the transaction may tell the enlistment to abort. At this point
// it already knows. Eat this message.
}
internal override void InDoubt(InternalEnlistment enlistment, Exception e)
{
// Ignore this in case the enlistment gets here before
// the transaction tells it to do so
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Xunit;
namespace Microsoft.Framework.WebEncoders
{
public class HtmlEncoderTests
{
[Fact]
public void TestSurrogate()
{
Assert.Equal("💩", System.Text.Encodings.Web.HtmlEncoder.Default.Encode("\U0001f4a9"));
using (var writer = new StringWriter())
{
System.Text.Encodings.Web.HtmlEncoder.Default.Encode(writer, "\U0001f4a9");
Assert.Equal("💩", writer.GetStringBuilder().ToString());
}
}
[Fact]
public void Ctor_WithTextEncoderSettings()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('a', 'b');
filter.AllowCharacters('\0', '&', '\uFFFF', 'd');
HtmlEncoder encoder = new HtmlEncoder(filter);
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("b", encoder.HtmlEncode("b"));
Assert.Equal("c", encoder.HtmlEncode("c"));
Assert.Equal("d", encoder.HtmlEncode("d"));
Assert.Equal("�", encoder.HtmlEncode("\0")); // we still always encode control chars
Assert.Equal("&", encoder.HtmlEncode("&")); // we still always encode HTML-special chars
Assert.Equal("", encoder.HtmlEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars
}
[Fact]
public void Ctor_WithUnicodeRanges()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols);
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("\u00E9", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("\u2601", encoder.HtmlEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Ctor_WithNoParameters_DefaultsToBasicLatin()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("é", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("☁", encoder.HtmlEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Default_EquivalentToBasicLatin()
{
// Arrange
HtmlEncoder controlEncoder = new HtmlEncoder(UnicodeRanges.BasicLatin);
HtmlEncoder testEncoder = HtmlEncoder.Default;
// Act & assert
for (int i = 0; i <= Char.MaxValue; i++)
{
if (!IsSurrogateCodePoint(i))
{
string input = new String((char)i, 1);
Assert.Equal(controlEncoder.HtmlEncode(input), testEncoder.HtmlEncode(input));
}
}
}
[Theory]
[InlineData("<", "<")]
[InlineData(">", ">")]
[InlineData("&", "&")]
[InlineData("'", "'")]
[InlineData("\"", """)]
[InlineData("+", "+")]
public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple(string input, string expected)
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);
// Act
string retVal = encoder.HtmlEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Extended()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);
// Act & assert - BMP chars
for (int i = 0; i <= 0xFFFF; i++)
{
string input = new String((char)i, 1);
string expected;
if (IsSurrogateCodePoint(i))
{
expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char
}
else
{
if (input == "<") { expected = "<"; }
else if (input == ">") { expected = ">"; }
else if (input == "&") { expected = "&"; }
else if (input == "\"") { expected = """; }
else
{
bool mustEncode = false;
if (i == '\'' || i == '+')
{
mustEncode = true; // apostrophe, plus
}
else if (i <= 0x001F || (0x007F <= i && i <= 0x9F))
{
mustEncode = true; // control char
}
else if (!UnicodeHelpers.IsCharacterDefined((char)i))
{
mustEncode = true; // undefined (or otherwise disallowed) char
}
if (mustEncode)
{
expected = String.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
}
else
{
expected = input; // no encoding
}
}
}
string retVal = encoder.HtmlEncode(input);
Assert.Equal(expected, retVal);
}
// Act & assert - astral chars
for (int i = 0x10000; i <= 0x10FFFF; i++)
{
string input = Char.ConvertFromUtf32(i);
string expected = String.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
string retVal = encoder.HtmlEncode(input);
Assert.Equal(expected, retVal);
}
}
[Fact]
public void HtmlEncode_BadSurrogates_ReturnsUnicodeReplacementChar()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD𐏿e\uFFFD";
// Act
string retVal = encoder.HtmlEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void HtmlEncode_EmptyStringInput_ReturnsEmptyString()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
// Act & assert
Assert.Equal("", encoder.HtmlEncode(""));
}
[Fact]
public void HtmlEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
string input = "Hello, there!";
// Act & assert
Assert.Same(input, encoder.HtmlEncode(input));
}
[Fact]
public void HtmlEncode_NullInput_Throws()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
Assert.Throws<ArgumentNullException>(() => { encoder.HtmlEncode(null); });
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingAtBeginning()
{
Assert.Equal("&Hello, there!", new HtmlEncoder().HtmlEncode("&Hello, there!"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingAtEnd()
{
Assert.Equal("Hello, there!&", new HtmlEncoder().HtmlEncode("Hello, there!&"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingInMiddle()
{
Assert.Equal("Hello, &there!", new HtmlEncoder().HtmlEncode("Hello, &there!"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingInterspersed()
{
Assert.Equal("Hello, <there>!", new HtmlEncoder().HtmlEncode("Hello, <there>!"));
}
[Fact]
public void HtmlEncode_CharArray()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
var output = new StringWriter();
// Act
encoder.HtmlEncode("Hello+world!".ToCharArray(), 3, 5, output);
// Assert
Assert.Equal("lo+wo", output.ToString());
}
[Fact]
public void HtmlEncode_StringSubstring()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
var output = new StringWriter();
// Act
encoder.HtmlEncode("Hello+world!", 3, 5, output);
// Assert
Assert.Equal("lo+wo", output.ToString());
}
private static bool IsSurrogateCodePoint(int codePoint)
{
return (0xD800 <= codePoint && codePoint <= 0xDFFF);
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public sealed class TerrainWithWaterScene : IDemoScene
{
Demo demo;
PhysicsScene scene;
string name;
string instanceIndexName;
string info;
public PhysicsScene PhysicsScene { get { return scene; } }
public string SceneName { get { return name; } }
public string SceneInfo { get { return info; } }
// Declare objects in the scene
Sky skyInstance1;
Cursor cursorInstance;
Shot shotInstance;
Terrain terrainInstance1;
Lake lakeInstance1;
DefaultShapes defaultShapesInstance;
Column columnInstance1;
Column columnInstance2;
Pier pierInstance1;
Ragdoll2 ragdoll2Instance1;
Boat1 boat1Instance1;
Car1 car1Instance1;
Box2 box2Instance1;
Crab1 crab1Instance1;
TorusMesh torusMesh;
Camera2 camera2Instance1;
Lights lightInstance;
// Declare controllers in the scene
SkyDraw1 skyDraw1Instance1;
CursorDraw1 cursorDraw1Instance;
Boat1Animation1 boat1Animation1Instance1;
Car1Animation1 car1Animation1Instance1;
TerrainDraw1 terrainDraw1Instance1;
LakeDraw1 lakeDraw1Instance1;
Camera2Animation1 camera2Animation1Instance1;
Camera2Draw1 camera2Draw1Instance1;
public TerrainWithWaterScene(Demo demo, string name, int instanceIndex, string info)
{
this.demo = demo;
this.name = name;
this.instanceIndexName = " " + instanceIndex.ToString();
this.info = info;
// Create a new objects in the scene
skyInstance1 = new Sky(demo, 1);
cursorInstance = new Cursor(demo);
shotInstance = new Shot(demo);
terrainInstance1 = new Terrain(demo, 1);
lakeInstance1 = new Lake(demo, 1, 8, 8);
defaultShapesInstance = new DefaultShapes(demo);
columnInstance1 = new Column(demo, 1);
columnInstance2 = new Column(demo, 2);
pierInstance1 = new Pier(demo, 1);
ragdoll2Instance1 = new Ragdoll2(demo, 1);
boat1Instance1 = new Boat1(demo, 1);
car1Instance1 = new Car1(demo, 1);
box2Instance1 = new Box2(demo, 1);
crab1Instance1 = new Crab1(demo, 1);
torusMesh = new TorusMesh(demo, 1);
camera2Instance1 = new Camera2(demo, 1);
lightInstance = new Lights(demo);
// Create a new controllers in the scene
skyDraw1Instance1 = new SkyDraw1(demo, 1);
cursorDraw1Instance = new CursorDraw1(demo);
boat1Animation1Instance1 = new Boat1Animation1(demo, 1);
car1Animation1Instance1 = new Car1Animation1(demo, 1);
terrainDraw1Instance1 = new TerrainDraw1(demo, 1);
lakeDraw1Instance1 = new LakeDraw1(demo, 1, 8, 8);
camera2Animation1Instance1 = new Camera2Animation1(demo, 1);
camera2Draw1Instance1 = new Camera2Draw1(demo, 1);
}
public void Create()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null) return;
scene = demo.Engine.Factory.PhysicsSceneManager.Create(sceneInstanceIndexName);
// Initialize maximum number of solver iterations for the scene
scene.MaxIterationCount = 10;
// Initialize time of simulation for the scene
scene.TimeOfSimulation = 1.0f / 15.0f;
Initialize();
// Initialize objects in the scene
skyInstance1.Initialize(scene);
cursorInstance.Initialize(scene);
shotInstance.Initialize(scene);
terrainInstance1.Initialize(scene);
lakeInstance1.Initialize(scene);
defaultShapesInstance.Initialize(scene);
columnInstance1.Initialize(scene);
columnInstance2.Initialize(scene);
pierInstance1.Initialize(scene);
ragdoll2Instance1.Initialize(scene);
boat1Instance1.Initialize(scene);
car1Instance1.Initialize(scene);
box2Instance1.Initialize(scene);
crab1Instance1.Initialize(scene);
torusMesh.Initialize(scene);
camera2Instance1.Initialize(scene);
lightInstance.Initialize(scene);
// Initialize controllers in the scene
skyDraw1Instance1.Initialize(scene);
cursorDraw1Instance.Initialize(scene);
boat1Animation1Instance1.Initialize(scene);
car1Animation1Instance1.Initialize(scene);
terrainDraw1Instance1.Initialize(scene);
lakeDraw1Instance1.Initialize(scene);
camera2Animation1Instance1.Initialize(scene);
camera2Draw1Instance1.Initialize(scene);
// Create shapes shared for all physics objects in the scene
// These shapes are used by all objects in the scene
Demo.CreateSharedShapes(demo, scene);
// Create shapes for objects in the scene
Sky.CreateShapes(demo, scene);
Cursor.CreateShapes(demo, scene);
Shot.CreateShapes(demo, scene);
//terrainInstance1.CreateShapes(demo, scene, 0.0f, false);
//lakeInstance1.CreateShapes(demo, scene, 2, 2, 50.0f, 0.95f, 0.04f, 0.04f, 0.5f, 1.0f, 1.0f, 0.2f, 1.0f, 0.0f, false);
terrainInstance1.CreateShapes(demo, scene, 0.0f, true);
lakeInstance1.CreateShapes(demo, scene, 150, 150, 50.0f, 0.95f, 0.04f, 0.04f, 0.5f, 1.0f, 1.0f, 0.2f, 1.0f, 0.0f, true);
DefaultShapes.CreateShapes(demo, scene);
Column.CreateShapes(demo, scene);
Pier.CreateShapes(demo, scene);
Ragdoll2.CreateShapes(demo, scene);
Boat1.CreateShapes(demo, scene);
Car1.CreateShapes(demo, scene);
Box2.CreateShapes(demo, scene);
Crab1.CreateShapes(demo, scene);
TorusMesh.CreateShapes(demo, scene);
Camera2.CreateShapes(demo, scene);
Lights.CreateShapes(demo, scene);
// Create physics objects for objects in the scene
skyInstance1.Create(new Vector3(0.0f, 0.0f, 0.0f));
cursorInstance.Create();
shotInstance.Create();
terrainInstance1.Create(new Vector3(-316.0f, -128.0f, -2072.0f), new Vector3(32.0f, 256.0f, 32.0f), Quaternion.Identity, 0.0f);
//lakeInstance1.Create(new Vector3(-316.0f, -100.0f, -2072.0f), new Vector3(2400.0f, 1.0f, 2400.0f), Quaternion.Identity, 0.0f);
lakeInstance1.Create(new Vector3(-316.0f, -100.0f, -2072.0f), new Vector3(4.0f, 1.0f, 4.0f), Quaternion.Identity, 0.0f);
defaultShapesInstance.Create();
columnInstance1.Create(new Vector3(10.0f, 30.0f, 20.0f), Vector3.One, Quaternion.Identity, "Box", 4, new Vector3(4.0f, 2.0f, 8.0f), 1.0f, true, 0.1f, 0.05f);
columnInstance2.Create(new Vector3(20.0f, 30.0f, 20.0f), Vector3.One, Quaternion.Identity, "Box", 5, new Vector3(8.0f, 8.0f, 8.0f), 1.0f, true, 0.1f, 0.05f);
pierInstance1.Create(new Vector3(0.0f, 0.0f, 100.0f), Vector3.One, Quaternion.Identity);
ragdoll2Instance1.Create(new Vector3(-10.0f, -50.0f, 70.0f), Vector3.One, Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(45.0f)), false, false, 1.0f);
boat1Instance1.Create(new Vector3(0.0f, -5.0f, 0.0f), Vector3.One, Quaternion.Identity);
car1Instance1.Create(new Vector3(-80.0f, -70.0f, 20.0f), Vector3.One, Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(-115.0f)));
box2Instance1.Create(new Vector3(-20.0f, 0.0f, 40.0f), Vector3.One, Quaternion.Identity, 4, new Vector3(1.0f, 4.0f, 0.1f), 0.02f);
crab1Instance1.Create(new Vector3(-90.0f, -75.0f, -40.0f), new Vector3(0.5f, 0.5f, 0.5f), Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(180.0f)));
torusMesh.Create(new Vector3(10.0f, 20.0f, 50.0f), Vector3.One, Quaternion.Identity, 100000.0f);
camera2Instance1.Create(new Vector3(50.0f, 5.0f, 40.0f), Quaternion.Identity, Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(-220.0f)), Quaternion.Identity, true);
lightInstance.CreateLightPoint(0, "Glass", new Vector3(-120.0f, -97.0f, -140.0f), new Vector3(0.1f, 0.9f, 0.2f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(1, "Glass", new Vector3(-70.0f, -97.0f, -200.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(2, "Glass", new Vector3(-90.0f, -97.0f, -100.0f), new Vector3(0.0f, 0.7f, 0.8f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(3, "Glass", new Vector3(70.0f, -97.0f, -180.0f), new Vector3(1.0f, 0.4f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(4, "Glass", new Vector3(10.0f, -97.0f, -160.0f), new Vector3(0.2f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(5, "Glass", new Vector3(40.0f, -97.0f, -140.0f), new Vector3(0.4f, 0.6f, 1.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(6, "Glass", new Vector3(-40.0f, -95.0f, -190.0f), new Vector3(1.0f, 0.9f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(7, "Glass", new Vector3(-40.0f, -95.0f, -140.0f), new Vector3(0.5f, 0.7f, 0.1f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(8, "Glass", new Vector3(-40.0f, -85.0f, -90.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(9, "Glass", new Vector3(-10.0f, -95.0f, -190.0f), new Vector3(1.0f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(10, "Glass", new Vector3(-10.0f, -95.0f, -140.0f), new Vector3(0.3f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(11, "Glass", new Vector3(-10.0f, -85.0f, -90.0f), new Vector3(1.0f, 1.0f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(12, "Glass", new Vector3(-40.0f, -85.0f, -290.0f), new Vector3(0.5f, 0.7f, 0.1f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(13, "Glass", new Vector3(-40.0f, -95.0f, -240.0f), new Vector3(1.0f, 1.0f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(14, "Glass", new Vector3(-10.0f, -85.0f, -290.0f), new Vector3(1.0f, 0.9f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(15, "Glass", new Vector3(-10.0f, -95.0f, -240.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(16, "Glass", new Vector3(-60.0f, -69.0f, 20.0f), new Vector3(0.6f, 0.8f, 0.2f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(17, "Glass", new Vector3(-20.0f, -55.0f, 45.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(18, "Glass", new Vector3(10.0f, -72.0f, -20.0f), new Vector3(0.8f, 0.7f, 0.2f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(19, "Glass", new Vector3(25.0f, -55.0f, 25.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(0, "Glass", new Vector3(0.0f, -65.0f, 0.0f), new Vector3(1.0f, 0.5f, 0.2f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(1, "Glass", new Vector3(-5.0f, -55.0f, 40.0f), new Vector3(0.5f, 1.0f, 0.2f), 20.0f, 1.0f);
// Set controllers for objects in the scene
SetControllers();
}
public void Initialize()
{
scene.UserControllers.PostDrawMethods += demo.DrawInfo;
if (scene.Light == null)
{
scene.CreateLight(true);
scene.Light.Type = PhysicsLightType.Directional;
scene.Light.SetDirection(-0.4f, -0.8f, -0.4f, 0.0f);
}
}
public void SetControllers()
{
skyDraw1Instance1.SetControllers();
cursorDraw1Instance.SetControllers();
boat1Animation1Instance1.SetControllers(true);
car1Animation1Instance1.SetControllers(false);
terrainDraw1Instance1.SetControllers();
lakeDraw1Instance1.SetControllers();
camera2Animation1Instance1.SetControllers(true);
camera2Draw1Instance1.SetControllers(false, false, false, false, false, false);
}
public void Refresh(double time)
{
camera2Animation1Instance1.RefreshControllers();
camera2Draw1Instance1.RefreshControllers();
GL.Clear(ClearBufferMask.DepthBufferBit);
scene.Simulate(time);
scene.Draw(time);
if (demo.EnableMenu)
{
GL.Clear(ClearBufferMask.DepthBufferBit);
demo.MenuScene.PhysicsScene.Draw(time);
}
demo.SwapBuffers();
}
public void Remove()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null)
demo.Engine.Factory.PhysicsSceneManager.Remove(sceneInstanceIndexName);
}
public void CreateResources()
{
}
public void DisposeResources()
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace VideoStoreRedux.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Faithlife.Utility
{
/// <summary>
/// Copies data from one stream to another.
/// </summary>
public static class StreamUtility
{
/// <summary>
/// Reads all bytes from the stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>An array of all bytes read from the stream.</returns>
public static byte[] ReadAllBytes(this Stream stream)
{
using var streamMemory = new MemoryStream();
stream.CopyTo(streamMemory);
return streamMemory.ToArray();
}
/// <summary>
/// Reads all bytes from the stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>An array of all bytes read from the stream.</returns>
public static async Task<byte[]> ReadAllBytesAsync(this Stream stream, CancellationToken cancellationToken = default)
{
using var streamMemory = new MemoryStream();
await stream.CopyToAsync(streamMemory, 81920, cancellationToken).ConfigureAwait(false);
return streamMemory.ToArray();
}
/// <summary>
/// Reads <paramref name="count"/> bytes from <paramref name="stream"/> into
/// <paramref name="buffer"/>, starting at the byte given by <paramref name="offset"/>.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="buffer">The buffer to read data into.</param>
/// <param name="offset">The offset within the buffer at which data is first written.</param>
/// <param name="count">The count of bytes to read.</param>
/// <remarks>Unlike Stream.Read, this method will not return fewer bytes than requested
/// unless the end of the stream is reached.</remarks>
public static int ReadBlock(this Stream stream, byte[] buffer, int offset, int count)
{
// check arguments
if (stream is null)
throw new ArgumentNullException(nameof(stream));
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || buffer.Length - offset < count)
throw new ArgumentOutOfRangeException(nameof(count));
// track total bytes read
var totalBytesRead = 0;
while (count > 0)
{
// read data
var bytesRead = stream.Read(buffer, offset, count);
// check for end of stream
if (bytesRead == 0)
break;
// move to next block
offset += bytesRead;
count -= bytesRead;
totalBytesRead += bytesRead;
}
return totalBytesRead;
}
/// <summary>
/// Reads <paramref name="count"/> bytes from <paramref name="stream"/> into
/// <paramref name="buffer"/>, starting at the byte given by <paramref name="offset"/>.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="buffer">The buffer to read data into.</param>
/// <param name="offset">The offset within the buffer at which data is first written.</param>
/// <param name="count">The count of bytes to read.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <remarks>Unlike Stream.ReadAsync, this method will not return fewer bytes than requested
/// unless the end of the stream is reached.</remarks>
public static async Task<int> ReadBlockAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
{
// check arguments
if (stream is null)
throw new ArgumentNullException(nameof(stream));
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || buffer.Length - offset < count)
throw new ArgumentOutOfRangeException(nameof(count));
// track total bytes read
var totalBytesRead = 0;
while (count > 0)
{
// read data
#if NETSTANDARD2_0
var bytesRead = await stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
#else
var bytesRead = await stream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
#endif
// check for end of stream
if (bytesRead == 0)
break;
// move to next block
offset += bytesRead;
count -= bytesRead;
totalBytesRead += bytesRead;
}
return totalBytesRead;
}
/// <summary>
/// Reads exactly <paramref name="count"/> bytes from <paramref name="stream"/>.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="count">The count of bytes to read.</param>
/// <returns>A new byte array containing the data read from the stream.</returns>
public static byte[] ReadExactly(this Stream stream, int count)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
var buffer = new byte[count];
ReadExactly(stream, buffer, 0, count);
return buffer;
}
/// <summary>
/// Reads exactly <paramref name="count"/> bytes from <paramref name="stream"/>.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="count">The count of bytes to read.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A new byte array containing the data read from the stream.</returns>
public static async Task<byte[]> ReadExactlyAsync(this Stream stream, int count, CancellationToken cancellationToken = default)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
var buffer = new byte[count];
await ReadExactlyAsync(stream, buffer, 0, count, cancellationToken).ConfigureAwait(false);
return buffer;
}
/// <summary>
/// Reads exactly <paramref name="count"/> bytes from <paramref name="stream"/> into
/// <paramref name="buffer"/>, starting at the byte given by <paramref name="offset"/>.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="buffer">The buffer to read data into.</param>
/// <param name="offset">The offset within the buffer at which data is first written.</param>
/// <param name="count">The count of bytes to read.</param>
public static void ReadExactly(this Stream stream, byte[] buffer, int offset, int count)
{
if (stream.ReadBlock(buffer, offset, count) != count)
throw new EndOfStreamException();
}
/// <summary>
/// Reads exactly <paramref name="count"/> bytes from <paramref name="stream"/> into
/// <paramref name="buffer"/>, starting at the byte given by <paramref name="offset"/>.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="buffer">The buffer to read data into.</param>
/// <param name="offset">The offset within the buffer at which data is first written.</param>
/// <param name="count">The count of bytes to read.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
{
if (await stream.ReadBlockAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false) != count)
throw new EndOfStreamException();
}
/// <summary>
/// Uses <see cref="RebasedStream"/> and/or <see cref="TruncatedStream"/> to create a
/// read-only partial stream wrapper.
/// </summary>
/// <param name="stream">The stream to wrap.</param>
/// <param name="offset">The desired offset into the wrapped stream, which is immediately
/// seeked to that position.</param>
/// <param name="length">The desired length of the partial stream (optional).</param>
/// <param name="ownership">Indicates the ownership of the wrapped stream.</param>
/// <returns>The read-only partial stream wrapper.</returns>
/// <remarks>If <paramref name="offset"/> is zero and <paramref name="length"/> is null,
/// the stream is returned unwrapped.</remarks>
public static Stream CreatePartialStream(Stream stream, long offset, long? length, Ownership ownership)
{
if (offset != 0)
{
stream.Position = offset;
stream = new RebasedStream(stream, ownership);
}
if (length.HasValue)
stream = new TruncatedStream(stream, length.Value, ownership);
return stream;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NLog;
using PoESkillTree.Engine.Utils;
using PoESkillTree.Localization;
using PoESkillTree.Model.Builds;
using PoESkillTree.Utils;
namespace PoESkillTree.Model.Serialization
{
/// <summary>
/// Can deserialize PersistentData with the new build saving structure.
/// </summary>
public class PersistentDataDeserializerCurrent : AbstractPersistentDataDeserializer
{
private static readonly ILogger Log = LogManager.GetCurrentClassLogger();
private string _currentBuildPath;
private string _selectedBuildPath;
// 2.3.0 was released as 2.3.0.1052, this is for everything after that version
public PersistentDataDeserializerCurrent()
: base("2.3.0.1053", "999.0")
{
DeserializesBuildsSavePath = true;
}
public override void DeserializePersistentDataFile(string xmlString)
{
var obj = XmlSerializationUtils.DeserializeString<XmlPersistentData>(xmlString);
PersistentData.Options = obj.Options;
obj.StashBookmarks?.ForEach(PersistentData.StashBookmarks.Add);
obj.LeagueStashes?.ForEach(l => PersistentData.LeagueStashes[l.Name] = l.Bookmarks);
_currentBuildPath = obj.CurrentBuildPath;
_selectedBuildPath = obj.SelectedBuildPath;
}
protected override async Task DeserializeAdditionalFilesAsync()
{
await DeserializeBuildsAsync();
var current = BuildForPath(_currentBuildPath) as PoEBuild ?? SelectOrCreateCurrentBuild();
PersistentData.CurrentBuild = current;
PersistentData.SelectedBuild = BuildForPath(_selectedBuildPath) as PoEBuild;
}
/// <summary>
/// Clears all builds and deserializes them again.
/// </summary>
/// <returns></returns>
public async Task ReloadBuildsAsync()
{
PersistentData.RootBuild.Builds.Clear();
await DeserializeBuildsAsync();
var current = SelectOrCreateCurrentBuild();
PersistentData.CurrentBuild = current;
PersistentData.SelectedBuild = current;
}
/// <summary>
/// Imports the build located at <paramref name="buildPath"/>. <see cref="IPersistentData.SaveBuild"/> may be
/// called by this method.
/// </summary>
public async Task ImportBuildFromFileAsync(string buildPath)
{
const string extension = SerializationConstants.BuildFileExtension;
if (!File.Exists(buildPath) || Path.GetExtension(buildPath) != extension)
{
Log.Error($"Could not import build file from {buildPath}");
var message = string.Format(
L10n.Message(
"Could not import build file, only existing files with the extension {0} can be imported."),
extension);
await DialogCoordinator.ShowErrorAsync(PersistentData, message, title: L10n.Message("Import failed"));
return;
}
var unifiedBuildsSavePath = PersistentData.Options.BuildsSavePath.Replace(Path.AltDirectorySeparatorChar,
Path.DirectorySeparatorChar);
var unifiedPath = buildPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
if (unifiedPath.StartsWith(unifiedBuildsSavePath))
{
// If BuildsSavePath is part of buildPath, just set it as current and selected build
// Remove BuildsSavePath
var relativePath = unifiedPath.Remove(0, unifiedBuildsSavePath.Length + 1);
// Remove extension
var path = relativePath.Remove(relativePath.Length - extension.Length);
var build = BuildForPath(path) as PoEBuild;
if (build == null)
{
Log.Warn($"Import failed, build with path {path} not found");
return;
}
PersistentData.CurrentBuild = build;
PersistentData.SelectedBuild = build;
}
else
{
// Else, proper import
var build = await ImportBuildAsync(
async () => await XmlSerializationUtils.DeserializeFileAsync<XmlBuild>(buildPath));
if (build != null)
{
build.Name = Util.FindDistinctName(build.Name, PersistentData.RootBuild.Builds.Select(b => b.Name));
PersistentData.RootBuild.Builds.Add(build);
PersistentData.CurrentBuild = build;
PersistentData.SelectedBuild = build;
PersistentData.SaveBuild(PersistentData.RootBuild);
}
}
}
/// <summary>
/// Imports the build given as a xml string. <see cref="IPersistentData.SaveBuild"/> may be
/// called by this method.
/// </summary>
public Task<PoEBuild> ImportBuildFromStringAsync(string buildXml)
{
return ImportBuildAsync(
() => Task.FromResult(XmlSerializationUtils.DeserializeString<XmlBuild>(buildXml)));
}
private async Task<PoEBuild> ImportBuildAsync(Func<Task<XmlBuild>> supplier)
{
try
{
var xmlBuild = await supplier();
var build = ConvertFromXmlBuild(xmlBuild);
if (!CheckVersion(xmlBuild.Version))
{
Log.Warn($"Build is of an old version and can't be imported (version {xmlBuild.Version})");
await DialogCoordinator.ShowWarningAsync(PersistentData,
L10n.Message("Build is of an old version and can't be imported"),
title: L10n.Message("Import failed"));
return null;
}
return build;
}
catch (Exception e)
{
Log.Error(e, "Error while importing build");
await DialogCoordinator.ShowErrorAsync(PersistentData, L10n.Message("Could not import build"),
e.Message, L10n.Message("Import failed"));
return null;
}
}
private PoEBuild SelectOrCreateCurrentBuild()
{
var current = PersistentData.RootBuild.BuildsPreorder().FirstOrDefault();
if (current == null)
{
current = CreateDefaultCurrentBuild();
current.Name = Util.FindDistinctName(current.Name, PersistentData.RootBuild.Builds.Select(b => b.Name));
PersistentData.RootBuild.Builds.Add(current);
}
return current;
}
private async Task DeserializeBuildsAsync()
{
var path = PersistentData.Options.BuildsSavePath;
if (!Directory.Exists(path))
return;
await DeserializeFolderAsync(path, PersistentData.RootBuild);
}
private static async Task DeserializeBuildsAsync(string buildFolderPath, BuildFolder folder, IEnumerable<string> buildNames)
{
var buildTasks = new List<Task<IBuild>>();
foreach (var directoryPath in Directory.EnumerateDirectories(buildFolderPath))
{
var fileName = Path.GetFileName(directoryPath);
var build = new BuildFolder { Name = SerializationUtils.DecodeFileName(fileName) };
buildTasks.Add(DeserializeFolderAsync(directoryPath, build));
}
foreach (var filePath in Directory.EnumerateFiles(buildFolderPath))
{
if (Path.GetExtension(filePath) != SerializationConstants.BuildFileExtension)
continue;
buildTasks.Add(DeserializeBuildAsync(filePath));
}
var builds = new Dictionary<string, IBuild>();
foreach (var buildTask in buildTasks)
{
var build = await buildTask;
if (build != null)
builds[build.Name] = build;
}
// Add the builds ordered by buildNames
foreach (var buildName in buildNames)
{
if (builds.ContainsKey(buildName))
{
folder.Builds.Add(builds[buildName]);
builds.Remove(buildName);
}
}
// Add builds not in buildNames last
foreach (var build in builds.Values)
{
folder.Builds.Add(build);
}
}
private static async Task<IBuild> DeserializeFolderAsync(string path, BuildFolder folder)
{
var fullPath = Path.Combine(path, SerializationConstants.BuildFolderFileName);
XmlBuildFolder xmlFolder;
if (File.Exists(fullPath))
{
xmlFolder = await DeserializeAsync<XmlBuildFolder>(fullPath);
}
else
{
xmlFolder = null;
Log.Info($"Build folder file {fullPath} does not exist. Contained builds will be ordered arbitrarily.");
}
if (xmlFolder != null && CheckVersion(xmlFolder.Version))
{
folder.IsExpanded = xmlFolder.IsExpanded;
await DeserializeBuildsAsync(path, folder, xmlFolder.Builds);
}
else
{
await DeserializeBuildsAsync(path, folder, Enumerable.Empty<string>());
}
return folder;
}
private static async Task<IBuild> DeserializeBuildAsync(string path)
{
var xmlBuild = await DeserializeAsync<XmlBuild>(path).ConfigureAwait(false);
var build = ConvertFromXmlBuild(xmlBuild);
if (build != null && CheckVersion(xmlBuild.Version))
{
build.KeepChanges();
return build;
}
var backupPath = path + ".bad";
Log.Warn($"Moving build file {path} to {backupPath} as it could not be deserialized");
FileUtils.DeleteIfExists(backupPath);
File.Move(path, backupPath);
return null;
}
private static bool CheckVersion(string buildVersion)
{
var version = new Version(buildVersion);
var compare = SerializationConstants.BuildVersion.CompareTo(version);
if (compare > 0)
{
throw new InvalidOperationException("Build of old version found, a converter needs to be implemented.");
}
if (compare < 0)
{
Log.Error(
"Build has higher version than supported "
+ $"(version {buildVersion}, supported is {SerializationConstants.BuildVersion})\n");
return false;
}
return true;
}
private static async Task<T> DeserializeAsync<T>(string path)
{
try
{
return await XmlSerializationUtils.DeserializeFileAsync<T>(path, true).ConfigureAwait(false);
}
catch (Exception e)
{
Log.Error(e, $"Could not deserialize file from {path} as type {typeof(T)}");
return default(T);
}
}
private IBuild BuildForPath(string path)
{
if (path == null)
return null;
IBuild build = PersistentData.RootBuild;
foreach (var part in path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
{
var folder = build as BuildFolder;
if (folder == null)
return null;
var name = SerializationUtils.DecodeFileName(part);
build = folder.Builds.FirstOrDefault(child => child.Name == name);
if (build == null)
return null;
}
return build;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Diagnostics;
namespace System.Data.Linq {
using System.Data.Linq.Mapping;
using System.Data.Linq.Provider;
/// <summary>
/// Describes the type of change the entity will undergo when submitted to the database.
/// </summary>
public enum ChangeAction {
/// <summary>
/// The entity will not be submitted.
/// </summary>
None = 0,
/// <summary>
/// The entity will be deleted.
/// </summary>
Delete,
/// <summary>
/// The entity will be inserted.
/// </summary>
Insert,
/// <summary>
/// The entity will be updated.
/// </summary>
Update
}
internal class ChangeProcessor {
CommonDataServices services;
DataContext context;
ChangeTracker tracker;
ChangeDirector changeDirector;
EdgeMap currentParentEdges;
EdgeMap originalChildEdges;
ReferenceMap originalChildReferences;
internal ChangeProcessor(CommonDataServices services, DataContext context) {
this.services = services;
this.context = context;
this.tracker = services.ChangeTracker;
this.changeDirector = services.ChangeDirector;
this.currentParentEdges = new EdgeMap();
this.originalChildEdges = new EdgeMap();
this.originalChildReferences = new ReferenceMap();
}
internal void SubmitChanges(ConflictMode failureMode) {
this.TrackUntrackedObjects();
// Must apply inferred deletions only after any untracked objects
// are tracked
this.ApplyInferredDeletions();
this.BuildEdgeMaps();
var list = this.GetOrderedList();
ValidateAll(list);
int numUpdatesAttempted = 0;
ChangeConflictSession conflictSession = new ChangeConflictSession(this.context);
List<ObjectChangeConflict> conflicts = new List<ObjectChangeConflict>();
List<TrackedObject> deletedItems = new List<TrackedObject>();
List<TrackedObject> insertedItems = new List<TrackedObject>();
List<TrackedObject> syncDependentItems = new List<TrackedObject>();
foreach (TrackedObject item in list) {
try {
if (item.IsNew) {
if (item.SynchDependentData()) {
syncDependentItems.Add(item);
}
changeDirector.Insert(item);
// store all inserted items for post processing
insertedItems.Add(item);
}
else if (item.IsDeleted) {
// Delete returns 1 if the delete was successfull, 0 if the row exists
// but wasn't deleted due to an OC conflict, or -1 if the row was
// deleted by another context (no OC conflict in this case)
numUpdatesAttempted++;
int ret = changeDirector.Delete(item);
if (ret == 0) {
conflicts.Add(new ObjectChangeConflict(conflictSession, item, false));
}
else {
// store all deleted items for post processing
deletedItems.Add(item);
}
}
else if (item.IsPossiblyModified) {
if (item.SynchDependentData()) {
syncDependentItems.Add(item);
}
if (item.IsModified) {
CheckForInvalidChanges(item);
numUpdatesAttempted++;
if (changeDirector.Update(item) <= 0) {
conflicts.Add(new ObjectChangeConflict(conflictSession, item));
}
}
}
}
catch (ChangeConflictException) {
conflicts.Add(new ObjectChangeConflict(conflictSession, item));
}
if (conflicts.Count > 0 && failureMode == ConflictMode.FailOnFirstConflict) {
break;
}
}
// if we have accumulated any failed updates, throw the exception now
if (conflicts.Count > 0) {
// First we need to rollback any value that have already been auto-[....]'d, since the values are no longer valid on the server
changeDirector.RollbackAutoSync();
// Also rollback any dependent items that were [....]'d, since their parent values may have been rolled back
foreach (TrackedObject syncDependentItem in syncDependentItems) {
Debug.Assert(syncDependentItem.IsNew || syncDependentItem.IsPossiblyModified, "SynchDependent data should only be rolled back for new and modified objects.");
syncDependentItem.SynchDependentData();
}
this.context.ChangeConflicts.Fill(conflicts);
throw CreateChangeConflictException(numUpdatesAttempted, conflicts.Count);
}
else {
// No conflicts occurred, so we don't need to save the rollback values anymore
changeDirector.ClearAutoSyncRollback();
}
// Only after all updates have been sucessfully processed do we want to make
// post processing modifications to the objects and/or cache state.
PostProcessUpdates(insertedItems, deletedItems);
}
private void PostProcessUpdates(List<TrackedObject> insertedItems, List<TrackedObject> deletedItems) {
// perform post delete processing
foreach (TrackedObject deletedItem in deletedItems) {
// remove deleted item from identity cache
this.services.RemoveCachedObjectLike(deletedItem.Type, deletedItem.Original);
ClearForeignKeyReferences(deletedItem);
}
// perform post insert processing
foreach (TrackedObject insertedItem in insertedItems) {
object lookup = this.services.InsertLookupCachedObject(insertedItem.Type, insertedItem.Current);
if (lookup != insertedItem.Current) {
throw new DuplicateKeyException(insertedItem.Current, Strings.DatabaseGeneratedAlreadyExistingKey);
}
insertedItem.InitializeDeferredLoaders();
}
}
/// <summary>
/// Clears out the foreign key values and parent object references for deleted objects on the child side of a relationship.
/// For bi-directional relationships, also performs the following fixup:
/// - for 1:N we remove the deleted entity from the opposite EntitySet or collection
/// - for 1:1 we null out the back reference
/// </summary>
private void ClearForeignKeyReferences(TrackedObject to) {
Debug.Assert(to.IsDeleted, "Foreign key reference cleanup should only happen on Deleted objects.");
foreach (MetaAssociation assoc in to.Type.Associations) {
if (assoc.IsForeignKey) {
// If there is a member on the other side referring back to us (i.e. this is a bi-directional relationship),
// we want to do a cache lookup to find the other side, then will remove ourselves from that collection.
// This cache lookup is only possible if the other key is the primary key, since that is the only way items can be found in the cache.
if (assoc.OtherMember != null && assoc.OtherKeyIsPrimaryKey) {
Debug.Assert(assoc.OtherMember.IsAssociation, "OtherMember of the association is expected to also be an association.");
// Search the cache for the target of the association, since
// it might not be loaded on the object being deleted, and we
// don't want to force a load.
object[] keyValues = CommonDataServices.GetForeignKeyValues(assoc, to.Current);
object cached = this.services.IdentityManager.Find(assoc.OtherType, keyValues);
if (cached != null) {
if (assoc.OtherMember.Association.IsMany) {
// Note that going through the IList interface handles
// EntitySet as well as POCO collections that implement IList
// and are not FixedSize.
System.Collections.IList collection = assoc.OtherMember.MemberAccessor.GetBoxedValue(cached) as System.Collections.IList;
if (collection != null && !collection.IsFixedSize) {
collection.Remove(to.Current);
// Explicitly clear the foreign key values and parent object reference
ClearForeignKeysHelper(assoc, to.Current);
}
}
else {
// Null out the other association. Since this is a 1:1 association,
// we're not concerned here with causing a deferred load, since the
// target is already cached (since we're deleting it).
assoc.OtherMember.MemberAccessor.SetBoxedValue(ref cached, null);
// Explicitly clear the foreign key values and parent object reference
ClearForeignKeysHelper(assoc, to.Current);
}
}
// else the item was not found in the cache, so there is no fixup that has to be done
// We are explicitly not calling ClearForeignKeysHelper because it breaks existing shipped behavior and we want to maintain backward compatibility
}
else {
// This is a unidirectional relationship or we have no way to look up the other side in the cache, so just clear our own side
ClearForeignKeysHelper(assoc, to.Current);
}
}
// else this is not the 1-side (foreign key) of the relationship, so there is nothing for us to do
}
}
// Ensure the the member and foreign keys are nulled so that after trackedInstance is deleted,
// the object does not appear to be associated with the other side anymore. This prevents the deleted object
// from referencing objects still in the cache, but also will prevent the related object from being implicitly loaded
private static void ClearForeignKeysHelper(MetaAssociation assoc, object trackedInstance) {
Debug.Assert(assoc.IsForeignKey, "Foreign key clearing should only happen on foreign key side of the association.");
Debug.Assert(assoc.ThisMember.IsAssociation, "Expected ThisMember of an association to always be an association.");
// If this member is one of our deferred loaders, and it does not already have a value, explicitly set the deferred source to
// null so that when we set the association member itself to null later, it doesn't trigger an implicit load.
// This is only necessary if the value has not already been assigned or set, because otherwise we won't implicitly load anyway when the member is accessed.
MetaDataMember thisMember = assoc.ThisMember;
if (thisMember.IsDeferred &&
!(thisMember.StorageAccessor.HasAssignedValue(trackedInstance) || thisMember.StorageAccessor.HasLoadedValue(trackedInstance)))
{
// If this is a deferred member, set the value directly in the deferred accessor instead of going
// through the normal member accessor, so that we don't trigger an implicit load.
thisMember.DeferredSourceAccessor.SetBoxedValue(ref trackedInstance, null);
}
// Notify the object that the relationship should be considered deleted.
// This allows the object to do its own fixup even when we can't do it automatically.
thisMember.MemberAccessor.SetBoxedValue(ref trackedInstance, null);
// Also set the foreign key values to null if possible
for (int i = 0, n = assoc.ThisKey.Count; i < n; i++) {
MetaDataMember thisKey = assoc.ThisKey[i];
if (thisKey.CanBeNull) {
thisKey.StorageAccessor.SetBoxedValue(ref trackedInstance, null);
}
}
}
private static void ValidateAll(IEnumerable<TrackedObject> list) {
foreach (var item in list) {
if (item.IsNew) {
item.SynchDependentData();
if (item.Type.HasAnyValidateMethod) {
SendOnValidate(item.Type, item, ChangeAction.Insert);
}
} else if (item.IsDeleted) {
if (item.Type.HasAnyValidateMethod) {
SendOnValidate(item.Type, item, ChangeAction.Delete);
}
} else if (item.IsPossiblyModified) {
item.SynchDependentData();
if (item.IsModified && item.Type.HasAnyValidateMethod) {
SendOnValidate(item.Type, item, ChangeAction.Update);
}
}
}
}
private static void SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction) {
if (type != null) {
SendOnValidate(type.InheritanceBase, item, changeAction);
if (type.OnValidateMethod != null) {
try {
type.OnValidateMethod.Invoke(item.Current, new object[] { changeAction });
} catch (TargetInvocationException tie) {
if (tie.InnerException != null) {
throw tie.InnerException;
}
throw;
}
}
}
}
internal string GetChangeText() {
this.ObserveUntrackedObjects();
// Must apply inferred deletions only after any untracked objects
// are tracked
this.ApplyInferredDeletions();
this.BuildEdgeMaps();
// append change text only
StringBuilder changeText = new StringBuilder();
foreach (TrackedObject item in this.GetOrderedList()) {
if (item.IsNew) {
item.SynchDependentData();
changeDirector.AppendInsertText(item, changeText);
}
else if (item.IsDeleted) {
changeDirector.AppendDeleteText(item, changeText);
}
else if (item.IsPossiblyModified) {
item.SynchDependentData();
if (item.IsModified) {
changeDirector.AppendUpdateText(item, changeText);
}
}
}
return changeText.ToString();
}
internal ChangeSet GetChangeSet() {
List<object> newEntities = new List<object>();
List<object> deletedEntities = new List<object>();
List<object> changedEntities = new List<object>();
this.ObserveUntrackedObjects();
// Must apply inferred deletions only after any untracked objects
// are tracked
this.ApplyInferredDeletions();
foreach (TrackedObject item in this.tracker.GetInterestingObjects()) {
if (item.IsNew) {
item.SynchDependentData();
newEntities.Add(item.Current);
}
else if (item.IsDeleted) {
deletedEntities.Add(item.Current);
}
else if (item.IsPossiblyModified) {
item.SynchDependentData();
if (item.IsModified) {
changedEntities.Add(item.Current);
}
}
}
return new ChangeSet(newEntities.AsReadOnly(), deletedEntities.AsReadOnly(), changedEntities.AsReadOnly());
}
// verify that primary key and db-generated values have not changed
private static void CheckForInvalidChanges(TrackedObject tracked) {
foreach (MetaDataMember mem in tracked.Type.PersistentDataMembers) {
if (mem.IsPrimaryKey || mem.IsDbGenerated || mem.IsVersion) {
if (tracked.HasChangedValue(mem)) {
if (mem.IsPrimaryKey) {
throw Error.IdentityChangeNotAllowed(mem.Name, tracked.Type.Name);
}
else {
throw Error.DbGeneratedChangeNotAllowed(mem.Name, tracked.Type.Name);
}
}
}
}
}
/// <summary>
/// Create an ChangeConflictException with the best message
/// </summary>
static private ChangeConflictException CreateChangeConflictException(int totalUpdatesAttempted, int failedUpdates) {
string msg = Strings.RowNotFoundOrChanged;
if (totalUpdatesAttempted > 1) {
msg = Strings.UpdatesFailedMessage(failedUpdates, totalUpdatesAttempted);
}
return new ChangeConflictException(msg);
}
internal void TrackUntrackedObjects() {
Dictionary<object, object> visited = new Dictionary<object, object>();
// search for untracked new objects
List<TrackedObject> items = new List<TrackedObject>(this.tracker.GetInterestingObjects());
foreach (TrackedObject item in items) {
this.TrackUntrackedObjects(item.Type, item.Current, visited);
}
}
internal void ApplyInferredDeletions() {
foreach (TrackedObject item in this.tracker.GetInterestingObjects()) {
if (item.CanInferDelete()) {
// based on DeleteOnNull specifications on the item's associations,
// a deletion can be inferred for this item. The actual state transition
// is dependent on the current item state.
if (item.IsNew) {
item.ConvertToRemoved();
}
else if (item.IsPossiblyModified || item.IsModified) {
item.ConvertToDeleted();
}
}
}
}
private void TrackUntrackedObjects(MetaType type, object item, Dictionary<object, object> visited) {
if (!visited.ContainsKey(item)) {
visited.Add(item, item);
TrackedObject tracked = this.tracker.GetTrackedObject(item);
if (tracked == null) {
tracked = this.tracker.Track(item);
tracked.ConvertToNew();
}
else if (tracked.IsDead || tracked.IsRemoved) {
// ignore
return;
}
// search parents (objects we are dependent on)
foreach (RelatedItem parent in this.services.GetParents(type, item)) {
this.TrackUntrackedObjects(parent.Type, parent.Item, visited);
}
// synch up primary key
if (tracked.IsNew) {
tracked.InitializeDeferredLoaders();
if (!tracked.IsPendingGeneration(tracked.Type.IdentityMembers)) {
tracked.SynchDependentData();
object cached = this.services.InsertLookupCachedObject(tracked.Type, item);
if (cached != item) {
TrackedObject cachedTracked = this.tracker.GetTrackedObject(cached);
Debug.Assert(cachedTracked != null);
if (cachedTracked.IsDeleted || cachedTracked.CanInferDelete()) {
// adding new object with same ID as object being deleted.. turn into modified
tracked.ConvertToPossiblyModified(cachedTracked.Original);
// turn deleted to dead...
cachedTracked.ConvertToDead();
this.services.RemoveCachedObjectLike(tracked.Type, item);
this.services.InsertLookupCachedObject(tracked.Type, item);
}
else if (!cachedTracked.IsDead) {
throw new DuplicateKeyException(item, Strings.CantAddAlreadyExistingKey);
}
}
}
else {
// we may have a generated PK, however we set the PK on this new item to
// match a deleted item
object cached = this.services.GetCachedObjectLike(tracked.Type, item);
if (cached != null) {
TrackedObject cachedTracked = this.tracker.GetTrackedObject(cached);
Debug.Assert(cachedTracked != null);
if (cachedTracked.IsDeleted || cachedTracked.CanInferDelete()) {
// adding new object with same ID as object being deleted.. turn into modified
tracked.ConvertToPossiblyModified(cachedTracked.Original);
// turn deleted to dead...
cachedTracked.ConvertToDead();
this.services.RemoveCachedObjectLike(tracked.Type, item);
this.services.InsertLookupCachedObject(tracked.Type, item);
}
}
}
}
// search children (objects that are dependent on us)
foreach (RelatedItem child in this.services.GetChildren(type, item)) {
this.TrackUntrackedObjects(child.Type, child.Item, visited);
}
}
}
internal void ObserveUntrackedObjects() {
Dictionary<object, object> visited = new Dictionary<object, object>();
List<TrackedObject> items = new List<TrackedObject>(this.tracker.GetInterestingObjects());
foreach (TrackedObject item in items) {
this.ObserveUntrackedObjects(item.Type, item.Current, visited);
}
}
private void ObserveUntrackedObjects(MetaType type, object item, Dictionary<object, object> visited) {
if (!visited.ContainsKey(item)) {
visited.Add(item, item);
TrackedObject tracked = this.tracker.GetTrackedObject(item);
if (tracked == null) {
tracked = this.tracker.Track(item);
tracked.ConvertToNew();
} else if (tracked.IsDead || tracked.IsRemoved) {
// ignore
return;
}
// search parents (objects we are dependent on)
foreach (RelatedItem parent in this.services.GetParents(type, item)) {
this.ObserveUntrackedObjects(parent.Type, parent.Item, visited);
}
// synch up primary key unless its generated.
if (tracked.IsNew) {
if (!tracked.IsPendingGeneration(tracked.Type.IdentityMembers)) {
tracked.SynchDependentData();
}
}
// search children (objects that are dependent on us)
foreach (RelatedItem child in this.services.GetChildren(type, item)) {
this.ObserveUntrackedObjects(child.Type, child.Item, visited);
}
}
}
private TrackedObject GetOtherItem(MetaAssociation assoc, object instance) {
if (instance == null)
return null;
object other = null;
// Don't load unloaded references
if (assoc.ThisMember.StorageAccessor.HasAssignedValue(instance) ||
assoc.ThisMember.StorageAccessor.HasLoadedValue(instance)
) {
other = assoc.ThisMember.MemberAccessor.GetBoxedValue(instance);
}
else if (assoc.OtherKeyIsPrimaryKey) {
// Maybe it's in the cache, but not yet attached through reference.
object[] foreignKeys = CommonDataServices.GetForeignKeyValues(assoc, instance);
other = this.services.GetCachedObject(assoc.OtherType, foreignKeys);
}
// else the other key is not the primary key so there is no way to try to look it up
return (other != null) ? this.tracker.GetTrackedObject(other) : null;
}
private bool HasAssociationChanged(MetaAssociation assoc, TrackedObject item) {
if (item.Original != null && item.Current != null) {
if (assoc.ThisMember.StorageAccessor.HasAssignedValue(item.Current) ||
assoc.ThisMember.StorageAccessor.HasLoadedValue(item.Current)
) {
return this.GetOtherItem(assoc, item.Current) != this.GetOtherItem(assoc, item.Original);
}
else {
object[] currentFKs = CommonDataServices.GetForeignKeyValues(assoc, item.Current);
object[] originaFKs = CommonDataServices.GetForeignKeyValues(assoc, item.Original);
for (int i = 0, n = currentFKs.Length; i < n; i++) {
if (!object.Equals(currentFKs[i], originaFKs[i]))
return true;
}
}
}
return false;
}
private void BuildEdgeMaps() {
this.currentParentEdges.Clear();
this.originalChildEdges.Clear();
this.originalChildReferences.Clear();
List<TrackedObject> list = new List<TrackedObject>(this.tracker.GetInterestingObjects());
foreach (TrackedObject item in list) {
bool isNew = item.IsNew;
MetaType mt = item.Type;
foreach (MetaAssociation assoc in mt.Associations) {
if (assoc.IsForeignKey) {
TrackedObject otherItem = this.GetOtherItem(assoc, item.Current);
TrackedObject dbOtherItem = this.GetOtherItem(assoc, item.Original);
bool pointsToDeleted = (otherItem != null && otherItem.IsDeleted) || (dbOtherItem != null && dbOtherItem.IsDeleted);
bool pointsToNew = (otherItem != null && otherItem.IsNew);
if (isNew || pointsToDeleted || pointsToNew || this.HasAssociationChanged(assoc, item)) {
if (otherItem != null) {
this.currentParentEdges.Add(assoc, item, otherItem);
}
if (dbOtherItem != null) {
if (assoc.IsUnique) {
this.originalChildEdges.Add(assoc, dbOtherItem, item);
}
this.originalChildReferences.Add(dbOtherItem, item);
}
}
}
}
}
}
enum VisitState {
Before,
After
}
private List<TrackedObject> GetOrderedList() {
var objects = this.tracker.GetInterestingObjects().ToList();
// give list an initial order (most likely correct order) to avoid deadlocks in server
var range = Enumerable.Range(0, objects.Count).ToList();
range.Sort((int x, int y) => Compare(objects[x], x, objects[y], y));
var ordered = range.Select(i => objects[i]).ToList();
// permute order if constraint dependencies requires some changes to come before others
var visited = new Dictionary<TrackedObject, VisitState>();
var list = new List<TrackedObject>();
foreach (TrackedObject item in ordered) {
this.BuildDependencyOrderedList(item, list, visited);
}
return list;
}
private static int Compare(TrackedObject x, int xOrdinal, TrackedObject y, int yOrdinal) {
// deal with possible nulls
if (x == y) {
return 0;
}
if (x == null) {
return -1;
}
else if (y == null) {
return 1;
}
// first order by action: Inserts first, Updates, Deletes last
int xAction = x.IsNew ? 0 : x.IsDeleted ? 2 : 1;
int yAction = y.IsNew ? 0 : y.IsDeleted ? 2 : 1;
if (xAction < yAction) {
return -1;
}
else if (xAction > yAction) {
return 1;
}
// no need to order inserts (PK's may not even exist)
if (x.IsNew) {
// keep original order
return xOrdinal.CompareTo(yOrdinal);
}
// second order by type
if (x.Type != y.Type) {
return string.CompareOrdinal(x.Type.Type.FullName, y.Type.Type.FullName);
}
// lastly, order by PK values
int result = 0;
foreach (MetaDataMember mm in x.Type.IdentityMembers) {
object xValue = mm.StorageAccessor.GetBoxedValue(x.Current);
object yValue = mm.StorageAccessor.GetBoxedValue(y.Current);
if (xValue == null) {
if (yValue != null) {
return -1;
}
}
else {
IComparable xc = xValue as IComparable;
if (xc != null) {
result = xc.CompareTo(yValue);
if (result != 0) {
return result;
}
}
}
}
// they are the same? leave in original order
return xOrdinal.CompareTo(yOrdinal);
}
private void BuildDependencyOrderedList(TrackedObject item, List<TrackedObject> list, Dictionary<TrackedObject, VisitState> visited) {
VisitState state;
if (visited.TryGetValue(item, out state)) {
if (state == VisitState.Before) {
throw Error.CycleDetected();
}
return;
}
visited[item] = VisitState.Before;
if (item.IsInteresting) {
if (item.IsDeleted) {
// if 'item' is deleted
// all objects that used to refer to 'item' must be ordered before item
foreach (TrackedObject other in this.originalChildReferences[item]) {
if (other != item) {
this.BuildDependencyOrderedList(other, list, visited);
}
}
}
else {
// if 'item' is new or changed
// for all objects 'other' that 'item' refers to along association 'assoc'
// if 'other' is new then 'other' must be ordered before 'item'
// if 'assoc' is pure one-to-one and some other item 'prevItem' used to refer to 'other'
// then 'prevItem' must be ordered before 'item'
foreach (MetaAssociation assoc in item.Type.Associations) {
if (assoc.IsForeignKey) {
TrackedObject other = this.currentParentEdges[assoc, item];
if (other != null) {
if (other.IsNew) {
// if other is new, visit other first (since item's FK depends on it)
if (other != item || item.Type.DBGeneratedIdentityMember != null) {
this.BuildDependencyOrderedList(other, list, visited);
}
}
else if ((assoc.IsUnique || assoc.ThisKeyIsPrimaryKey)) {
TrackedObject prevItem = this.originalChildEdges[assoc, other];
if (prevItem != null && other != item) {
this.BuildDependencyOrderedList(prevItem, list, visited);
}
}
}
}
}
}
list.Add(item);
}
visited[item] = VisitState.After;
}
class EdgeMap {
Dictionary<MetaAssociation, Dictionary<TrackedObject, TrackedObject>> associations;
internal EdgeMap() {
this.associations = new Dictionary<MetaAssociation, Dictionary<TrackedObject, TrackedObject>>();
}
internal void Add(MetaAssociation assoc, TrackedObject from, TrackedObject to) {
Dictionary<TrackedObject, TrackedObject> pairs;
if (!associations.TryGetValue(assoc, out pairs)) {
pairs = new Dictionary<TrackedObject, TrackedObject>();
associations.Add(assoc, pairs);
}
pairs.Add(from, to);
}
internal TrackedObject this[MetaAssociation assoc, TrackedObject from] {
get {
Dictionary<TrackedObject, TrackedObject> pairs;
if (associations.TryGetValue(assoc, out pairs)) {
TrackedObject to;
if (pairs.TryGetValue(from, out to)) {
return to;
}
}
return null;
}
}
internal void Clear() {
this.associations.Clear();
}
}
class ReferenceMap {
Dictionary<TrackedObject, List<TrackedObject>> references;
internal ReferenceMap() {
this.references = new Dictionary<TrackedObject, List<TrackedObject>>();
}
internal void Add(TrackedObject from, TrackedObject to) {
List<TrackedObject> refs;
if (!references.TryGetValue(from, out refs)) {
refs = new List<TrackedObject>();
references.Add(from, refs);
}
if (!refs.Contains(to))
refs.Add(to);
}
internal IEnumerable<TrackedObject> this[TrackedObject from] {
get {
List<TrackedObject> refs;
if (references.TryGetValue(from, out refs)) {
return refs;
}
return Empty;
}
}
internal void Clear() {
this.references.Clear();
}
private static TrackedObject[] Empty = new TrackedObject[] { };
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function MoveToToy::create( %this )
{
// Initialize the toys settings.
MoveToToy.moveSpeed = 50;
MoveToToy.trackMouse = true;
// Add the custom controls.
addNumericOption("Move Speed", 1, 1000, 1, "setMoveSpeed", MoveToToy.moveSpeed, true, "Sets the linear speed to use when moving to the target position.");
addFlagOption("Track Mouse", "setTrackMouse", MoveToToy.trackMouse, false, "Whether to track the position of the mouse or not." );
// Reset the toy initially.
MoveToToy.reset();
}
//-----------------------------------------------------------------------------
function MoveToToy::destroy( %this )
{
}
//-----------------------------------------------------------------------------
function MoveToToy::reset( %this )
{
// Clear the scene.
SandboxScene.clear();
// Create background.
%this.createBackground();
// Create target.
%this.createTarget();
// Create sight.
%this.createSight();
}
//-----------------------------------------------------------------------------
function MoveToToy::createBackground( %this )
{
// Create the sprite.
%object = new Sprite();
// Set the sprite as "static" so it is not affected by gravity.
%object.setBodyType( static );
// Always try to configure a scene-object prior to adding it to a scene for best performance.
// Set the position.
%object.Position = "0 0";
// Set the size.
%object.Size = "100 75";
// Set to the furthest background layer.
%object.SceneLayer = 31;
// Set an image.
%object.Image = "ToyAssets:highlightBackground";
// Set the blend color.
%object.BlendColor = SlateGray;
// Add the sprite to the scene.
SandboxScene.add( %object );
}
//-----------------------------------------------------------------------------
function MoveToToy::createSight( %this )
{
// Create the sprite.
%object = new Sprite();
// Set the sight object.
MoveToToy.SightObject = %object;
// Set the static image.
%object.Image = "ToyAssets:Crosshair2";
// Set the blend color.
%object.BlendColor = Lime;
// Set the transparency.
%object.setBlendAlpha( 0.5 );
// Set a useful size.
%object.Size = 40;
// Set the sprite rotating to make it more interesting.
%object.AngularVelocity = -90;
// Add to the scene.
SandboxScene.add( %object );
}
//-----------------------------------------------------------------------------
function MoveToToy::createTarget( %this )
{
// Create the sprite.
%object = new Sprite();
// Set the target object.
MoveToToy.TargetObject = %object;
// Set the static image.
%object.Image = "ToyAssets:Crosshair3";
// Set the blend color.
%object.BlendColor = DarkOrange;
// Set a useful size.
%object.Size = 20;
// Set the sprite rotating to make it more interesting.
%object.AngularVelocity = 60;
// Add to the scene.
SandboxScene.add( %object );
}
//-----------------------------------------------------------------------------
function MoveToToy::setMoveSpeed( %this, %value )
{
%this.moveSpeed = %value;
}
//-----------------------------------------------------------------------------
function MoveToToy::setTrackMouse( %this, %value )
{
%this.trackMouse = %value;
}
//-----------------------------------------------------------------------------
function MoveToToy::onTouchDown(%this, %touchID, %worldPosition)
{
// Set the target to the touched position.
MoveToToy.TargetObject.Position = %worldPosition;
// Move the sight to the touched position.
MoveToToy.SightObject.MoveTo( %worldPosition, MoveToToy.moveSpeed, true, true );
}
//-----------------------------------------------------------------------------
function MoveToToy::onTouchDragged(%this, %touchID, %worldPosition)
{
// Finish if not tracking the mouse.
if ( !MoveToToy.trackMouse )
return;
// Set the target to the touched position.
MoveToToy.TargetObject.Position = %worldPosition;
// Move the sight to the touched position.
MoveToToy.SightObject.MoveTo( %worldPosition, MoveToToy.moveSpeed, true, true );
}
function MoveToToy::test1(%this)
{
MoveToToy.TargetObject.setPosition("-500 20");
MoveToToy.SightObject.setPosition("-500 -20");
MoveToToy.TargetObject.setLinearVelocityX(0);
MoveToToy.TargetObject.schedule(1000, "setLinearVelocityX", "150");
MoveToToy.SightObject.schedule(1000, "moveTo", "500 -20", "150");
%this.report();
}
function MoveToToy::report(%this)
{
echo("Target speed is " @ MoveToToy.TargetObject.getLinearVelocityX() @ " and position is " @ MoveToToy.TargetObject.getPositionX());
echo("Sight speed is " @ MoveToToy.SightObject.getLinearVelocityX() @ " and position is " @ MoveToToy.SightObject.getPositionX());
%this.schedule(1000, "report");
}
| |
namespace Fixtures.MirrorPrimitives
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class SwaggerDataTypesClient : ServiceClient<SwaggerDataTypesClient>, ISwaggerDataTypesClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
public SwaggerDataTypesClient() : base()
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDataTypesClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDataTypesClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDataTypesClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.Initialize();
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost:3000/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver()
};
DeserializationSettings = new JsonSerializerSettings{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver()
};
}
/// <summary>
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetProduct", tracingParameters);
}
// Construct URL
string url = this.BaseUri.AbsoluteUri +
"//datatypes";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
httpRequest.Headers.Add("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> PutProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutProduct", tracingParameters);
}
// Construct URL
string url = this.BaseUri.AbsoluteUri +
"//datatypes";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
httpRequest.Headers.Add("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> PostProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PostProduct", tracingParameters);
}
// Construct URL
string url = this.BaseUri.AbsoluteUri +
"//datatypes";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
httpRequest.Headers.Add("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PatchProduct", tracingParameters);
}
// Construct URL
string url = this.BaseUri.AbsoluteUri +
"//datatypes";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
httpRequest.Headers.Add("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections.Immutable
{
public sealed partial class ImmutableSortedDictionary<TKey, TValue>
{
/// <summary>
/// A node in the AVL tree storing this map.
/// </summary>
[DebuggerDisplay("{_key} = {_value}")]
internal sealed class Node : IBinaryTree<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>
{
/// <summary>
/// The default empty node.
/// </summary>
internal static readonly Node EmptyNode = new Node();
/// <summary>
/// The key associated with this node.
/// </summary>
private readonly TKey _key;
/// <summary>
/// The value associated with this node.
/// </summary>
/// <remarks>
/// Sadly this field could be readonly but doing so breaks serialization due to bug:
/// http://connect.microsoft.com/VisualStudio/feedback/details/312970/weird-argumentexception-when-deserializing-field-in-typedreferences-cannot-be-static-or-init-only
/// </remarks>
private TValue _value;
/// <summary>
/// A value indicating whether this node has been frozen (made immutable).
/// </summary>
/// <remarks>
/// Nodes must be frozen before ever being observed by a wrapping collection type
/// to protect collections from further mutations.
/// </remarks>
private bool _frozen;
/// <summary>
/// The depth of the tree beneath this node.
/// </summary>
private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2)
/// <summary>
/// The left tree.
/// </summary>
private Node _left;
/// <summary>
/// The right tree.
/// </summary>
private Node _right;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class
/// that is pre-frozen.
/// </summary>
private Node()
{
Contract.Ensures(this.IsEmpty);
_frozen = true; // the empty node is *always* frozen.
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class
/// that is not yet frozen.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <param name="frozen">Whether this node is prefrozen.</param>
private Node(TKey key, TValue value, Node left, Node right, bool frozen = false)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
Contract.Ensures(!this.IsEmpty);
Contract.Ensures(_key != null);
Contract.Ensures(_left == left);
Contract.Ensures(_right == right);
_key = key;
_value = value;
_left = left;
_right = right;
_height = checked((byte)(1 + Math.Max(left._height, right._height)));
_frozen = frozen;
}
/// <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
{
Contract.Ensures((_left != null && _right != null) || Contract.Result<bool>());
return _left == null;
}
}
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Right
{
get { return _right; }
}
/// <summary>
/// Gets the height of the tree beneath this node.
/// </summary>
public int Height { get { return _height; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
public Node Left { get { return _left; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
public Node Right { get { return _right; } }
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Right
{
get { return _right; }
}
/// <summary>
/// Gets the value represented by the current node.
/// </summary>
public KeyValuePair<TKey, TValue> Value
{
get { return new KeyValuePair<TKey, TValue>(_key, _value); }
}
/// <summary>
/// Gets the number of elements contained by this node and below.
/// </summary>
int IBinaryTree.Count
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the keys.
/// </summary>
internal IEnumerable<TKey> Keys
{
get { return Linq.Enumerable.Select(this, p => p.Key); }
}
/// <summary>
/// Gets the values.
/// </summary>
internal IEnumerable<TValue> Values
{
get { return Linq.Enumerable.Select(this, p => p.Value); }
}
#region IEnumerable<TKey> Members
/// <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>
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>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <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>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <param name="builder">The builder, if applicable.</param>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
internal Enumerator GetEnumerator(Builder builder)
{
return new Enumerator(this, builder);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
internal void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex, int dictionarySize)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex));
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
internal void CopyTo(Array array, int arrayIndex, int dictionarySize)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex));
foreach (var item in this)
{
array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++);
}
}
/// <summary>
/// Creates a node tree from an existing (mutable) collection.
/// </summary>
/// <param name="dictionary">The collection.</param>
/// <returns>The root of the node tree.</returns>
[Pure]
internal static Node NodeTreeFromSortedDictionary(SortedDictionary<TKey, TValue> dictionary)
{
Requires.NotNull(dictionary, nameof(dictionary));
Contract.Ensures(Contract.Result<Node>() != null);
var list = dictionary.AsOrderedCollection();
return NodeTreeFromList(list, 0, list.Count);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal Node Add(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
bool dummy;
return this.SetOrAdd(key, value, keyComparer, valueComparer, false, out dummy, out mutated);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal Node SetItem(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
return this.SetOrAdd(key, value, keyComparer, valueComparer, true, out replacedExistingValue, out mutated);
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
internal Node Remove(TKey key, IComparer<TKey> keyComparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
return this.RemoveRecursive(key, keyComparer, out mutated);
}
/// <summary>
/// Tries to get the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="value">The value.</param>
/// <returns>True if the key was found.</returns>
[Pure]
internal bool TryGetValue(TKey key, IComparer<TKey> keyComparer, out TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(key, keyComparer);
if (match.IsEmpty)
{
value = default(TValue);
return false;
}
else
{
value = match._value;
return true;
}
}
/// <summary>
/// Searches the dictionary for a given key and returns the equal key it finds, if any.
/// </summary>
/// <param name="equalKey">The key to search for.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="actualKey">The key from the dictionary that the search found, or <paramref name="equalKey"/> if the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// the canonical value, or a value that has more complete data than the value you currently have,
/// although their comparer functions indicate they are equal.
/// </remarks>
[Pure]
internal bool TryGetKey(TKey equalKey, IComparer<TKey> keyComparer, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, nameof(equalKey));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(equalKey, keyComparer);
if (match.IsEmpty)
{
actualKey = equalKey;
return false;
}
else
{
actualKey = match._key;
return true;
}
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
[Pure]
internal bool ContainsKey(TKey key, IComparer<TKey> keyComparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
return !this.Search(key, keyComparer).IsEmpty;
}
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <param name="valueComparer">The value comparer to use.</param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
internal bool ContainsValue(TValue value, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(valueComparer, nameof(valueComparer));
foreach (KeyValuePair<TKey, TValue> item in this)
{
if (valueComparer.Equals(value, item.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether [contains] [the specified pair].
/// </summary>
/// <param name="pair">The pair.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified pair]; otherwise, <c>false</c>.
/// </returns>
[Pure]
internal bool Contains(KeyValuePair<TKey, TValue> pair, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNullAllowStructs(pair.Key, nameof(pair.Key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
var matchingNode = this.Search(pair.Key, keyComparer);
if (matchingNode.IsEmpty)
{
return false;
}
return valueComparer.Equals(matchingNode._value, pair.Value);
}
/// <summary>
/// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes.
/// </summary>
internal void Freeze()
{
// If this node is frozen, all its descendants must already be frozen.
if (!_frozen)
{
_left.Freeze();
_right.Freeze();
_frozen = true;
}
}
#region Tree balancing methods
/// <summary>
/// AVL rotate left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
return tree;
}
var right = tree._right;
return right.Mutate(left: tree.Mutate(right: right._left));
}
/// <summary>
/// AVL rotate right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
return tree;
}
var left = tree._left;
return left.Mutate(right: tree.Mutate(left: left._right));
}
/// <summary>
/// AVL rotate double-left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._right.IsEmpty)
{
return tree;
}
Node rotatedRightChild = tree.Mutate(right: RotateRight(tree._right));
return RotateLeft(rotatedRightChild);
}
/// <summary>
/// AVL rotate double-right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (tree._left.IsEmpty)
{
return tree;
}
Node rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left));
return RotateRight(rotatedLeftChild);
}
/// <summary>
/// Returns a value indicating whether the tree is in balance.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns>
[Pure]
private static int Balance(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return tree._right._height - tree._left._height;
}
/// <summary>
/// Determines whether the specified tree is right heavy.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>
/// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>.
/// </returns>
[Pure]
private static bool IsRightHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) >= 2;
}
/// <summary>
/// Determines whether the specified tree is left heavy.
/// </summary>
[Pure]
private static bool IsLeftHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) <= -2;
}
/// <summary>
/// Balances the specified tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>A balanced tree.</returns>
[Pure]
private static Node MakeBalanced(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
Contract.Ensures(Contract.Result<Node>() != null);
if (IsRightHeavy(tree))
{
return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree);
}
if (IsLeftHeavy(tree))
{
return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree);
}
return tree;
}
#endregion
/// <summary>
/// Creates a node tree that contains the contents of a list.
/// </summary>
/// <param name="items">An indexable list with the contents that the new node tree should contain.</param>
/// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param>
/// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param>
/// <returns>The root of the created node tree.</returns>
[Pure]
private static Node NodeTreeFromList(IOrderedCollection<KeyValuePair<TKey, TValue>> items, int start, int length)
{
Requires.NotNull(items, nameof(items));
Requires.Range(start >= 0, nameof(start));
Requires.Range(length >= 0, nameof(length));
Contract.Ensures(Contract.Result<Node>() != null);
if (length == 0)
{
return EmptyNode;
}
int rightCount = (length - 1) / 2;
int leftCount = (length - 1) - rightCount;
Node left = NodeTreeFromList(items, start, leftCount);
Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount);
var item = items[start + leftCount];
return new Node(item.Key, item.Value, left, right, true);
}
/// <summary>
/// Adds the specified key. Callers are expected to have validated arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private Node SetOrAdd(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated)
{
// Arg validation skipped in this private method because it's recursive and the tax
// of revalidating arguments on each recursive call is significant.
// All our callers are therefore required to have done input validation.
replacedExistingValue = false;
if (this.IsEmpty)
{
mutated = true;
return new Node(key, value, this, this);
}
else
{
Node result = this;
int compareResult = keyComparer.Compare(key, _key);
if (compareResult > 0)
{
var newRight = _right.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
else if (compareResult < 0)
{
var newLeft = _left.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
if (valueComparer.Equals(_value, value))
{
mutated = false;
return this;
}
else if (overwriteExistingValue)
{
mutated = true;
replacedExistingValue = true;
result = new Node(key, value, _left, _right);
}
else
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
}
}
return mutated ? MakeBalanced(result) : result;
}
}
/// <summary>
/// Removes the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private Node RemoveRecursive(TKey key, IComparer<TKey> keyComparer, out bool mutated)
{
// Skip parameter validation because it's too expensive and pointless in recursive methods.
if (this.IsEmpty)
{
mutated = false;
return this;
}
else
{
Node result = this;
int compare = keyComparer.Compare(key, _key);
if (compare == 0)
{
// We have a match.
mutated = true;
// If this is a leaf, just remove it
// by returning Empty. If we have only one child,
// replace the node with the child.
if (_right.IsEmpty && _left.IsEmpty)
{
result = EmptyNode;
}
else if (_right.IsEmpty && !_left.IsEmpty)
{
result = _left;
}
else if (!_right.IsEmpty && _left.IsEmpty)
{
result = _right;
}
else
{
// We have two children. Remove the next-highest node and replace
// this node with it.
var successor = _right;
while (!successor._left.IsEmpty)
{
successor = successor._left;
}
bool dummyMutated;
var newRight = _right.Remove(successor._key, keyComparer, out dummyMutated);
result = successor.Mutate(left: _left, right: newRight);
}
}
else if (compare < 0)
{
var newLeft = _left.Remove(key, keyComparer, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
var newRight = _right.Remove(key, keyComparer, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
return result.IsEmpty ? result : MakeBalanced(result);
}
}
/// <summary>
/// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node
/// with the described changes.
/// </summary>
/// <param name="left">The left branch of the mutated node.</param>
/// <param name="right">The right branch of the mutated node.</param>
/// <returns>The mutated (or created) node.</returns>
private Node Mutate(Node left = null, Node right = null)
{
if (_frozen)
{
return new Node(_key, _value, left ?? _left, right ?? _right);
}
else
{
if (left != null)
{
_left = left;
}
if (right != null)
{
_right = right;
}
_height = checked((byte)(1 + Math.Max(_left._height, _right._height)));
return this;
}
}
/// <summary>
/// Searches the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
[Pure]
private Node Search(TKey key, IComparer<TKey> keyComparer)
{
// Arg validation is too expensive for recursive methods.
// Callers are expected to have validated parameters.
if (this.IsEmpty)
{
return this;
}
else
{
int compare = keyComparer.Compare(key, _key);
if (compare == 0)
{
return this;
}
else if (compare > 0)
{
return _right.Search(key, keyComparer);
}
else
{
return _left.Search(key, keyComparer);
}
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Policy;
using System.Reflection;
using System.Globalization;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.EventQueue;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Interfaces;
using ScriptCompileQueue = OpenSim.Framework.LocklessQueue<object[]>;
namespace OpenSim.Region.ScriptEngine.XEngine
{
public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SmartThreadPool m_ThreadPool;
private int m_MaxScriptQueue;
private Scene m_Scene;
private IConfig m_ScriptConfig = null;
private IConfigSource m_ConfigSource = null;
private ICompiler m_Compiler;
private int m_MinThreads;
private int m_MaxThreads ;
private int m_IdleTimeout;
private int m_StackSize;
private int m_SleepTime;
private int m_SaveTime;
private ThreadPriority m_Prio;
private bool m_Enabled = false;
private bool m_InitialStartup = true;
private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
private string m_ScriptErrorMessage;
private Dictionary<string, string> m_uniqueScripts = new Dictionary<string, string>();
private bool m_AppDomainLoading;
private Dictionary<UUID,ArrayList> m_ScriptErrors =
new Dictionary<UUID,ArrayList>();
// disable warning: need to keep a reference to XEngine.EventManager
// alive to avoid it being garbage collected
#pragma warning disable 414
private EventManager m_EventManager;
#pragma warning restore 414
private IXmlRpcRouter m_XmlRpcRouter;
private int m_EventLimit;
private bool m_KillTimedOutScripts;
private static List<XEngine> m_ScriptEngines =
new List<XEngine>();
// Maps the local id to the script inventory items in it
private Dictionary<uint, List<UUID> > m_PrimObjects =
new Dictionary<uint, List<UUID> >();
// Maps the UUID above to the script instance
private Dictionary<UUID, IScriptInstance> m_Scripts =
new Dictionary<UUID, IScriptInstance>();
// Maps the asset ID to the assembly
private Dictionary<UUID, string> m_Assemblies =
new Dictionary<UUID, string>();
private Dictionary<string, int> m_AddingAssemblies =
new Dictionary<string, int>();
// This will list AppDomains by script asset
private Dictionary<UUID, AppDomain> m_AppDomains =
new Dictionary<UUID, AppDomain>();
// List the scripts running in each appdomain
private Dictionary<UUID, List<UUID> > m_DomainScripts =
new Dictionary<UUID, List<UUID> >();
private ScriptCompileQueue m_CompileQueue = new ScriptCompileQueue();
IWorkItemResult m_CurrentCompile = null;
public string ScriptEngineName
{
get { return "XEngine"; }
}
public Scene World
{
get { return m_Scene; }
}
public static List<XEngine> ScriptEngines
{
get { return m_ScriptEngines; }
}
public IScriptModule ScriptModule
{
get { return this; }
}
// private struct RezScriptParms
// {
// uint LocalID;
// UUID ItemID;
// string Script;
// }
public IConfig Config
{
get { return m_ScriptConfig; }
}
public IConfigSource ConfigSource
{
get { return m_ConfigSource; }
}
public event ScriptRemoved OnScriptRemoved;
public event ObjectRemoved OnObjectRemoved;
//
// IRegionModule functions
//
public void Initialise(IConfigSource configSource)
{
if (configSource.Configs["XEngine"] == null)
return;
m_ScriptConfig = configSource.Configs["XEngine"];
m_ConfigSource = configSource;
}
public void AddRegion(Scene scene)
{
if (m_ScriptConfig == null)
return;
m_ScriptFailCount = 0;
m_ScriptErrorMessage = String.Empty;
if (m_ScriptConfig == null)
{
// m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
return;
}
m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
if (!m_Enabled)
return;
AppDomain.CurrentDomain.AssemblyResolve +=
OnAssemblyResolve;
m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
scene.RegionInfo.RegionName);
m_Scene = scene;
m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
m_AppDomainLoading = m_ScriptConfig.GetBoolean("AppDomainLoading", true);
m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
m_Prio = ThreadPriority.BelowNormal;
switch (priority)
{
case "Lowest":
m_Prio = ThreadPriority.Lowest;
break;
case "BelowNormal":
m_Prio = ThreadPriority.BelowNormal;
break;
case "Normal":
m_Prio = ThreadPriority.Normal;
break;
case "AboveNormal":
m_Prio = ThreadPriority.AboveNormal;
break;
case "Highest":
m_Prio = ThreadPriority.Highest;
break;
default:
m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
break;
}
lock (m_ScriptEngines)
{
m_ScriptEngines.Add(this);
}
// Needs to be here so we can queue the scripts that need starting
//
m_Scene.EventManager.OnRezScript += OnRezScript;
// Complete basic setup of the thread pool
//
SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
m_MaxScriptQueue, m_StackSize);
m_Scene.StackModuleInterface<IScriptModule>(this);
m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
if (m_XmlRpcRouter != null)
{
OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
}
}
public void RemoveRegion(Scene scene)
{
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
{
// Force a final state save
//
if (m_Assemblies.ContainsKey(instance.AssetID))
{
string assembly = m_Assemblies[instance.AssetID];
instance.SaveState(assembly);
}
// Clear the event queue and abort the instance thread
//
instance.ClearQueue();
instance.Stop(0);
// Release events, timer, etc
//
instance.DestroyScriptInstance();
// Unload scripts and app domains
// Must be done explicitly because they have infinite
// lifetime
//
m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
if (m_DomainScripts[instance.AppDomain].Count == 0)
{
m_DomainScripts.Remove(instance.AppDomain);
UnloadAppDomain(instance.AppDomain);
}
}
m_Scripts.Clear();
m_PrimObjects.Clear();
m_Assemblies.Clear();
m_DomainScripts.Clear();
}
lock (m_ScriptEngines)
{
m_ScriptEngines.Remove(this);
}
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_EventManager = new EventManager(this);
m_Compiler = new Compiler(this);
m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
m_Scene.EventManager.OnScriptReset += OnScriptReset;
m_Scene.EventManager.OnStartScript += OnStartScript;
m_Scene.EventManager.OnStopScript += OnStopScript;
m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
m_Scene.EventManager.OnShutdown += OnShutdown;
if (m_SleepTime > 0)
{
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
new Object[]{ m_SleepTime });
}
if (m_SaveTime > 0)
{
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
new Object[] { m_SaveTime });
}
m_ThreadPool.Start();
}
public void Close()
{
lock (m_ScriptEngines)
{
if (m_ScriptEngines.Contains(this))
m_ScriptEngines.Remove(this);
}
}
public object DoBackup(object o)
{
Object[] p = (Object[])o;
int saveTime = (int)p[0];
if (saveTime > 0)
System.Threading.Thread.Sleep(saveTime);
// m_log.Debug("[XEngine] Backing up script states");
List<IScriptInstance> instances = new List<IScriptInstance>();
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
instances.Add(instance);
}
foreach (IScriptInstance i in instances)
{
string assembly = String.Empty;
lock (m_Scripts)
{
if (!m_Assemblies.ContainsKey(i.AssetID))
continue;
assembly = m_Assemblies[i.AssetID];
}
i.SaveState(assembly);
}
instances.Clear();
if (saveTime > 0)
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
new Object[] { saveTime });
return 0;
}
public object DoMaintenance(object p)
{
object[] parms = (object[])p;
int sleepTime = (int)parms[0];
foreach (IScriptInstance inst in m_Scripts.Values)
{
if (inst.EventTime() > m_EventLimit)
{
inst.Stop(100);
if (!m_KillTimedOutScripts)
inst.Start();
}
}
System.Threading.Thread.Sleep(sleepTime);
m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
new Object[]{ sleepTime });
return 0;
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "XEngine"; }
}
public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
{
if (script.StartsWith("//MRM:"))
return;
List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
List<string> names = new List<string>();
foreach (IScriptModule m in engines)
names.Add(m.ScriptEngineName);
int lineEnd = script.IndexOf('\n');
if (lineEnd > 1)
{
string firstline = script.Substring(0, lineEnd).Trim();
int colon = firstline.IndexOf(':');
if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
{
string engineName = firstline.Substring(2, colon-2);
if (names.Contains(engineName))
{
engine = engineName;
script = "//" + script.Substring(script.IndexOf(':')+1);
}
else
{
if (engine == ScriptEngineName)
{
SceneObjectPart part =
m_Scene.GetSceneObjectPart(
localID);
TaskInventoryItem item =
part.Inventory.GetInventoryItem(itemID);
ScenePresence presence =
m_Scene.GetScenePresence(
item.OwnerID);
if (presence != null)
{
presence.ControllingClient.SendAgentAlertMessage(
"Selected engine unavailable. "+
"Running script on "+
ScriptEngineName,
false);
}
}
}
}
}
if (engine != ScriptEngineName)
return;
// If we've seen this exact script text before, use that reference instead
if (m_uniqueScripts.ContainsKey(script))
script = m_uniqueScripts[script];
else
m_uniqueScripts[script] = script;
Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
if (stateSource == (int)StateSource.ScriptedRez)
{
DoOnRezScript(parms);
}
else
{
m_CompileQueue.Enqueue(parms);
if (m_CurrentCompile == null)
{
// NOTE: Although we use a lockless queue, the lock here
// is required. It ensures that there are never two
// compile threads running, which, due to a race
// conndition, might otherwise happen
//
lock (m_CompileQueue)
{
if (m_CurrentCompile == null)
m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
}
}
}
}
public Object DoOnRezScriptQueue(Object dummy)
{
if (m_InitialStartup)
{
m_InitialStartup = false;
System.Threading.Thread.Sleep(15000);
if (m_CompileQueue.Count == 0)
{
// No scripts on region, so won't get triggered later
// by the queue becoming empty so we trigger it here
m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
}
}
object[] o;
while (m_CompileQueue.Dequeue(out o))
DoOnRezScript(o);
// NOTE: Despite having a lockless queue, this lock is required
// to make sure there is never no compile thread while there
// are still scripts to compile. This could otherwise happen
// due to a race condition
//
lock (m_CompileQueue)
{
m_CurrentCompile = null;
}
m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
m_ScriptErrorMessage);
m_ScriptFailCount = 0;
return null;
}
private bool DoOnRezScript(object[] parms)
{
Object[] p = parms;
uint localID = (uint)p[0];
UUID itemID = (UUID)p[1];
string script =(string)p[2];
int startParam = (int)p[3];
bool postOnRez = (bool)p[4];
StateSource stateSource = (StateSource)p[5];
// Get the asset ID of the script, so we can check if we
// already have it.
// We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
// m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
// and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
if (part == null)
{
m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started.");
m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
m_ScriptFailCount++;
return false;
}
TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
if (item == null)
{
m_ScriptErrorMessage += "Can't find script inventory item.\n";
m_ScriptFailCount++;
return false;
}
UUID assetID = item.AssetID;
//m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})",
// item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name);
ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
string assembly = "";
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
lock (m_ScriptErrors)
{
try
{
lock (m_AddingAssemblies)
{
m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID, out assembly, out linemap);
if (!m_AddingAssemblies.ContainsKey(assembly)) {
m_AddingAssemblies[assembly] = 1;
} else {
m_AddingAssemblies[assembly]++;
}
}
string[] warnings = m_Compiler.GetWarnings();
if (warnings != null && warnings.Length != 0)
{
foreach (string warning in warnings)
{
if (!m_ScriptErrors.ContainsKey(itemID))
m_ScriptErrors[itemID] = new ArrayList();
m_ScriptErrors[itemID].Add(warning);
// try
// {
// // DISPLAY WARNING INWORLD
// string text = "Warning:\n" + warning;
// if (text.Length > 1000)
// text = text.Substring(0, 1000);
// if (!ShowScriptSaveResponse(item.OwnerID,
// assetID, text, true))
// {
// if (presence != null && (!postOnRez))
// presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
//
// World.SimChat(Utils.StringToBytes(text),
// ChatTypeEnum.DebugChannel, 2147483647,
// part.AbsolutePosition,
// part.Name, part.UUID, false);
// }
// }
// catch (Exception e2) // LEGIT: User Scripting
// {
// m_log.Error("[XEngine]: " +
// "Error displaying warning in-world: " +
// e2.ToString());
// m_log.Error("[XEngine]: " +
// "Warning:\r\n" +
// warning);
// }
}
}
}
catch (Exception e)
{
// try
// {
if (!m_ScriptErrors.ContainsKey(itemID))
m_ScriptErrors[itemID] = new ArrayList();
// DISPLAY ERROR INWORLD
// m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
//
m_ScriptFailCount++;
m_ScriptErrors[itemID].Add(e.Message.ToString());
// string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
// if (text.Length > 1000)
// text = text.Substring(0, 1000);
// if (!ShowScriptSaveResponse(item.OwnerID,
// assetID, text, false))
// {
// if (presence != null && (!postOnRez))
// presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
// World.SimChat(Utils.StringToBytes(text),
// ChatTypeEnum.DebugChannel, 2147483647,
// part.AbsolutePosition,
// part.Name, part.UUID, false);
// }
// }
// catch (Exception e2) // LEGIT: User Scripting
// {
// m_log.Error("[XEngine]: "+
// "Error displaying error in-world: " +
// e2.ToString());
// m_log.Error("[XEngine]: " +
// "Errormessage: Error compiling script:\r\n" +
// e.Message.ToString());
// }
return false;
}
}
lock (m_Scripts)
{
ScriptInstance instance = null;
// Create the object record
if ((!m_Scripts.ContainsKey(itemID)) ||
(m_Scripts[itemID].AssetID != assetID))
{
UUID appDomain = assetID;
if (part.ParentGroup.IsAttachment)
appDomain = part.ParentGroup.RootPart.UUID;
if (!m_AppDomains.ContainsKey(appDomain))
{
try
{
AppDomainSetup appSetup = new AppDomainSetup();
// appSetup.ApplicationBase = Path.Combine(
// "ScriptEngines",
// m_Scene.RegionInfo.RegionID.ToString());
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
AppDomain sandbox;
if (m_AppDomainLoading)
sandbox = AppDomain.CreateDomain(
m_Scene.RegionInfo.RegionID.ToString(),
evidence, appSetup);
else
sandbox = AppDomain.CurrentDomain;
//PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
//AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
//PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
//PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
//CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
//sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
//sandbox.SetAppDomainPolicy(sandboxPolicy);
m_AppDomains[appDomain] = sandbox;
m_AppDomains[appDomain].AssemblyResolve +=
new ResolveEventHandler(
AssemblyResolver.OnAssemblyResolve);
m_DomainScripts[appDomain] = new List<UUID>();
}
catch (Exception e)
{
m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
m_ScriptErrorMessage += "Exception creating app domain:\n";
m_ScriptFailCount++;
lock (m_AddingAssemblies)
{
m_AddingAssemblies[assembly]--;
}
return false;
}
}
m_DomainScripts[appDomain].Add(itemID);
instance = new ScriptInstance(this, part,
itemID, assetID, assembly,
m_AppDomains[appDomain],
part.ParentGroup.RootPart.Name,
item.Name, startParam, postOnRez,
stateSource, m_MaxScriptQueue);
m_log.DebugFormat("[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}",
part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, part.ParentGroup.RootPart.AbsolutePosition.ToString());
if (presence != null)
{
ShowScriptSaveResponse(item.OwnerID,
assetID, "Compile successful", true);
}
instance.AppDomain = appDomain;
instance.LineMap = linemap;
m_Scripts[itemID] = instance;
}
lock (m_PrimObjects)
{
if (!m_PrimObjects.ContainsKey(localID))
m_PrimObjects[localID] = new List<UUID>();
if (!m_PrimObjects[localID].Contains(itemID))
m_PrimObjects[localID].Add(itemID);
}
if (!m_Assemblies.ContainsKey(assetID))
m_Assemblies[assetID] = assembly;
lock (m_AddingAssemblies)
{
m_AddingAssemblies[assembly]--;
}
if (instance!=null)
instance.Init();
}
return true;
}
public void OnRemoveScript(uint localID, UUID itemID)
{
lock (m_Scripts)
{
// Do we even have it?
if (!m_Scripts.ContainsKey(itemID))
return;
IScriptInstance instance=m_Scripts[itemID];
m_Scripts.Remove(itemID);
instance.ClearQueue();
instance.Stop(0);
// bool objectRemoved = false;
lock (m_PrimObjects)
{
// Remove the script from it's prim
if (m_PrimObjects.ContainsKey(localID))
{
// Remove inventory item record
if (m_PrimObjects[localID].Contains(itemID))
m_PrimObjects[localID].Remove(itemID);
// If there are no more scripts, remove prim
if (m_PrimObjects[localID].Count == 0)
{
m_PrimObjects.Remove(localID);
// objectRemoved = true;
}
}
}
instance.RemoveState();
instance.DestroyScriptInstance();
m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
if (m_DomainScripts[instance.AppDomain].Count == 0)
{
m_DomainScripts.Remove(instance.AppDomain);
UnloadAppDomain(instance.AppDomain);
}
instance = null;
ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
if (handlerObjectRemoved != null)
{
SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
handlerObjectRemoved(part.UUID);
}
CleanAssemblies();
}
ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
if (handlerScriptRemoved != null)
handlerScriptRemoved(itemID);
}
public void OnScriptReset(uint localID, UUID itemID)
{
ResetScript(itemID);
}
public void OnStartScript(uint localID, UUID itemID)
{
StartScript(itemID);
}
public void OnStopScript(uint localID, UUID itemID)
{
StopScript(itemID);
}
private void CleanAssemblies()
{
List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
foreach (IScriptInstance i in m_Scripts.Values)
{
if (assetIDList.Contains(i.AssetID))
assetIDList.Remove(i.AssetID);
}
lock (m_AddingAssemblies)
{
foreach (UUID assetID in assetIDList)
{
// Do not remove assembly files if another instance of the script
// is currently initialising
if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
|| m_AddingAssemblies[m_Assemblies[assetID]] == 0)
{
// m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
try
{
if (File.Exists(m_Assemblies[assetID]))
File.Delete(m_Assemblies[assetID]);
if (File.Exists(m_Assemblies[assetID]+".text"))
File.Delete(m_Assemblies[assetID]+".text");
if (File.Exists(m_Assemblies[assetID]+".mdb"))
File.Delete(m_Assemblies[assetID]+".mdb");
if (File.Exists(m_Assemblies[assetID]+".map"))
File.Delete(m_Assemblies[assetID]+".map");
}
catch (Exception)
{
}
m_Assemblies.Remove(assetID);
}
}
}
}
private void UnloadAppDomain(UUID id)
{
if (m_AppDomains.ContainsKey(id))
{
AppDomain domain = m_AppDomains[id];
m_AppDomains.Remove(id);
if (domain != AppDomain.CurrentDomain)
AppDomain.Unload(domain);
domain = null;
// m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
}
}
//
// Start processing
//
private void SetupEngine(int minThreads, int maxThreads,
int idleTimeout, ThreadPriority threadPriority,
int maxScriptQueue, int stackSize)
{
m_MaxScriptQueue = maxScriptQueue;
STPStartInfo startInfo = new STPStartInfo();
startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
startInfo.MaxWorkerThreads = maxThreads;
startInfo.MinWorkerThreads = minThreads;
startInfo.ThreadPriority = threadPriority;
startInfo.StackSize = stackSize;
startInfo.StartSuspended = true;
m_ThreadPool = new SmartThreadPool(startInfo);
}
//
// Used by script instances to queue event handler jobs
//
public IScriptWorkItem QueueEventHandler(object parms)
{
return new XWorkItem(m_ThreadPool.QueueWorkItem(
new WorkItemCallback(this.ProcessEventHandler),
parms));
}
/// <summary>
/// Process a previously posted script event.
/// </summary>
/// <param name="parms"></param>
/// <returns></returns>
private object ProcessEventHandler(object parms)
{
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
IScriptInstance instance = (ScriptInstance) parms;
//m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);
return instance.EventProcessor();
}
/// <summary>
/// Post event to an entire prim
/// </summary>
/// <param name="localID"></param>
/// <param name="p"></param>
/// <returns></returns>
public bool PostObjectEvent(uint localID, EventParams p)
{
bool result = false;
lock (m_PrimObjects)
{
if (!m_PrimObjects.ContainsKey(localID))
return false;
foreach (UUID itemID in m_PrimObjects[localID])
{
if (m_Scripts.ContainsKey(itemID))
{
IScriptInstance instance = m_Scripts[itemID];
if (instance != null)
{
instance.PostEvent(p);
result = true;
}
}
}
}
return result;
}
/// <summary>
/// Post an event to a single script
/// </summary>
/// <param name="itemID"></param>
/// <param name="p"></param>
/// <returns></returns>
public bool PostScriptEvent(UUID itemID, EventParams p)
{
if (m_Scripts.ContainsKey(itemID))
{
IScriptInstance instance = m_Scripts[itemID];
if (instance != null)
instance.PostEvent(p);
return true;
}
return false;
}
public bool PostScriptEvent(UUID itemID, string name, Object[] p)
{
Object[] lsl_p = new Object[p.Length];
for (int i = 0; i < p.Length ; i++)
{
if (p[i] is int)
lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
else if (p[i] is string)
lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
else if (p[i] is Vector3)
lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
else if (p[i] is Quaternion)
lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
else if (p[i] is float)
lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
else
lsl_p[i] = p[i];
}
return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
}
public bool PostObjectEvent(UUID itemID, string name, Object[] p)
{
SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
if (part == null)
return false;
Object[] lsl_p = new Object[p.Length];
for (int i = 0; i < p.Length ; i++)
{
if (p[i] is int)
lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
else if (p[i] is string)
lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
else if (p[i] is Vector3)
lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
else if (p[i] is Quaternion)
lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
else if (p[i] is float)
lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
else
lsl_p[i] = p[i];
}
return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
}
public Assembly OnAssemblyResolve(object sender,
ResolveEventArgs args)
{
if (!(sender is System.AppDomain))
return null;
string[] pathList = new string[] {"bin", "ScriptEngines",
Path.Combine("ScriptEngines",
m_Scene.RegionInfo.RegionID.ToString())};
string assemblyName = args.Name;
if (assemblyName.IndexOf(",") != -1)
assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
foreach (string s in pathList)
{
string path = Path.Combine(Directory.GetCurrentDirectory(),
Path.Combine(s, assemblyName))+".dll";
if (File.Exists(path))
return Assembly.LoadFrom(path);
}
return null;
}
private IScriptInstance GetInstance(UUID itemID)
{
IScriptInstance instance;
lock (m_Scripts)
{
if (!m_Scripts.ContainsKey(itemID))
return null;
instance = m_Scripts[itemID];
}
return instance;
}
public void SetScriptState(UUID itemID, bool running)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
{
if (running)
instance.Start();
else
instance.Stop(100);
}
}
public bool GetScriptState(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.Running;
return false;
}
public void ApiResetScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.ApiResetScript();
}
public void ResetScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.ResetScript();
}
public void StartScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.Start();
}
public void StopScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.Stop(0);
}
public DetectParams GetDetectParams(UUID itemID, int idx)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.GetDetectParams(idx);
return null;
}
public void SetMinEventDelay(UUID itemID, double delay)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
instance.MinEventDelay = delay;
}
public UUID GetDetectID(UUID itemID, int idx)
{
IScriptInstance instance = GetInstance(itemID);
if (instance != null)
return instance.GetDetectID(idx);
return UUID.Zero;
}
public void SetState(UUID itemID, string newState)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
instance.SetState(newState);
}
public int GetStartParameter(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return 0;
return instance.StartParam;
}
public void OnShutdown()
{
List<IScriptInstance> instances = new List<IScriptInstance>();
lock (m_Scripts)
{
foreach (IScriptInstance instance in m_Scripts.Values)
instances.Add(instance);
}
foreach (IScriptInstance i in instances)
{
// Stop the script, even forcibly if needed. Then flag
// it as shutting down and restore the previous run state
// for serialization, so the scripts don't come back
// dead after region restart
//
bool prevRunning = i.Running;
i.Stop(50);
i.ShuttingDown = true;
i.Running = prevRunning;
}
DoBackup(new Object[] {0});
}
public IScriptApi GetApi(UUID itemID, string name)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return null;
return instance.GetApi(name);
}
public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
if (eq == null)
{
controllingClient.SendScriptRunningReply(objectID, itemID,
GetScriptState(itemID));
}
else
{
eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
controllingClient.AgentId);
}
}
public string GetXMLState(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return "";
string xml = instance.GetXMLState();
XmlDocument sdoc = new XmlDocument();
sdoc.LoadXml(xml);
XmlNodeList rootL = sdoc.GetElementsByTagName("ScriptState");
XmlNode rootNode = rootL[0];
// Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
XmlDocument doc = new XmlDocument();
XmlElement stateData = doc.CreateElement("", "State", "");
XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
stateID.Value = itemID.ToString();
stateData.Attributes.Append(stateID);
XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
assetID.Value = instance.AssetID.ToString();
stateData.Attributes.Append(assetID);
XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
engineName.Value = ScriptEngineName;
stateData.Attributes.Append(engineName);
doc.AppendChild(stateData);
// Add <ScriptState>...</ScriptState>
XmlNode xmlstate = doc.ImportNode(rootNode, true);
stateData.AppendChild(xmlstate);
string assemName = instance.GetAssemblyName();
string fn = Path.GetFileName(assemName);
string assem = String.Empty;
if (File.Exists(assemName + ".text"))
{
FileInfo tfi = new FileInfo(assemName + ".text");
if (tfi != null)
{
Byte[] tdata = new Byte[tfi.Length];
try
{
FileStream tfs = File.Open(assemName + ".text",
FileMode.Open, FileAccess.Read);
tfs.Read(tdata, 0, tdata.Length);
tfs.Close();
assem = new System.Text.ASCIIEncoding().GetString(tdata);
}
catch (Exception e)
{
m_log.DebugFormat("[XEngine]: Unable to open script textfile {0}, reason: {1}", assemName+".text", e.Message);
}
}
}
else
{
FileInfo fi = new FileInfo(assemName);
if (fi != null)
{
Byte[] data = new Byte[fi.Length];
try
{
FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read);
fs.Read(data, 0, data.Length);
fs.Close();
assem = System.Convert.ToBase64String(data);
}
catch (Exception e)
{
m_log.DebugFormat("[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
}
}
}
string map = String.Empty;
if (File.Exists(fn + ".map"))
{
FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read);
StreamReader msr = new StreamReader(mfs);
map = msr.ReadToEnd();
msr.Close();
mfs.Close();
}
XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");
assemblyName.Value = fn;
assemblyData.Attributes.Append(assemblyName);
assemblyData.InnerText = assem;
stateData.AppendChild(assemblyData);
XmlElement mapData = doc.CreateElement("", "LineMap", "");
XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");
mapName.Value = fn + ".map";
mapData.Attributes.Append(mapName);
mapData.InnerText = map;
stateData.AppendChild(mapData);
return doc.InnerXml;
}
private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
{
return false;
}
public bool SetXMLState(UUID itemID, string xml)
{
if (xml == String.Empty)
return false;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xml);
}
catch (Exception)
{
m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
return false;
}
XmlNodeList rootL = doc.GetElementsByTagName("State");
if (rootL.Count < 1)
return false;
XmlElement rootE = (XmlElement)rootL[0];
if (rootE.GetAttribute("Engine") != ScriptEngineName)
return false;
// On rez from inventory, that ID will have changed. It was only
// advisory anyway. So we don't check it anymore.
//
// if (rootE.GetAttribute("UUID") != itemID.ToString())
// return;
XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");
if (stateL.Count != 1)
return false;
XmlElement stateE = (XmlElement)stateL[0];
if (World.m_trustBinaries)
{
XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");
if (assemL.Count != 1)
return false;
XmlElement assemE = (XmlElement)assemL[0];
string fn = assemE.GetAttribute("Filename");
string base64 = assemE.InnerText;
string path = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
path = Path.Combine(path, fn);
if (!File.Exists(path))
{
Byte[] filedata = Convert.FromBase64String(base64);
FileStream fs = File.Create(path);
fs.Write(filedata, 0, filedata.Length);
fs.Close();
fs = File.Create(path + ".text");
StreamWriter sw = new StreamWriter(fs);
sw.Write(base64);
sw.Close();
fs.Close();
}
}
string statepath = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
statepath = Path.Combine(statepath, itemID.ToString() + ".state");
FileStream sfs = File.Create(statepath);
StreamWriter ssw = new StreamWriter(sfs);
ssw.Write(stateE.OuterXml);
ssw.Close();
sfs.Close();
XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
if (mapL.Count > 0)
{
XmlElement mapE = (XmlElement)mapL[0];
string mappath = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));
FileStream mfs = File.Create(mappath);
StreamWriter msw = new StreamWriter(mfs);
msw.Write(mapE.InnerText);
msw.Close();
mfs.Close();
}
return true;
}
public ArrayList GetScriptErrors(UUID itemID)
{
System.Threading.Thread.Sleep(1000);
lock (m_ScriptErrors)
{
if (m_ScriptErrors.ContainsKey(itemID))
{
ArrayList ret = m_ScriptErrors[itemID];
m_ScriptErrors.Remove(itemID);
return ret;
}
return new ArrayList();
}
}
public void SuspendScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
instance.Suspend();
}
public void ResumeScript(UUID itemID)
{
IScriptInstance instance = GetInstance(itemID);
if (instance == null)
return;
instance.Resume();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedParameter.Global
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable UnusedAutoPropertyAccessor.Global
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Events;
using Apache.Ignite.Core.Resource;
using Apache.Ignite.Core.Tests.Compute;
using NUnit.Framework;
/// <summary>
/// <see cref="IEvents"/> tests.
/// </summary>
public class EventsTest
{
/** */
public const string CacheName = "eventsTest";
/** */
private IIgnite _grid1;
/** */
private IIgnite _grid2;
/** */
private IIgnite _grid3;
/** */
private IIgnite[] _grids;
/// <summary>
/// Executes before each test.
/// </summary>
[SetUp]
public void SetUp()
{
StartGrids();
EventsTestHelper.ListenResult = true;
}
/// <summary>
/// Executes after each test.
/// </summary>
[TearDown]
public void TearDown()
{
try
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
}
catch (Exception)
{
// Restart grids to cleanup
StopGrids();
throw;
}
finally
{
EventsTestHelper.AssertFailures();
if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes"))
StopGrids(); // clean events for other tests
}
}
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureTearDown]
public void FixtureTearDown()
{
StopGrids();
}
/// <summary>
/// Tests enable/disable of event types.
/// </summary>
[Test]
public void TestEnableDisable()
{
var events = _grid1.GetEvents();
Assert.AreEqual(0, events.GetEnabledEvents().Count);
Assert.IsFalse(EventType.CacheAll.Any(events.IsEnabled));
events.EnableLocal(EventType.CacheAll);
Assert.AreEqual(EventType.CacheAll, events.GetEnabledEvents());
Assert.IsTrue(EventType.CacheAll.All(events.IsEnabled));
events.EnableLocal(EventType.TaskExecutionAll);
events.DisableLocal(EventType.CacheAll);
Assert.AreEqual(EventType.TaskExecutionAll, events.GetEnabledEvents());
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[Test]
public void TestLocalListen()
{
var events = _grid1.GetEvents();
var listener = EventsTestHelper.GetListener();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
events.LocalListen(listener, eventType);
CheckSend(3); // 3 events per task * 3 grids
// Check unsubscription for specific event
events.StopLocalListen(listener, EventType.TaskReduced);
CheckSend(2);
// Unsubscribe from all events
events.StopLocalListen(listener, Enumerable.Empty<int>());
CheckNoEvent();
// Check unsubscription by filter
events.LocalListen(listener, EventType.TaskReduced);
CheckSend();
EventsTestHelper.ListenResult = false;
CheckSend(); // one last event will be received for each listener
CheckNoEvent();
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[Test]
[Ignore("IGNITE-879")]
public void TestLocalListenRepeatedSubscription()
{
var events = _grid1.GetEvents();
var listener = EventsTestHelper.GetListener();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
events.LocalListen(listener, eventType);
CheckSend(3); // 3 events per task * 3 grids
events.LocalListen(listener, eventType);
events.LocalListen(listener, eventType);
CheckSend(9);
events.StopLocalListen(listener, eventType);
CheckSend(6);
events.StopLocalListen(listener, eventType);
CheckSend(3);
events.StopLocalListen(listener, eventType);
CheckNoEvent();
}
/// <summary>
/// Tests all available event types/classes.
/// </summary>
[Test, TestCaseSource("TestCases")]
public void TestEventTypes(EventTestCase testCase)
{
var events = _grid1.GetEvents();
events.EnableLocal(testCase.EventType);
var listener = EventsTestHelper.GetListener();
events.LocalListen(listener, testCase.EventType);
EventsTestHelper.ClearReceived(testCase.EventCount);
testCase.GenerateEvent(_grid1);
EventsTestHelper.VerifyReceive(testCase.EventCount, testCase.EventObjectType, testCase.EventType);
if (testCase.VerifyEvents != null)
testCase.VerifyEvents(EventsTestHelper.ReceivedEvents.Reverse(), _grid1);
// Check stop
events.StopLocalListen(listener);
EventsTestHelper.ClearReceived(0);
testCase.GenerateEvent(_grid1);
Thread.Sleep(EventsTestHelper.Timeout);
}
/// <summary>
/// Test cases for TestEventTypes: type id + type + event generator.
/// </summary>
public IEnumerable<EventTestCase> TestCases
{
get
{
yield return new EventTestCase
{
EventType = EventType.CacheAll,
EventObjectType = typeof (CacheEvent),
GenerateEvent = g => g.GetCache<int, int>(CacheName).Put(TestUtils.GetPrimaryKey(g, CacheName), 1),
VerifyEvents = (e, g) => VerifyCacheEvents(e, g),
EventCount = 3
};
yield return new EventTestCase
{
EventType = EventType.TaskExecutionAll,
EventObjectType = typeof (TaskEvent),
GenerateEvent = g => GenerateTaskEvent(g),
VerifyEvents = (e, g) => VerifyTaskEvents(e),
EventCount = 3
};
yield return new EventTestCase
{
EventType = EventType.JobExecutionAll,
EventObjectType = typeof (JobEvent),
GenerateEvent = g => GenerateTaskEvent(g),
EventCount = 7
};
yield return new EventTestCase
{
EventType = new[] {EventType.CacheQueryExecuted},
EventObjectType = typeof (CacheQueryExecutedEvent),
GenerateEvent = g => GenerateCacheQueryEvent(g),
EventCount = 1
};
yield return new EventTestCase
{
EventType = new[] { EventType.CacheQueryObjectRead },
EventObjectType = typeof (CacheQueryReadEvent),
GenerateEvent = g => GenerateCacheQueryEvent(g),
EventCount = 1
};
}
}
/// <summary>
/// Tests the LocalQuery.
/// </summary>
[Test]
public void TestLocalQuery()
{
var events = _grid1.GetEvents();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
var oldEvents = events.LocalQuery();
GenerateTaskEvent();
// "Except" works because of overridden equality
var qryResult = events.LocalQuery(eventType).Except(oldEvents).ToList();
Assert.AreEqual(3, qryResult.Count);
}
/// <summary>
/// Tests the record local.
/// </summary>
[Test]
public void TestRecordLocal()
{
Assert.Throws<NotSupportedException>(() => _grid1.GetEvents().RecordLocal(new MyEvent()));
}
/// <summary>
/// Tests the WaitForLocal.
/// </summary>
[Test]
public void TestWaitForLocal()
{
var events = _grid1.GetEvents();
var timeout = TimeSpan.FromSeconds(3);
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
var taskFuncs = GetWaitTasks(events).Select(
func => (Func<IEventFilter<IEvent>, int[], Task<IEvent>>) (
(filter, types) =>
{
var task = func(filter, types);
Thread.Sleep(100); // allow task to start and begin waiting for events
GenerateTaskEvent();
return task;
})).ToArray();
for (int i = 0; i < taskFuncs.Length; i++)
{
var getWaitTask = taskFuncs[i];
// No params
var waitTask = getWaitTask(null, new int[0]);
waitTask.Wait(timeout);
// Event types
waitTask = getWaitTask(null, new[] {EventType.TaskReduced});
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
if (i > 3)
{
// Filter
waitTask = getWaitTask(new LocalEventFilter<IEvent>(e => e.Type == EventType.TaskReduced), new int[0]);
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
// Filter & types
waitTask = getWaitTask(new LocalEventFilter<IEvent>(e => e.Type == EventType.TaskReduced),
new[] {EventType.TaskReduced});
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
}
}
}
/// <summary>
/// Gets the wait tasks for different overloads of WaitForLocal.
/// </summary>
private static IEnumerable<Func<IEventFilter<IEvent>, int[], Task<IEvent>>> GetWaitTasks(IEvents events)
{
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(types));
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(types.ToList()));
yield return (filter, types) => events.WaitForLocalAsync(types);
yield return (filter, types) => events.WaitForLocalAsync(types.ToList());
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(filter, types));
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(filter, types.ToList()));
yield return (filter, types) => events.WaitForLocalAsync(filter, types);
yield return (filter, types) => events.WaitForLocalAsync(filter, types.ToList());
}
/// <summary>
/// Tests the wait for local overloads.
/// </summary>
[Test]
public void TestWaitForLocalOverloads()
{
}
/*
/// <summary>
/// Tests RemoteListen.
/// </summary>
[Test]
public void TestRemoteListen(
[Values(true, false)] bool async,
[Values(true, false)] bool binarizable,
[Values(true, false)] bool autoUnsubscribe)
{
foreach (var g in _grids)
{
g.GetEvents().EnableLocal(EventType.JobExecutionAll);
g.GetEvents().EnableLocal(EventType.TaskExecutionAll);
}
var events = _grid1.GetEvents();
var expectedType = EventType.JobStarted;
var remoteFilter = binary
? (IEventFilter<IEvent>) new RemoteEventBinarizableFilter(expectedType)
: new RemoteEventFilter(expectedType);
var localListener = EventsTestHelper.GetListener();
if (async)
events = events.WithAsync();
var listenId = events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter,
autoUnsubscribe: autoUnsubscribe);
if (async)
listenId = events.GetFuture<Guid>().Get();
Assert.IsNotNull(listenId);
CheckSend(3, typeof(JobEvent), expectedType);
_grid3.GetEvents().DisableLocal(EventType.JobExecutionAll);
CheckSend(2, typeof(JobEvent), expectedType);
events.StopRemoteListen(listenId.Value);
if (async)
events.GetFuture().Get();
CheckNoEvent();
// Check unsubscription with listener
events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter,
autoUnsubscribe: autoUnsubscribe);
if (async)
events.GetFuture<Guid>().Get();
CheckSend(2, typeof(JobEvent), expectedType);
EventsTestHelper.ListenResult = false;
CheckSend(1, typeof(JobEvent), expectedType); // one last event
CheckNoEvent();
}*/
/// <summary>
/// Tests RemoteQuery.
/// </summary>
[Test]
public void TestRemoteQuery([Values(true, false)] bool async)
{
foreach (var g in _grids)
g.GetEvents().EnableLocal(EventType.JobExecutionAll);
var events = _grid1.GetEvents();
var eventFilter = new RemoteEventFilter(EventType.JobStarted);
var oldEvents = events.RemoteQuery(eventFilter);
GenerateTaskEvent();
var remoteQuery = !async
? events.RemoteQuery(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll)
: events.RemoteQueryAsync(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll).Result;
var qryResult = remoteQuery.Except(oldEvents).Cast<JobEvent>().ToList();
Assert.AreEqual(_grids.Length - 1, qryResult.Count);
Assert.IsTrue(qryResult.All(x => x.Type == EventType.JobStarted));
}
/// <summary>
/// Tests serialization.
/// </summary>
[Test]
public void TestSerialization()
{
var grid = (Ignite) _grid1;
var comp = (Impl.Compute.Compute) grid.GetCluster().ForLocal().GetCompute();
var locNode = grid.GetCluster().GetLocalNode();
var expectedGuid = Guid.Parse("00000000-0000-0001-0000-000000000002");
var expectedGridGuid = new IgniteGuid(expectedGuid, 3);
using (var inStream = IgniteManager.Memory.Allocate().GetStream())
{
var result = comp.ExecuteJavaTask<bool>("org.apache.ignite.platform.PlatformEventsWriteEventTask",
inStream.MemoryPointer);
Assert.IsTrue(result);
inStream.SynchronizeInput();
var reader = grid.Marshaller.StartUnmarshal(inStream);
var cacheEvent = EventReader.Read<CacheEvent>(reader);
CheckEventBase(cacheEvent);
Assert.AreEqual("cacheName", cacheEvent.CacheName);
Assert.AreEqual(locNode, cacheEvent.EventNode);
Assert.AreEqual(1, cacheEvent.Partition);
Assert.AreEqual(true, cacheEvent.IsNear);
Assert.AreEqual(2, cacheEvent.Key);
Assert.AreEqual(expectedGridGuid, cacheEvent.Xid);
Assert.AreEqual(4, cacheEvent.NewValue);
Assert.AreEqual(true, cacheEvent.HasNewValue);
Assert.AreEqual(5, cacheEvent.OldValue);
Assert.AreEqual(true, cacheEvent.HasOldValue);
Assert.AreEqual(expectedGuid, cacheEvent.SubjectId);
Assert.AreEqual("cloClsName", cacheEvent.ClosureClassName);
Assert.AreEqual("taskName", cacheEvent.TaskName);
Assert.IsTrue(cacheEvent.ToShortString().StartsWith("NODE_FAILED: IsNear="));
var qryExecEvent = EventReader.Read<CacheQueryExecutedEvent>(reader);
CheckEventBase(qryExecEvent);
Assert.AreEqual("qryType", qryExecEvent.QueryType);
Assert.AreEqual("cacheName", qryExecEvent.CacheName);
Assert.AreEqual("clsName", qryExecEvent.ClassName);
Assert.AreEqual("clause", qryExecEvent.Clause);
Assert.AreEqual(expectedGuid, qryExecEvent.SubjectId);
Assert.AreEqual("taskName", qryExecEvent.TaskName);
Assert.AreEqual(
"NODE_FAILED: QueryType=qryType, CacheName=cacheName, ClassName=clsName, Clause=clause, " +
"SubjectId=00000000-0000-0001-0000-000000000002, TaskName=taskName", qryExecEvent.ToShortString());
var qryReadEvent = EventReader.Read<CacheQueryReadEvent>(reader);
CheckEventBase(qryReadEvent);
Assert.AreEqual("qryType", qryReadEvent.QueryType);
Assert.AreEqual("cacheName", qryReadEvent.CacheName);
Assert.AreEqual("clsName", qryReadEvent.ClassName);
Assert.AreEqual("clause", qryReadEvent.Clause);
Assert.AreEqual(expectedGuid, qryReadEvent.SubjectId);
Assert.AreEqual("taskName", qryReadEvent.TaskName);
Assert.AreEqual(1, qryReadEvent.Key);
Assert.AreEqual(2, qryReadEvent.Value);
Assert.AreEqual(3, qryReadEvent.OldValue);
Assert.AreEqual(4, qryReadEvent.Row);
Assert.AreEqual(
"NODE_FAILED: QueryType=qryType, CacheName=cacheName, ClassName=clsName, Clause=clause, " +
"SubjectId=00000000-0000-0001-0000-000000000002, TaskName=taskName, Key=1, Value=2, " +
"OldValue=3, Row=4", qryReadEvent.ToShortString());
var cacheRebalancingEvent = EventReader.Read<CacheRebalancingEvent>(reader);
CheckEventBase(cacheRebalancingEvent);
Assert.AreEqual("cacheName", cacheRebalancingEvent.CacheName);
Assert.AreEqual(1, cacheRebalancingEvent.Partition);
Assert.AreEqual(locNode, cacheRebalancingEvent.DiscoveryNode);
Assert.AreEqual(2, cacheRebalancingEvent.DiscoveryEventType);
Assert.AreEqual(3, cacheRebalancingEvent.DiscoveryTimestamp);
Assert.IsTrue(cacheRebalancingEvent.ToShortString().StartsWith(
"NODE_FAILED: CacheName=cacheName, Partition=1, DiscoveryNode=GridNode"));
var checkpointEvent = EventReader.Read<CheckpointEvent>(reader);
CheckEventBase(checkpointEvent);
Assert.AreEqual("cpKey", checkpointEvent.Key);
Assert.AreEqual("NODE_FAILED: Key=cpKey", checkpointEvent.ToShortString());
var discoEvent = EventReader.Read<DiscoveryEvent>(reader);
CheckEventBase(discoEvent);
Assert.AreEqual(grid.TopologyVersion, discoEvent.TopologyVersion);
Assert.AreEqual(grid.GetNodes(), discoEvent.TopologyNodes);
Assert.IsTrue(discoEvent.ToShortString().StartsWith("NODE_FAILED: EventNode=GridNode"));
var jobEvent = EventReader.Read<JobEvent>(reader);
CheckEventBase(jobEvent);
Assert.AreEqual(expectedGridGuid, jobEvent.JobId);
Assert.AreEqual("taskClsName", jobEvent.TaskClassName);
Assert.AreEqual("taskName", jobEvent.TaskName);
Assert.AreEqual(locNode, jobEvent.TaskNode);
Assert.AreEqual(expectedGridGuid, jobEvent.TaskSessionId);
Assert.AreEqual(expectedGuid, jobEvent.TaskSubjectId);
Assert.IsTrue(jobEvent.ToShortString().StartsWith("NODE_FAILED: TaskName=taskName"));
var taskEvent = EventReader.Read<TaskEvent>(reader);
CheckEventBase(taskEvent);
Assert.AreEqual(true,taskEvent.Internal);
Assert.AreEqual(expectedGuid, taskEvent.SubjectId);
Assert.AreEqual("taskClsName", taskEvent.TaskClassName);
Assert.AreEqual("taskName", taskEvent.TaskName);
Assert.AreEqual(expectedGridGuid, taskEvent.TaskSessionId);
Assert.IsTrue(taskEvent.ToShortString().StartsWith("NODE_FAILED: TaskName=taskName"));
}
}
/// <summary>
/// Tests the event store configuration.
/// </summary>
[Test]
public void TestConfiguration()
{
var cfg = _grid1.GetConfiguration().EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(cfg);
Assert.AreEqual(MemoryEventStorageSpi.DefaultExpirationTimeout, cfg.ExpirationTimeout);
Assert.AreEqual(MemoryEventStorageSpi.DefaultMaxEventCount, cfg.MaxEventCount);
// Test user-defined event storage.
var igniteCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid4",
EventStorageSpi = new MyEventStorage()
};
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(igniteCfg));
Assert.AreEqual("Unsupported IgniteConfiguration.EventStorageSpi: " +
"'Apache.Ignite.Core.Tests.MyEventStorage'. Supported implementations: " +
"'Apache.Ignite.Core.Events.NoopEventStorageSpi', " +
"'Apache.Ignite.Core.Events.MemoryEventStorageSpi'.", ex.Message);
}
/// <summary>
/// Checks base event fields serialization.
/// </summary>
/// <param name="evt">The evt.</param>
private void CheckEventBase(IEvent evt)
{
var locNode = _grid1.GetCluster().GetLocalNode();
Assert.AreEqual(locNode, evt.Node);
Assert.AreEqual("msg", evt.Message);
Assert.AreEqual(EventType.NodeFailed, evt.Type);
Assert.IsNotNullOrEmpty(evt.Name);
Assert.AreNotEqual(Guid.Empty, evt.Id.GlobalId);
Assert.IsTrue(Math.Abs((evt.Timestamp - DateTime.UtcNow).TotalSeconds) < 20,
"Invalid event timestamp: '{0}', current time: '{1}'", evt.Timestamp, DateTime.Now);
Assert.Greater(evt.LocalOrder, 0);
Assert.IsTrue(evt.ToString().Contains("[Name=NODE_FAILED"));
Assert.IsTrue(evt.ToShortString().StartsWith("NODE_FAILED"));
}
/// <summary>
/// Sends events in various ways and verifies correct receive.
/// </summary>
/// <param name="repeat">Expected event count multiplier.</param>
/// <param name="eventObjectType">Expected event object type.</param>
/// <param name="eventType">Type of the event.</param>
private void CheckSend(int repeat = 1, Type eventObjectType = null, params int[] eventType)
{
EventsTestHelper.ClearReceived(repeat);
GenerateTaskEvent();
EventsTestHelper.VerifyReceive(repeat, eventObjectType ?? typeof (TaskEvent),
eventType.Any() ? eventType : EventType.TaskExecutionAll);
}
/// <summary>
/// Checks that no event has arrived.
/// </summary>
private void CheckNoEvent()
{
// this will result in an exception in case of a event
EventsTestHelper.ClearReceived(0);
GenerateTaskEvent();
Thread.Sleep(EventsTestHelper.Timeout);
EventsTestHelper.AssertFailures();
}
/// <summary>
/// Gets the Ignite configuration.
/// </summary>
private static IgniteConfiguration GetConfiguration(string name, bool client = false)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = name,
EventStorageSpi = new MemoryEventStorageSpi(),
CacheConfiguration = new [] {new CacheConfiguration(CacheName) },
ClientMode = client
};
}
/// <summary>
/// Generates the task event.
/// </summary>
private void GenerateTaskEvent(IIgnite grid = null)
{
(grid ?? _grid1).GetCompute().Broadcast(new ComputeAction());
}
/// <summary>
/// Verifies the task events.
/// </summary>
private static void VerifyTaskEvents(IEnumerable<IEvent> events)
{
var e = events.Cast<TaskEvent>().ToArray();
// started, reduced, finished
Assert.AreEqual(
new[] {EventType.TaskStarted, EventType.TaskReduced, EventType.TaskFinished},
e.Select(x => x.Type).ToArray());
}
/// <summary>
/// Generates the cache query event.
/// </summary>
private static void GenerateCacheQueryEvent(IIgnite g)
{
var cache = g.GetCache<int, int>(CacheName);
cache.Clear();
cache.Put(TestUtils.GetPrimaryKey(g, CacheName), 1);
cache.Query(new ScanQuery<int, int>()).GetAll();
}
/// <summary>
/// Verifies the cache events.
/// </summary>
private static void VerifyCacheEvents(IEnumerable<IEvent> events, IIgnite grid)
{
var e = events.Cast<CacheEvent>().ToArray();
foreach (var cacheEvent in e)
{
Assert.AreEqual(CacheName, cacheEvent.CacheName);
Assert.AreEqual(null, cacheEvent.ClosureClassName);
Assert.AreEqual(null, cacheEvent.TaskName);
Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.EventNode);
Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.Node);
Assert.AreEqual(false, cacheEvent.HasOldValue);
Assert.AreEqual(null, cacheEvent.OldValue);
if (cacheEvent.Type == EventType.CacheObjectPut)
{
Assert.AreEqual(true, cacheEvent.HasNewValue);
Assert.AreEqual(1, cacheEvent.NewValue);
}
else if (cacheEvent.Type == EventType.CacheEntryCreated)
{
Assert.AreEqual(false, cacheEvent.HasNewValue);
Assert.AreEqual(null, cacheEvent.NewValue);
}
else if (cacheEvent.Type == EventType.CacheEntryDestroyed)
{
Assert.IsFalse(cacheEvent.HasNewValue);
Assert.IsFalse(cacheEvent.HasOldValue);
}
else
{
Assert.Fail("Unexpected event type");
}
}
}
/// <summary>
/// Starts the grids.
/// </summary>
private void StartGrids()
{
if (_grid1 != null)
return;
_grid1 = Ignition.Start(GetConfiguration("grid1"));
_grid2 = Ignition.Start(GetConfiguration("grid2"));
_grid3 = Ignition.Start(GetConfiguration("grid3", true));
_grids = new[] {_grid1, _grid2, _grid3};
}
/// <summary>
/// Stops the grids.
/// </summary>
private void StopGrids()
{
_grid1 = _grid2 = _grid3 = null;
_grids = null;
Ignition.StopAll(true);
}
}
/// <summary>
/// Event test helper class.
/// </summary>
[Serializable]
public static class EventsTestHelper
{
/** */
public static readonly ConcurrentStack<IEvent> ReceivedEvents = new ConcurrentStack<IEvent>();
/** */
public static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>();
/** */
public static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0);
/** */
public static readonly ConcurrentStack<Guid?> LastNodeIds = new ConcurrentStack<Guid?>();
/** */
public static volatile bool ListenResult = true;
/** */
public static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(800);
/// <summary>
/// Clears received event information.
/// </summary>
/// <param name="expectedCount">The expected count of events to be received.</param>
public static void ClearReceived(int expectedCount)
{
ReceivedEvents.Clear();
ReceivedEvent.Reset(expectedCount);
LastNodeIds.Clear();
}
/// <summary>
/// Verifies received events against events events.
/// </summary>
public static void VerifyReceive(int count, Type eventObjectType, ICollection<int> eventTypes)
{
// check if expected event count has been received; Wait returns false if there were none.
Assert.IsTrue(ReceivedEvent.Wait(Timeout),
"Failed to receive expected number of events. Remaining count: " + ReceivedEvent.CurrentCount);
Assert.AreEqual(count, ReceivedEvents.Count);
Assert.IsTrue(ReceivedEvents.All(x => x.GetType() == eventObjectType));
Assert.IsTrue(ReceivedEvents.All(x => eventTypes.Contains(x.Type)));
AssertFailures();
}
/// <summary>
/// Gets the event listener.
/// </summary>
/// <returns>New instance of event listener.</returns>
public static IEventListener<IEvent> GetListener()
{
return new LocalEventFilter<IEvent>(Listen);
}
/// <summary>
/// Combines accumulated failures and throws an assertion, if there are any.
/// Clears accumulated failures.
/// </summary>
public static void AssertFailures()
{
try
{
if (Failures.Any())
Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y)));
}
finally
{
Failures.Clear();
}
}
/// <summary>
/// Listen method.
/// </summary>
/// <param name="evt">Event.</param>
private static bool Listen(IEvent evt)
{
try
{
LastNodeIds.Push(evt.Node.Id);
ReceivedEvents.Push(evt);
ReceivedEvent.Signal();
return ListenResult;
}
catch (Exception ex)
{
// When executed on remote nodes, these exceptions will not go to sender,
// so we have to accumulate them.
Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", evt, evt.Node.Id, ex));
throw;
}
}
}
/// <summary>
/// Test event filter.
/// </summary>
[Serializable]
public class LocalEventFilter<T> : IEventFilter<T>, IEventListener<T> where T : IEvent
{
/** */
private readonly Func<T, bool> _invoke;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteListenEventFilter"/> class.
/// </summary>
/// <param name="invoke">The invoke delegate.</param>
public LocalEventFilter(Func<T, bool> invoke)
{
_invoke = invoke;
}
/** <inheritdoc /> */
bool IEventFilter<T>.Invoke(T evt)
{
return _invoke(evt);
}
/** <inheritdoc /> */
bool IEventListener<T>.Invoke(T evt)
{
return _invoke(evt);
}
/** <inheritdoc /> */
// ReSharper disable once UnusedMember.Global
public bool Invoke(T evt)
{
throw new Exception("Invalid method");
}
}
/// <summary>
/// Remote event filter.
/// </summary>
[Serializable]
public class RemoteEventFilter : IEventFilter<IEvent>
{
/** */
private readonly int _type;
/** */
[InstanceResource]
public IIgnite Ignite { get; set; }
public RemoteEventFilter(int type)
{
_type = type;
}
/** <inheritdoc /> */
public bool Invoke(IEvent evt)
{
Assert.IsNotNull(Ignite);
return evt.Type == _type;
}
}
/// <summary>
/// Event test case.
/// </summary>
public class EventTestCase
{
/// <summary>
/// Gets or sets the type of the event.
/// </summary>
public ICollection<int> EventType { get; set; }
/// <summary>
/// Gets or sets the type of the event object.
/// </summary>
public Type EventObjectType { get; set; }
/// <summary>
/// Gets or sets the generate event action.
/// </summary>
public Action<IIgnite> GenerateEvent { get; set; }
/// <summary>
/// Gets or sets the verify events action.
/// </summary>
public Action<IEnumerable<IEvent>, IIgnite> VerifyEvents { get; set; }
/// <summary>
/// Gets or sets the event count.
/// </summary>
public int EventCount { get; set; }
/** <inheritdoc /> */
public override string ToString()
{
return EventObjectType.ToString();
}
}
/// <summary>
/// Custom event.
/// </summary>
public class MyEvent : IEvent
{
/** <inheritdoc /> */
public IgniteGuid Id
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public long LocalOrder
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public IClusterNode Node
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string Message
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public int Type
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string Name
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public DateTime Timestamp
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string ToShortString()
{
throw new NotImplementedException();
}
}
public class MyEventStorage : IEventStorageSpi
{
// No-op.
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using Xunit;
namespace System.Collections.Tests
{
public class StackBasicTests
{
[Fact]
public static void EmptyStackSizeIsZero()
{
Stack stack = new Stack();
Assert.Equal(0, stack.Count);
}
[Fact]
public static void DefaultStackIsNotSynchronized()
{
Stack stack = new Stack();
Assert.False(stack.IsSynchronized);
}
[Fact]
public static void NumberOfElementsAddedIsEqualToStackSize()
{
int iNumElementsAdded = 1975;
Stack stack = new Stack();
for (int i = 0; i < iNumElementsAdded; i++)
{
stack.Push(new Object());
}
Assert.Equal(stack.Count, iNumElementsAdded);
}
[Fact]
public static void ClearResetsNumberOfElementsToZero()
{
int iNumElementsAdded = 2;
Stack stack = new Stack();
for (int i = 0; i < iNumElementsAdded; i++)
{
stack.Push(new Object());
}
stack.Clear();
Assert.Equal(0, stack.Count);
}
[Fact]
public static void PopDecrementsStackSize()
{
int iNumElementsAdded = 25;
Stack stack = new Stack();
for (int i = 0; i < iNumElementsAdded; i++)
{
stack.Push(i);
}
for (int i = 0; i < iNumElementsAdded; i++)
{
Assert.Equal(stack.Count, iNumElementsAdded - i);
Object objTop = stack.Pop();
Assert.Equal(stack.Count, iNumElementsAdded - i - 1);
}
}
[Fact]
public static void PeekingEmptyStackThrows()
{
Stack stack = new Stack();
Assert.Throws<InvalidOperationException>(() => { var x = stack.Peek(); });
}
[Fact]
public static void PeekingEmptyStackAfterRemovingElementsThrows()
{
object objRet;
Stack stack = new Stack();
for (int i = 0; i < 1000; i++)
{
stack.Push(i);
}
for (int i = 0; i < 1000; i++)
{
objRet = stack.Pop();
}
Assert.Throws<InvalidOperationException>(() => { objRet = stack.Peek(); });
}
[Fact]
public static void ICollectionCanBeGivenToStack()
{
int iNumElements = 10000;
var objArr = new Object[iNumElements];
for (int i = 0; i < iNumElements; i++)
{
objArr[i] = i;
}
Stack stack = new Stack(objArr);
for (int i = 0; i < iNumElements; i++)
{
var objRet = stack.Pop();
Assert.True(objRet.Equals(iNumElements - i - 1));
}
}
[Fact]
public static void PeekingAtElementTwiceGivesSameResults()
{
Stack stack = new Stack();
stack.Push(1);
Assert.True(stack.Peek().Equals(stack.Peek()));
}
[Fact]
public static void PushAndPopWorkOnNullElements()
{
Stack stack = new Stack();
stack.Push(null);
stack.Push(-1);
stack.Push(null);
Assert.Equal(stack.Pop(), null);
Assert.True((-1).Equals(stack.Pop()));
Assert.Equal(stack.Pop(), null);
}
[Fact]
public static void CopyingToNullArrayThrows()
{
Stack stack = new Stack();
stack.Push("hey");
Assert.Throws<ArgumentNullException>(() => stack.CopyTo(null, 0));
}
[Fact]
public static void CopyingToMultiDimArrayThrows()
{
Stack stack = new Stack();
stack.Push("hey");
Assert.Throws<ArgumentException>(() => stack.CopyTo(new Object[8, 8], 0));
}
[Fact]
public static void CopyingOutOfRangeThrows_1()
{
Stack stack = new Stack();
var objArr = new Object[0];
Assert.Throws<ArgumentException>(() => stack.CopyTo(objArr, 1));
stack = new Stack();
Assert.Throws<ArgumentException>(() => stack.CopyTo(objArr, Int32.MaxValue));
stack = new Stack();
Assert.Throws<ArgumentOutOfRangeException>(() => stack.CopyTo(objArr, Int32.MinValue));
stack = new Stack();
Assert.Throws<ArgumentOutOfRangeException>(() => stack.CopyTo(objArr, -1));
}
[Fact]
public static void CopyingOutOfRangeThrows_2()
{
Stack stack = new Stack();
stack.Push("MyString");
var objArr = new Object[0];
Assert.Throws<ArgumentException>(() => stack.CopyTo(objArr, 0));
}
[Fact]
public static void GettingEnumeratorAndLoopingThroughWorks()
{
Stack stack = new Stack();
stack.Push("hey");
stack.Push("hello");
IEnumerator ienum = stack.GetEnumerator();
int iCounter = 0;
while (ienum.MoveNext())
{
iCounter++;
}
Assert.Equal(iCounter, stack.Count);
}
[Fact]
public static void GetBeforeStartingEnumerator()
{
// NOTE: The docs say this behaviour is undefined so if test fails it might be ok
Stack stack = new Stack();
stack.Push("a");
stack.Push("b");
IEnumerator ienum = stack.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => { Object obj = ienum.Current; });
}
[Fact]
public static void EnumeratingBeyondEndOfListThenGetObject()
{
Stack stack = new Stack();
stack.Push(new Object());
stack.Push(stack);
IEnumerator ienum = stack.GetEnumerator();
Assert.True(ienum.MoveNext());
for (int i = 0; i < 100; i++)
{
Object objTemp1 = ienum.Current;
Assert.True(objTemp1.Equals(stack));
}
Assert.True(ienum.MoveNext());
for (int i = 0; i < 100; i++)
{
Assert.False(ienum.MoveNext());
}
Assert.Throws<InvalidOperationException>(() => { var o = ienum.Current; });
}
[Fact]
public static void PassingNegativeCapacityThrows()
{
Assert.Throws<ArgumentOutOfRangeException>(() => { Stack stack = new Stack(Int32.MinValue); });
}
[Fact]
public static void CreatingStackWithZeroCapacityDoesntThrow()
{
Stack stack = new Stack(0);
}
[Fact]
public static void PassingValidCapacityCreatesZeroElementsStack()
{
Stack stack = new Stack(1);
Assert.Equal(0, stack.Count);
}
[Fact]
public static void SynchronizedStacksIsSynchronizedPropertyReturnsTrue()
{
Stack stack = Stack.Synchronized(new Stack());
Assert.True(stack.IsSynchronized);
}
[Fact]
public static void SynchronizingNullStackThrows()
{
Assert.Throws<ArgumentNullException>(() => { Stack stack = Stack.Synchronized(null); });
}
[Fact]
public static void TestingAllMethodsOfSynchronizedStack()
{
Stack q1 = new Stack();
for (int i = 0; i < 10; i++)
{
q1.Push("String_" + i);
}
Stack q2 = Stack.Synchronized(q1);
Assert.Equal(q2.Count, q1.Count);
q2.Clear();
Assert.Equal(0, q2.Count);
for (int i = 0; i < 10; i++)
{
q2.Push("String_" + i);
}
for (int i = 0, j = 9; i < 10; i++, j--)
{
Assert.True(((String)q2.Peek()).Equals("String_" + j));
Assert.True(((String)q2.Pop()).Equals("String_" + j));
}
Assert.Equal(0, q2.Count);
Assert.True(q2.IsSynchronized);
for (int i = 0; i < 10; i++)
q2.Push("String_" + i);
Stack q3 = Stack.Synchronized(q2);
Assert.True(q3.IsSynchronized);
Assert.Equal(q2.Count, q3.Count);
var strArr = new String[10];
q2.CopyTo(strArr, 0);
for (int i = 0, j = 9; i < 10; i++, j--)
{
Assert.True(strArr[i].Equals("String_" + j));
}
strArr = new String[10 + 10];
q2.CopyTo(strArr, 10);
for (int i = 0, j = 9; i < 10; i++, j--)
{
Assert.True(strArr[i + 10].Equals("String_" + j));
}
Assert.Throws<ArgumentNullException>(() => q2.CopyTo(null, 0));
var oArr = q2.ToArray();
for (int i = 0, j = 9; i < 10; i++, j--)
{
Assert.True(((String)oArr[i]).Equals("String_" + j));
}
var ienm1 = q2.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => { var oValue = ienm1.Current; });
var iCount = 9;
while (ienm1.MoveNext())
{
Assert.True(((String)ienm1.Current).Equals("String_" + iCount));
iCount--;
}
ienm1.Reset();
iCount = 9;
while (ienm1.MoveNext())
{
Assert.True(((String)ienm1.Current).Equals("String_" + iCount));
iCount--;
}
ienm1.Reset();
q2.Pop();
Assert.Throws<InvalidOperationException>(() => { var oValue = ienm1.Current; });
Assert.Throws<InvalidOperationException>(() => ienm1.MoveNext());
Assert.Throws<InvalidOperationException>(() => ienm1.Reset());
}
[Fact]
public static void PassingNullCollectionToConstructorThrows()
{
Assert.Throws<ArgumentNullException>(() => { Stack stack = new Stack(null); });
}
[Fact]
public void DebuggerAttributeTests()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Stack());
var testStack = new Stack();
testStack.Push("a");
testStack.Push(1);
testStack.Push("b");
testStack.Push(2);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(testStack);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Xml.Linq;
using FluentAssertions.Common;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
namespace FluentAssertions.Xml
{
/// <summary>
/// Contains a number of methods to assert that an <see cref="XDocument"/> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class XDocumentAssertions : ReferenceTypeAssertions<XDocument, XDocumentAssertions>
{
/// <summary>
/// Initializes a new instance of the <see cref="XDocumentAssertions" /> class.
/// </summary>
public XDocumentAssertions(XDocument document)
{
Subject = document;
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> equals the <paramref name="expected"/> document,
/// using its <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected document</param>
public AndConstraint<XDocumentAssertions> Be(XDocument expected)
{
return Be(expected, string.Empty);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> equals the <paramref name="expected"/> document,
/// using its <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">The expected document</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<XDocumentAssertions> Be(XDocument expected, string because, params object[] reasonArgs)
{
Execute.Assertion
.ForCondition(Subject.IsSameOrEqualTo(expected))
.BecauseOf(because, reasonArgs)
.FailWith("Expected XML document to be {0}{reason}, but found {1}", expected, Subject);
return new AndConstraint<XDocumentAssertions>(this);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> does not equal the <paramref name="unexpected"/> document,
/// using its <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected document</param>
public AndConstraint<XDocumentAssertions> NotBe(XDocument unexpected)
{
return NotBe(unexpected, string.Empty);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> does not equal the <paramref name="unexpected"/> document,
/// using its <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected document</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<XDocumentAssertions> NotBe(XDocument unexpected, string because, params object[] reasonArgs)
{
Execute.Assertion
.ForCondition(!ReferenceEquals(Subject, null))
.BecauseOf(because, reasonArgs)
.FailWith("Did not expect XML document to be {0}, but found <null>.", unexpected);
Execute.Assertion
.ForCondition(!Subject.Equals(unexpected))
.BecauseOf(because, reasonArgs)
.FailWith("Did not expect XML document to be {0}{reason}.", unexpected);
return new AndConstraint<XDocumentAssertions>(this);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> is equivalent to the <paramref name="expected"/> document,
/// using its <see cref="XNode.DeepEquals()" /> implementation.
/// </summary>
/// <param name="expected">The expected document</param>
public AndConstraint<XDocumentAssertions> BeEquivalentTo(XDocument expected)
{
return BeEquivalentTo(expected, string.Empty);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> is equivalent to the <paramref name="expected"/> document,
/// using its <see cref="XNode.DeepEquals()" /> implementation.
/// </summary>
/// <param name="expected">The expected document</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<XDocumentAssertions> BeEquivalentTo(XDocument expected, string because, params object[] reasonArgs)
{
Execute.Assertion
.ForCondition(XNode.DeepEquals(Subject, expected))
.BecauseOf(because, reasonArgs)
.FailWith("Expected XML document {0} to be equivalent to {1}{reason}.",
Subject, expected);
return new AndConstraint<XDocumentAssertions>(this);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> is not equivalent to the <paramref name="unexpected"/> document,
/// using its <see cref="XNode.DeepEquals()" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected document</param>
public AndConstraint<XDocumentAssertions> NotBeEquivalentTo(XDocument unexpected)
{
return NotBeEquivalentTo(unexpected, string.Empty);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> is not equivalent to the <paramref name="unexpected"/> document,
/// using its <see cref="XNode.DeepEquals()" /> implementation.
/// </summary>
/// <param name="unexpected">The unexpected document</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndConstraint<XDocumentAssertions> NotBeEquivalentTo(XDocument unexpected, string because, params object[] reasonArgs)
{
Execute.Assertion
.ForCondition(!XNode.DeepEquals(Subject, unexpected))
.BecauseOf(because, reasonArgs)
.FailWith("Did not expect XML document {0} to be equivalent to {1}{reason}.",
Subject, unexpected);
return new AndConstraint<XDocumentAssertions>(this);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> has a root element with the specified
/// <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">The name of the expected root element of the current document.</param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveRoot(string expected)
{
return HaveRoot(expected, string.Empty);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> has a root element with the specified
/// <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">The name of the expected root element of the current document.</param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveRoot(XName expected)
{
return HaveRoot(expected, string.Empty);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> has a root element with the specified
/// <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">The name of the expected root element of the current document.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveRoot(string expected, string because,
params object[] reasonArgs)
{
if (expected == null)
{
throw new ArgumentNullException("expected",
"Cannot assert the document has a root element if the element name is <null>*");
}
return HaveRoot(XNamespace.None + expected, because, reasonArgs);
}
/// <summary>
/// Asserts that the current <see cref="XDocument"/> has a root element with the specified
/// <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">The full name <see cref="XName"/> of the expected root element of the current document.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveRoot(XName expected, string because, params object[] reasonArgs)
{
if (Subject == null)
{
throw new ArgumentNullException("subject",
"Cannot assert the document has a root element if the document itself is <null>.");
}
if (expected == null)
{
throw new ArgumentNullException("expected",
"Cannot assert the document has a root element if the element name is <null>*");
}
XElement root = Subject.Root;
Execute.Assertion
.ForCondition((root != null) && (root.Name == expected))
.BecauseOf(because, reasonArgs)
.FailWith("Expected XML document to have root element \"" + expected.ToString().Escape() + "\"{reason}" +
", but found {0}.", Subject);
return new AndWhichConstraint<XDocumentAssertions, XElement>(this, root);
}
/// <summary>
/// Asserts that the <see cref="XDocument.Root"/> element of the current <see cref="XDocument"/> has a direct
/// child element with the specified <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">
/// The name of the expected child element of the current document's Root <see cref="XDocument.Root"/> element.
/// </param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveElement(string expected)
{
return HaveElement(expected, string.Empty);
}
/// <summary>
/// Asserts that the <see cref="XDocument.Root"/> element of the current <see cref="XDocument"/> has a direct
/// child element with the specified <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">
/// The full name <see cref="XName"/> of the expected child element of the current document's Root <see cref="XDocument.Root"/> element.
/// </param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveElement(XName expected)
{
return HaveElement(expected, string.Empty);
}
/// <summary>
/// Asserts that the <see cref="XDocument.Root"/> element of the current <see cref="XDocument"/> has a direct
/// child element with the specified <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">
/// The name of the expected child element of the current document's Root <see cref="XDocument.Root"/> element.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveElement(string expected, string because,
params object[] reasonArgs)
{
if (expected == null)
{
throw new ArgumentNullException("expected",
"Cannot assert the document has an element if the element name is <null>*");
}
return HaveElement(XNamespace.None + expected, because, reasonArgs);
}
/// <summary>
/// Asserts that the <see cref="XDocument.Root"/> element of the current <see cref="XDocument"/> has a direct
/// child element with the specified <paramref name="expected"/> name.
/// </summary>
/// <param name="expected">
/// The full name <see cref="XName"/> of the expected child element of the current document's Root <see cref="XDocument.Root"/> element.
/// </param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="reasonArgs">
/// Zero or more objects to format using the placeholders in <see cref="because" />.
/// </param>
public AndWhichConstraint<XDocumentAssertions, XElement> HaveElement(XName expected, string because,
params object[] reasonArgs)
{
if (Subject == null)
{
throw new ArgumentNullException("subject",
"Cannot assert the document has an element if the document itself is <null>.");
}
if (expected == null)
{
throw new ArgumentNullException("expected",
"Cannot assert the document has an element if the element name is <null>*");
}
string expectedText = expected.ToString().Escape();
Execute.Assertion
.ForCondition(Subject.Root != null)
.BecauseOf(because, reasonArgs)
.FailWith("Expected XML document {0} to have root element with child \"" + expectedText + "\"{reason}" +
", but XML document has no Root element.", Subject);
XElement xElement = Subject.Root.Element(expected);
Execute.Assertion
.ForCondition(xElement != null)
.BecauseOf(because, reasonArgs)
.FailWith("Expected XML document {0} to have root element with child \"" + expectedText + "\"{reason}" +
", but no such child element was found.", Subject);
return new AndWhichConstraint<XDocumentAssertions, XElement>(this, xElement);
}
/// <summary>
/// Returns the type of the subject the assertion applies on.
/// </summary>
protected override string Context
{
get { return "XML document"; }
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ResourceLevel
{
Empty,
Low,
Medium,
High,
Full
}
public class Tile : MonoBehaviour {
[SerializeField, Tooltip("Unscanned colour")]
private Color m_normalColour = Color.white;
[SerializeField, Tooltip("Lowest amount resource colour")]
private Color m_emptyColour = Color.grey;
[SerializeField, Tooltip("Low amount resource colour")]
private Color m_lowColour = Color.green;
[SerializeField, Tooltip("Medium amount resource colour")]
private Color m_mediumColour = Color.yellow;
[SerializeField, Tooltip("High amount resource colour")]
private Color m_highColour = Color.red + Color.yellow;
[SerializeField, Tooltip("Full amount resource colour")]
private Color m_fullColour = Color.red;
// Click delay variables
[SerializeField, Tooltip("Delay between clicks")]
private float m_clickDelay = 0.5f;
private float m_currentClickTime = 0.0f;
private bool m_canClick = true;
// Tile data
private int m_row = 0;
private int m_column = 0;
private float m_value = 1.0f / 8.0f;
private ResourceLevel m_currentLevel = ResourceLevel.Low;
private bool m_hasBeenScanned = false;
private bool m_hasBeenExtracted = false;
// Reference to the renderer and colour
private MeshRenderer m_meshRenderer;
private Color m_currentColour;
void Start()
{
// Set the starting colour
m_currentColour = m_normalColour;
m_meshRenderer = GetComponent<MeshRenderer>();
m_meshRenderer.material.color = m_currentColour;
}
void Update()
{
// Count the click timer after a click
if(!m_canClick)
{
if(m_currentClickTime < m_clickDelay)
{
m_currentClickTime += Time.deltaTime;
}
else
{
m_currentClickTime = 0;
m_canClick = true;
}
}
}
/// <summary>
/// Can the tile be clicked?
/// </summary>
/// <returns>True if the tile can be clicked</returns>
public bool CanBeClicked()
{
return m_canClick;
}
/// <summary>
/// Call this function when the tile is clicked
/// </summary>
public void Click()
{
m_canClick = true;
}
/// <summary>
/// Set the value of the tile
/// </summary>
/// <param name="row">X coordinate</param>
/// <param name="col">Y coordinate</param>
public void SetPositionValues(int row, int col)
{
m_row = row;
m_column = col;
}
/// <summary>
/// Get row of the tile
/// </summary>
/// <returns>X coordinate</returns>
public int GetRow()
{
return m_row;
}
/// <summary>
/// Get column of the tile
/// </summary>
/// <returns>Y coordinate</returns>
public int GetColumn()
{
return m_column;
}
/// <summary>
/// Get the current colour of the tile
/// </summary>
/// <returns>Current colour</returns>
public Color GetCurrentColour()
{
return m_currentColour;
}
/// <summary>
/// Set a new value for the tile
/// </summary>
/// <param name="newValue">The new value</param>
public void SetNewTileValue(float newValue)
{
m_value = newValue;
if (m_value <= (1.0f / 16.0f))
{
m_currentLevel = ResourceLevel.Empty;
}
else if (m_value <= (1.0f / 8.0f))
{
m_currentLevel = ResourceLevel.Low;
}
else if (m_value <= (1.0f / 4.0f))
{
m_currentLevel = ResourceLevel.Medium;
}
else if (m_value <= (1.0f / 2.0f))
{
m_currentLevel = ResourceLevel.High;
}
else if (m_value <= 1.0f)
{
m_currentLevel = ResourceLevel.Full;
}
else
{
Debug.LogWarning("Value not set properly");
}
}
/// <summary>
/// Get the tile's current value
/// </summary>
/// <returns></returns>
public float GetTileValue()
{
return m_value;
}
/// <summary>
/// Has the tile been scanned
/// </summary>
/// <returns></returns>
public bool IsScanned()
{
return m_hasBeenScanned;
}
/// <summary>
/// Scan the tile
/// </summary>
public void Scan()
{
m_hasBeenScanned = true;
switch (m_currentLevel)
{
case ResourceLevel.Empty:
m_currentColour = m_emptyColour;
break;
case ResourceLevel.Low:
m_currentColour = m_lowColour;
break;
case ResourceLevel.Medium:
m_currentColour = m_mediumColour;
break;
case ResourceLevel.High:
m_currentColour = m_highColour;
break;
case ResourceLevel.Full:
m_currentColour = m_fullColour;// (m_normalColour + m_fullColour) / 2.0f;
break;
default:
m_currentColour = m_normalColour;
break;
}
m_meshRenderer.material.color = m_currentColour;
}
public bool IsExtracted()
{
return m_hasBeenExtracted;
}
public void Extract()
{
m_hasBeenExtracted = true;
}
/// <summary>
/// Get the grid the tile is part of
/// </summary>
/// <returns>Main grid if it exists</returns>
public Grid GetGrid()
{
if(GetComponentInParent<Grid>() != null)
{
return GetComponentInParent<Grid>();
}
else
{
Debug.LogWarning("No grid attached.");
return null;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
#if !BUILDTASKS_CORE
using System.ComponentModel.Composition.Hosting;
#endif
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
namespace Microsoft.PythonTools.BuildTasks {
/// <summary>
/// Resolves a project's active environment from the contents of the project
/// file.
/// </summary>
public sealed class ResolveEnvironment : ITask {
private readonly string _projectPath;
internal readonly TaskLoggingHelper _log;
internal ResolveEnvironment(string projectPath, IBuildEngine buildEngine) {
BuildEngine = buildEngine;
_projectPath = projectPath;
_log = new TaskLoggingHelper(this);
}
#if !BUILDTASKS_CORE
class CatalogLog : ICatalogLog {
private readonly TaskLoggingHelper _helper;
public CatalogLog(TaskLoggingHelper helper) {
_helper = helper;
}
public void Log(string msg) {
_helper.LogWarning(msg);
}
}
#endif
/// <summary>
/// The interpreter ID to resolve.
/// </summary>
public string InterpreterId { get; set; }
[Output]
public string PrefixPath { get; private set; }
[Output]
public string ProjectRelativePrefixPath { get; private set; }
[Output]
public string InterpreterPath { get; private set; }
[Output]
public string WindowsInterpreterPath { get; private set; }
[Output]
public string Architecture { get; private set; }
[Output]
public string PathEnvironmentVariable { get; private set; }
[Output]
public string Description { get; private set; }
[Output]
public string MajorVersion { get; private set; }
[Output]
public string MinorVersion { get; private set; }
internal string[] SearchPaths { get; private set; }
public bool Execute() {
string id = InterpreterId;
ProjectCollection collection = null;
Project project = null;
#if !BUILDTASKS_CORE
var exports = GetExportProvider();
if (exports == null) {
_log.LogError("Unable to obtain interpreter service.");
return false;
}
#endif
try {
try {
project = ProjectCollection.GlobalProjectCollection.GetLoadedProjects(_projectPath).Single();
} catch (InvalidOperationException) {
// Could not get exactly one project matching the path.
}
if (project == null) {
collection = new ProjectCollection();
project = collection.LoadProject(_projectPath);
}
if (id == null) {
id = project.GetPropertyValue("InterpreterId");
if (String.IsNullOrWhiteSpace(id)) {
#if !BUILDTASKS_CORE
var options = exports.GetExportedValueOrDefault<IInterpreterOptionsService>();
if (options != null) {
id = options.DefaultInterpreterId;
}
#endif
}
}
var projectHome = PathUtils.GetAbsoluteDirectoryPath(
project.DirectoryPath,
project.GetPropertyValue("ProjectHome")
);
var searchPath = project.GetPropertyValue("SearchPath");
if (!string.IsNullOrEmpty(searchPath)) {
SearchPaths = searchPath.Split(';')
.Select(p => PathUtils.GetAbsoluteFilePath(projectHome, p))
.ToArray();
} else {
SearchPaths = new string[0];
}
#if BUILDTASKS_CORE
ProjectItem item = null;
InterpreterConfiguration config = null;
if (string.IsNullOrEmpty(id)) {
id = project.GetItems(MSBuildConstants.InterpreterReferenceItem).Select(pi => pi.GetMetadataValue(MSBuildConstants.IdKey)).LastOrDefault(i => !string.IsNullOrEmpty(i));
}
if (string.IsNullOrEmpty(id)) {
item = project.GetItems(MSBuildConstants.InterpreterItem).FirstOrDefault();
if (item == null) {
var found = PythonRegistrySearch.PerformDefaultSearch().OrderByDescending(i => i.Configuration.Version).ToArray();
config = (
found.Where(i => CPythonInterpreterFactoryConstants.TryParseInterpreterId(i.Configuration.Id, out var co, out _) &&
PythonRegistrySearch.PythonCoreCompany.Equals(co, StringComparison.OrdinalIgnoreCase)).FirstOrDefault()
?? found.FirstOrDefault()
)?.Configuration;
}
} else {
// Special case MSBuild environments
var m = Regex.Match(id, @"MSBuild\|(?<id>.+?)\|(?<moniker>.+)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
if (m.Success && m.Groups["id"].Success) {
var subId = m.Groups["id"].Value;
item = project.GetItems(MSBuildConstants.InterpreterItem)
.FirstOrDefault(pi => subId.Equals(pi.GetMetadataValue(MSBuildConstants.IdKey), StringComparison.OrdinalIgnoreCase));
}
if (item == null) {
config = PythonRegistrySearch.PerformDefaultSearch()
.FirstOrDefault(pi => id.Equals(pi.Configuration.Id, StringComparison.OrdinalIgnoreCase))?.Configuration;
}
}
if (item != null) {
PrefixPath = PathUtils.GetAbsoluteDirectoryPath(projectHome, item.EvaluatedInclude);
if (PathUtils.IsSubpathOf(projectHome, PrefixPath)) {
ProjectRelativePrefixPath = PathUtils.GetRelativeDirectoryPath(projectHome, PrefixPath);
} else {
ProjectRelativePrefixPath = string.Empty;
}
InterpreterPath = PathUtils.GetAbsoluteFilePath(PrefixPath, item.GetMetadataValue(MSBuildConstants.InterpreterPathKey));
WindowsInterpreterPath = PathUtils.GetAbsoluteFilePath(PrefixPath, item.GetMetadataValue(MSBuildConstants.WindowsPathKey));
Architecture = InterpreterArchitecture.TryParse(item.GetMetadataValue(MSBuildConstants.ArchitectureKey)).ToString("X");
PathEnvironmentVariable = item.GetMetadataValue(MSBuildConstants.PathEnvVarKey).IfNullOrEmpty("PYTHONPATH");
Description = item.GetMetadataValue(MSBuildConstants.DescriptionKey).IfNullOrEmpty(PathUtils.CreateFriendlyDirectoryPath(projectHome, PrefixPath));
Version ver;
if (Version.TryParse(item.GetMetadataValue(MSBuildConstants.VersionKey) ?? "", out ver)) {
MajorVersion = ver.Major.ToString();
MinorVersion = ver.Minor.ToString();
} else {
MajorVersion = MinorVersion = "0";
}
return true;
} else if (config != null) {
UpdateResultFromConfiguration(config, projectHome);
return true;
}
#else
// MsBuildProjectContextProvider isn't available in-proc, instead we rely upon the
// already loaded VsProjectContextProvider which is loaded in proc and already
// aware of the projects loaded in Solution Explorer.
var projectContext = exports.GetExportedValueOrDefault<MsBuildProjectContextProvider>();
if (projectContext != null) {
projectContext.AddContext(project);
}
try {
var config = exports.GetExportedValue<IInterpreterRegistryService>().FindConfiguration(id);
if (config != null) {
UpdateResultFromConfiguration(config, projectHome);
return true;
}
} finally {
if (projectContext != null) {
projectContext.RemoveContext(project);
}
}
#endif
if (!string.IsNullOrEmpty(id)) {
_log.LogError(
"The environment '{0}' is not available. Check your project configuration and try again.",
id
);
return false;
}
} catch (Exception ex) {
_log.LogErrorFromException(ex);
} finally {
if (collection != null) {
collection.UnloadAllProjects();
collection.Dispose();
}
}
_log.LogError("Unable to resolve environment");
return false;
}
public IBuildEngine BuildEngine { get; set; }
public ITaskHost HostObject { get; set; }
private void UpdateResultFromConfiguration(InterpreterConfiguration config, string projectHome) {
PrefixPath = PathUtils.EnsureEndSeparator(config.GetPrefixPath());
if (PathUtils.IsSubpathOf(projectHome, PrefixPath)) {
ProjectRelativePrefixPath = PathUtils.GetRelativeDirectoryPath(projectHome, PrefixPath);
} else {
ProjectRelativePrefixPath = string.Empty;
}
InterpreterPath = config.InterpreterPath;
WindowsInterpreterPath = config.GetWindowsInterpreterPath();
Architecture = config.Architecture.ToString("X");
PathEnvironmentVariable = config.PathEnvironmentVariable;
Description = config.Description;
MajorVersion = config.Version.Major.ToString();
MinorVersion = config.Version.Minor.ToString();
}
#if !BUILDTASKS_CORE
private ExportProvider GetExportProvider() {
return InterpreterCatalog.CreateContainer(
new CatalogLog(_log),
typeof(MsBuildProjectContextProvider),
typeof(IInterpreterRegistryService),
typeof(IInterpreterOptionsService)
);
}
#endif
}
/// <summary>
/// Constructs ResolveEnvironment task objects.
/// </summary>
public sealed class ResolveEnvironmentFactory : TaskFactory<ResolveEnvironment> {
public override ITask CreateTask(IBuildEngine taskFactoryLoggingHost) {
return new ResolveEnvironment(Properties["ProjectPath"], taskFactoryLoggingHost);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.Api.ImageEditing;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
public class ImageEditingPropertySidebar : Panel, IImagePropertyEditingContext
{
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = new Container();
private IHtmlEditorComponentContext _editorContext ;
private IBlogPostImageDataContext _imageDataContext;
private ImageEditingPropertyTitlebar imageEditingPropertyTitlebar;
private ImagePropertyEditorControl imagePropertyEditorControl;
private ImageEditingPropertyStatusbar imageEditingPropertyStatusbar;
private CreateFileCallback _createFileCallback ;
#region Initialization/Singleton
public static void Initialize(IHtmlEditorComponentContext editorContext, IBlogPostImageDataContext dataContext, CreateFileCallback callback)
{
// initialize one form per-thread
if ( _imagePropertySidebar == null )
{
_imagePropertySidebar = new ImageEditingPropertySidebar() ;
_imagePropertySidebar.Init(editorContext, dataContext, callback);
}
}
public static ImageEditingPropertySidebar Instance
{
get
{
return _imagePropertySidebar ;
}
}
[ThreadStatic]
private static ImageEditingPropertySidebar _imagePropertySidebar ;
public ImageEditingPropertySidebar()
{
InitializeDockPadding() ;
InitializeControls();
AdjustLayoutForLargeFonts() ;
}
private void InitializeControls()
{
SuspendLayout() ;
Size = new Size(236, 400) ;
imageEditingPropertyTitlebar = new ImageEditingPropertyTitlebar();
imageEditingPropertyTitlebar.Dock = DockStyle.Top;
imageEditingPropertyTitlebar.TabIndex = 0;
imageEditingPropertyTitlebar.TabStop = false;
imageEditingPropertyTitlebar.HideTitleBarClicked +=new EventHandler(imageEditingPropertyTitlebar_HideTitleBarClicked);
imagePropertyEditorControl = new ImagePropertyEditorControl();
imagePropertyEditorControl.AllowDragDropAutoScroll = false;
imagePropertyEditorControl.AllPaintingInWmPaint = true;
imagePropertyEditorControl.Dock = DockStyle.Fill ;
imagePropertyEditorControl.ImageInfo = null;
imagePropertyEditorControl.Location = new Point(0, 25);
imagePropertyEditorControl.Size = new Size(236, 335);
imagePropertyEditorControl.TabIndex = 1;
imagePropertyEditorControl.TopLayoutMargin = 2;
imageEditingPropertyStatusbar = new ImageEditingPropertyStatusbar();
imageEditingPropertyStatusbar.Dock = DockStyle.Bottom;
imageEditingPropertyStatusbar.Size = new Size(236, 24);
imageEditingPropertyStatusbar.TabIndex = 2;
imageEditingPropertyStatusbar.TabStop = false;
Controls.Add(imagePropertyEditorControl);
Controls.Add(imageEditingPropertyTitlebar);
Controls.Add(imageEditingPropertyStatusbar);
ResumeLayout(false);
}
#endregion
#region Public Interface
/// <summary>
/// Make the form visible / update its appearance based on current selection
/// </summary>
public void ShowSidebar()
{
// refresh the view
RefreshImage();
// manage UI
ManageVisibilityOfEditingUI() ;
if ( !Visible )
{
// show the form
Show() ;
}
}
private void _editorContext_SelectionChanged(object sender, EventArgs e)
{
RefreshImage();
// manage UI
ManageVisibilityOfEditingUI() ;
}
private void ManageVisibilityOfEditingUI()
{
// show/hide property UI as appropriate
SuspendLayout() ;
imagePropertyEditorControl.Visible = SelectionIsImage ;
imageEditingPropertyStatusbar.Visible = SelectionIsImage ;
ResumeLayout(true) ;
}
public void HideSidebar()
{
Visible = false ;
}
private void imageEditingPropertyTitlebar_HideTitleBarClicked(object sender, EventArgs e)
{
HideSidebar() ;
}
#endregion
private void Init(IHtmlEditorComponentContext editorContext, IBlogPostImageDataContext dataContext, CreateFileCallback callback)
{
_editorContext = editorContext ;
_editorContext.SelectionChanged +=new EventHandler(_editorContext_SelectionChanged);
_imageDataContext = dataContext;
_createFileCallback = callback ;
this.imagePropertyEditorControl.Init(dataContext);
}
private ImageEditingTabPageControl[] TabPages
{
get
{
return this.imagePropertyEditorControl.TabPages;
}
}
IHTMLImgElement IImagePropertyEditingContext.SelectedImage
{
get { return _selectedImage; }
}
private IHTMLImgElement _selectedImage ;
private bool SelectionIsImage
{
get
{
return _selectedImage != null ;
}
}
private ImageEditingPropertyHandler ImagePropertyHandler
{
get
{
if (_imagePropertyHandler == null)
{
Debug.Assert(_selectedImage != null, "No image selected!");
_imagePropertyHandler = new ImageEditingPropertyHandler(
this, _createFileCallback, _imageDataContext );
}
return _imagePropertyHandler ;
}
}
private ImageEditingPropertyHandler _imagePropertyHandler ;
public ImagePropertiesInfo ImagePropertiesInfo
{
get
{
return _imageInfo;
}
set
{
_imageInfo = value;
//unsubscribe from change event while the image info is being updated.
foreach(ImageEditingTabPageControl tabPage in TabPages)
tabPage.ImagePropertyChanged -= new ImagePropertyEventHandler(tabPage_ImagePropertyChanged);
imagePropertyEditorControl.ImagePropertyChanged -= new ImagePropertyEventHandler(tabPage_ImagePropertyChanged);
ManageCommands();
foreach(ImageEditingTabPageControl tabPage in TabPages)
tabPage.ImageInfo = _imageInfo;
imagePropertyEditorControl.ImageInfo = _imageInfo;
//re-subscribe to change events so they can be rebroadcast
foreach(ImageEditingTabPageControl tabPage in TabPages)
tabPage.ImagePropertyChanged += new ImagePropertyEventHandler(tabPage_ImagePropertyChanged);
imagePropertyEditorControl.ImagePropertyChanged += new ImagePropertyEventHandler(tabPage_ImagePropertyChanged);
imageEditingPropertyStatusbar.SetImageStatus(_imageInfo.ImageSourceUri.ToString(),
_imageInfo.ImageSourceUri.IsFile ? ImageEditingPropertyStatusbar.IMAGE_TYPE.LOCAL_IMAGE :
ImageEditingPropertyStatusbar.IMAGE_TYPE.WEB_IMAGE
);
}
}
private ImagePropertiesInfo _imageInfo;
/// <summary>
/// Manages the commands assocatiated with image editing.
/// </summary>
private void ManageCommands()
{
if(_imageDataContext != null)
{
for(int i=0; i<_imageDataContext.DecoratorsManager.ImageDecoratorGroups.Length; i++)
{
ImageDecoratorGroup imageDecoratorGroup = _imageDataContext.DecoratorsManager.ImageDecoratorGroups[i];
foreach(ImageDecorator imageDecorator in imageDecoratorGroup.ImageDecorators)
{
if(_imageInfo == null || _imageInfo.ImageSourceUri.IsFile || imageDecorator.IsWebImageSupported)
imageDecorator.Command.Enabled = true;
else
imageDecorator.Command.Enabled = false;
}
}
}
}
/// <summary>
/// Forces a reload of the image's properties. This is useful for refreshing the form when the image
/// properties have been changed externally.
/// </summary>
private void RefreshImage()
{
// update selected image (null if none is selected)
_selectedImage = _editorContext.SelectedImage ;
// refresh the view
if ( SelectionIsImage )
ImagePropertyHandler.RefreshView();
}
public event EventHandler SaveDefaultsRequested
{
add
{
imagePropertyEditorControl.SaveDefaultsRequested += value;
}
remove
{
imagePropertyEditorControl.SaveDefaultsRequested -= value;
}
}
public event EventHandler ResetToDefaultsRequested
{
add
{
imagePropertyEditorControl.ResetToDefaultsRequested += value;
}
remove
{
imagePropertyEditorControl.ResetToDefaultsRequested -= value;
}
}
public event ImagePropertyEventHandler ImagePropertyChanged;
protected virtual void OnImagePropertyChanged(ImagePropertyEvent evt)
{
if(ImagePropertyChanged != null)
{
ImagePropertyChanged(this, evt);
}
//notify the tabs that the image properties have changed so that they can update themselves.
foreach(ImageEditingTabPageControl tabPage in TabPages)
{
tabPage.HandleImagePropertyChangedEvent(evt);
}
}
private void tabPage_ImagePropertyChanged(object source, ImagePropertyEvent evt)
{
OnImagePropertyChanged(evt);
}
public void UpdateInlineImageSize(Size newSize, ImageDecoratorInvocationSource invocationSource)
{
ImagePropertiesInfo imagePropertiesInfo = (this as IImagePropertyEditingContext).ImagePropertiesInfo ;
imagePropertiesInfo.InlineImageSize = newSize;
ImagePropertyChanged(this, new ImagePropertyEvent(ImagePropertyType.InlineSize, imagePropertiesInfo, invocationSource));
RefreshImage();
}
private const int TOP_INSET = 1 ;
private const int LEFT_INSET = 5 ;
private const int RIGHT_INSET = 1 ;
private const int BOTTOM_INSET = 1 ;
private void InitializeDockPadding()
{
DockPadding.Top = TOP_INSET ;
DockPadding.Left = LEFT_INSET ;
DockPadding.Right = RIGHT_INSET ;
DockPadding.Bottom = BOTTOM_INSET ;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
// draw the border
Rectangle borderRectangle = new Rectangle(
ClientRectangle.Left + LEFT_INSET - 1,
ClientRectangle.Top + TOP_INSET - 1,
ClientRectangle.Width - LEFT_INSET - RIGHT_INSET + 1,
ClientRectangle.Height - TOP_INSET - BOTTOM_INSET + 1) ;
using ( Pen pen = new Pen(ApplicationManager.ApplicationStyle.PrimaryWorkspaceCommandBarBottomBevelFirstLineColor) )
e.Graphics.DrawRectangle( pen, borderRectangle ) ;
// draw the no image selected message
Font textFont = ApplicationManager.ApplicationStyle.NormalApplicationFont ;
string noImageSelected = "No image selected" ;
SizeF textSize = e.Graphics.MeasureString(noImageSelected, textFont) ;
Color textColor = Color.FromArgb(200, ApplicationManager.ApplicationStyle.PrimaryWorkspaceCommandBarTextColor);
using ( Brush brush = new SolidBrush(textColor) )
e.Graphics.DrawString( "No image selected", textFont, brush, new PointF((Width/2)-(textSize.Width/2),100));
}
private void AdjustLayoutForLargeFonts()
{
// see if we need to adjust our width for non-standard DPI (large fonts)
const double DESIGNTIME_DPI = 96 ;
double dpiX = Convert.ToDouble(DisplayHelper.PixelsPerLogicalInchX) ;
if ( dpiX > DESIGNTIME_DPI )
{
// adjust scale ration for percentage of toolbar containing text
const double TEXT_PERCENT = 0.0 ; // currently has no text
double scaleRatio = (1-TEXT_PERCENT) + ((TEXT_PERCENT*dpiX)/DESIGNTIME_DPI) ;
// change width as appropriate
Width = Convert.ToInt32( Convert.ToDouble(Width) * scaleRatio ) ;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Security;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16805")]
public partial class HttpClientHandler_SslProtocols_Test : HttpClientTestBase
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
[Theory]
[InlineData(SslProtocols.None)]
[InlineData(SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server),
client.GetAsync(url));
});
Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(~SslProtocols.None)]
#pragma warning disable 0618 // obsolete warning
[InlineData(SslProtocols.Ssl2)]
[InlineData(SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
#pragma warning restore 0618
public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SslProtocols.Tls, false)]
[InlineData(SslProtocols.Tls, true)]
[InlineData(SslProtocols.Tls11, false)]
[InlineData(SslProtocols.Tls11, true)]
[InlineData(SslProtocols.Tls12, false)]
[InlineData(SslProtocols.Tls12, true)]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
if (!BackendSupportsSslConfiguration)
{
return;
}
if (UseManagedHandler)
{
// TODO #23138: The managed handler is failing.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
}
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
public static readonly object [][] SupportedSSLVersionServers =
{
new object[] {SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer},
new object[] {SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer},
new object[] {SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer},
};
// This test is logically the same as the above test, albeit using remote servers
// instead of local ones. We're keeping it for now (as outerloop) because it helps
// to validate against another SSL implementation that what we mean by a particular
// TLS version matches that other implementation.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
if (UseManagedHandler)
{
// TODO #23138: The managed handler is failing.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
{
if (PlatformDetection.IsRedHatFamily7)
{
// Default protocol selection is always TLSv1 on Centos7 libcurl 7.29.0
// Hence, set the specific protocol on HttpClient that is required by test
handler.SslProtocols = sslProtocols;
}
using (var client = new HttpClient(handler))
{
(await client.GetAsync(url)).Dispose();
}
}
}
public static readonly object[][] NotSupportedSSLVersionServers =
{
new object[] {"SSLv2", Configuration.Http.SSLv2RemoteServer},
new object[] {"SSLv3", Configuration.Http.SSLv3RemoteServer},
};
// It would be easy to remove the dependency on these remote servers if we didn't
// explicitly disallow creating SslStream with SSLv2/3. Since we explicitly throw
// when trying to use such an SslStream, we can't stand up a localhost server that
// only speaks those protocols.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
if (!SSLv3DisabledByDefault)
{
return;
}
if (UseManagedHandler && !PlatformDetection.IsWindows10Version1607OrGreater)
{
// On Windows, https://github.com/dotnet/corefx/issues/21925#issuecomment-313408314
// On Linux, an older version of OpenSSL may permit negotiating SSLv3.
return;
}
using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(SslDefaultsToTls12))]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
if (!BackendSupportsSslConfiguration) return;
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetAsync(url),
LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(stream).SslProtocol);
await LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
return null;
}, options));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))]
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))]
public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException(
SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException)
{
if (!BackendSupportsSslConfiguration) return;
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = allowedProtocol;
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync(exceptedServerException, () => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(8538, TestPlatforms.Windows)]
[Fact]
public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12;
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
if (BackendSupportsSslConfiguration)
{
LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true };
options.SslProtocols = SslProtocols.Tls;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync<IOException>(() => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
foreach (var prot in new[] { SslProtocols.Tls11, SslProtocols.Tls12 })
{
options.SslProtocols = prot;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
else
{
await Assert.ThrowsAnyAsync<NotSupportedException>(() => client.GetAsync($"http://{Guid.NewGuid().ToString()}/"));
}
}
}
private static bool SslDefaultsToTls12 => !PlatformDetection.IsWindows7;
// TLS 1.2 may not be enabled on Win7
// https://technet.microsoft.com/en-us/library/dn786418.aspx#BKMK_SchannelTR_TLS12
}
}
| |
using System;
using NUnit.Framework;
using StructureMap.Configuration.DSL;
using StructureMap.Diagnostics;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.Testing.Configuration.DSL;
using StructureMap.Testing.Widget;
namespace StructureMap.Testing.Diagnostics
{
[TestFixture]
public class ValidationBuildSessionTester : Registry
{
private ValidationBuildSession validatedSession(Action<Registry> action)
{
var registry = new Registry();
action(registry);
PluginGraph graph = registry.Build();
var session = new ValidationBuildSession(graph);
session.PerformValidations();
return session;
}
private BuildError getFirstAndOnlyError(ValidationBuildSession session)
{
Assert.AreEqual(1, session.BuildErrors.Length);
return session.BuildErrors[0];
}
private LambdaInstance<IWidget> errorInstance()
{
return
new LambdaInstance<IWidget>(delegate() { throw new NotSupportedException("You can't make me!"); });
}
[Test]
public void Attach_dependency_to_the_build_error_but_do_not_create_new_error_for_dependency()
{
ValidationBuildSession session = validatedSession(r =>
{
r.InstanceOf<IWidget>().IsThis(errorInstance().WithName("BadInstance"));
r.InstanceOf<SomethingThatNeedsAWidget>().Is.OfConcreteType<SomethingThatNeedsAWidget>()
.WithName("DependentInstance")
.CtorDependency<IWidget>().Is(x => x.TheInstanceNamed("BadInstance"));
});
BuildError error = getFirstAndOnlyError(session);
Assert.AreEqual(1, error.Dependencies.Count);
BuildDependency dependency = error.Dependencies[0];
Assert.AreEqual(typeof (SomethingThatNeedsAWidget), dependency.PluginType);
Assert.AreEqual("DependentInstance", dependency.Instance.Name);
}
[Test]
public void Create_an_instance_for_the_first_time_happy_path()
{
ValidationBuildSession session =
validatedSession(
r => r.InstanceOf<IWidget>().Is.Object(new ColorWidget("Red")));
Assert.AreEqual(0, session.BuildErrors.Length);
}
[Test]
public void Create_an_instance_that_fails_and_an_instance_that_depends_on_that_exception()
{
ValidationBuildSession session = validatedSession(r =>
{
r.InstanceOf<IWidget>().IsThis(errorInstance().WithName("BadInstance"));
r.InstanceOf<SomethingThatNeedsAWidget>().Is.OfConcreteType<SomethingThatNeedsAWidget>()
.WithName("DependentInstance")
.CtorDependency<IWidget>().Is(x => x.TheInstanceNamed("BadInstance"));
});
Assert.AreEqual(1, session.BuildErrors.Length);
BuildError error = session.Find(typeof (SomethingThatNeedsAWidget), "DependentInstance");
Assert.IsNull(error);
BuildError error2 = session.Find(typeof (IWidget), "BadInstance");
Assert.IsNotNull(error2);
}
[Test]
public void Create_an_instance_that_fails_because_of_an_inline_child()
{
ValidationBuildSession session = validatedSession(
r =>
{
r.InstanceOf<SomethingThatNeedsAWidget>().Is.OfConcreteType<SomethingThatNeedsAWidget>()
.WithName("BadInstance")
.CtorDependency<IWidget>().Is(errorInstance());
});
BuildError error = getFirstAndOnlyError(session);
Assert.AreEqual("BadInstance", error.Instance.Name);
Assert.AreEqual(typeof (SomethingThatNeedsAWidget), error.PluginType);
}
[Test]
public void Create_an_instance_that_has_a_build_failure()
{
Instance instance = errorInstance().WithName("Bad");
ValidationBuildSession session =
validatedSession(registry => registry.InstanceOf<IWidget>().IsThis(instance));
BuildError error = getFirstAndOnlyError(session);
Assert.AreEqual(instance, error.Instance);
Assert.AreEqual(typeof (IWidget), error.PluginType);
Assert.IsNotNull(error.Exception);
}
[Test]
public void do_not_fail_with_the_bidirectional_checks()
{
var container = new Container(r =>
{
r.For<IWidget>().Use<ColorWidget>().WithCtorArg("color").EqualTo("red");
r.For<Rule>().Use<WidgetRule>();
r.ForConcreteType<ClassThatNeedsWidgetAndRule1>();
r.ForConcreteType<ClassThatNeedsWidgetAndRule2>();
r.InstanceOf<ClassThatNeedsWidgetAndRule2>().Is.OfConcreteType<ClassThatNeedsWidgetAndRule2>();
r.InstanceOf<ClassThatNeedsWidgetAndRule2>().Is.OfConcreteType<ClassThatNeedsWidgetAndRule2>();
r.InstanceOf<ClassThatNeedsWidgetAndRule2>().Is.OfConcreteType<ClassThatNeedsWidgetAndRule2>();
r.InstanceOf<ClassThatNeedsWidgetAndRule2>().Is.OfConcreteType<ClassThatNeedsWidgetAndRule2>().
CtorDependency<Rule>().Is<ARule>();
});
container.AssertConfigurationIsValid();
}
[Test]
public void Happy_path_with_no_validation_errors()
{
ValidationBuildSession session =
validatedSession(
registry => registry.InstanceOf<IWidget>().Is.Object(new ColorWidget("Red")));
Assert.AreEqual(0, session.ValidationErrors.Length);
}
[Test]
public void Request_an_instance_for_the_second_time_successfully_and_get_the_same_object()
{
var session = new ValidationBuildSession(new PluginGraph());
var instance = new ObjectInstance(new ColorWidget("Red"));
object widget1 = session.CreateInstance(typeof (IWidget), instance);
object widget2 = session.CreateInstance(typeof (IWidget), instance);
Assert.AreSame(widget1, widget2);
}
[Test]
public void Successfully_build_an_object_that_has_multiple_validation_errors()
{
ValidationBuildSession session =
validatedSession(
registry =>
registry.BuildInstancesOf<SomethingThatHasValidationFailures>().TheDefaultIsConcreteType
<SomethingThatHasValidationFailures>());
Assert.AreEqual(2, session.ValidationErrors.Length);
}
[Test]
public void Validate_a_single_object_with_both_a_passing_validation_method_and_a_failing_validation_method()
{
var instance = new ObjectInstance(new WidgetWithOneValidationFailure());
ValidationBuildSession session =
validatedSession(registry => registry.InstanceOf<IWidget>().IsThis(instance));
Assert.AreEqual(1, session.ValidationErrors.Length);
ValidationError error = session.ValidationErrors[0];
Assert.AreEqual(typeof (IWidget), error.PluginType);
Assert.AreEqual(instance, error.Instance);
Assert.AreEqual("ValidateFailure", error.MethodName);
Assert.IsInstanceOfType(typeof (NotImplementedException), error.Exception);
}
}
public class ClassThatNeedsWidgetAndRule1
{
public ClassThatNeedsWidgetAndRule1(IWidget widget, Rule rule)
{
}
}
public class ClassThatNeedsWidgetAndRule2
{
public ClassThatNeedsWidgetAndRule2(IWidget widget, Rule rule, ClassThatNeedsWidgetAndRule1 class1)
{
}
}
public class WidgetWithOneValidationFailure : IWidget
{
#region IWidget Members
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
[ValidationMethod]
public void ValidateSuccess()
{
// everything is wonderful
}
[ValidationMethod]
public void ValidateFailure()
{
throw new NotImplementedException("I'm not ready");
}
}
public class SomethingThatHasValidationFailures
{
[ValidationMethod]
public void Validate1()
{
throw new NotSupportedException("You can't make me");
}
[ValidationMethod]
public void Validate2()
{
throw new NotImplementedException("Not ready yet");
}
}
public class SomethingThatNeedsAWidget
{
public SomethingThatNeedsAWidget(IWidget widget)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Text;
using System.Runtime.Serialization;
using System.Globalization;
namespace System.Xml
{
public delegate void OnXmlDictionaryReaderClose(XmlDictionaryReader reader);
public abstract class XmlDictionaryReader : XmlReader
{
internal const int MaxInitialArrayLength = 65535;
public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader)
{
if (reader == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader));
XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
if (dictionaryReader == null)
{
dictionaryReader = new XmlWrappedReader(reader, null);
}
return dictionaryReader;
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer));
return CreateBinaryReader(buffer, 0, buffer.Length, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
return CreateBinaryReader(buffer, offset, count, dictionary, quotas, session, onClose: null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(buffer, offset, count, dictionary, quotas, session, onClose);
return reader;
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
return CreateBinaryReader(stream, dictionary, quotas, session, onClose: null);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(stream, dictionary, quotas, session, onClose);
return reader;
}
public static XmlDictionaryReader CreateTextReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer));
return CreateTextReader(buffer, 0, buffer.Length, quotas);
}
public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateTextReader(buffer, offset, count, null, quotas, null);
}
public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count,
Encoding encoding,
XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose)
{
XmlUTF8TextReader reader = new XmlUTF8TextReader();
reader.SetInput(buffer, offset, count, encoding, quotas, onClose);
return reader;
}
public static XmlDictionaryReader CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateTextReader(stream, null, quotas, null);
}
public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding encoding,
XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose)
{
XmlUTF8TextReader reader = new XmlUTF8TextReader();
reader.SetInput(stream, encoding, quotas, onClose);
return reader;
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas)
{
if (encoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(encoding));
return CreateMtomReader(stream, new Encoding[1] { encoding }, quotas);
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(stream, encodings, null, quotas);
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(stream, encodings, contentType, quotas, int.MaxValue, null);
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType,
XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas)
{
if (encoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(encoding));
return CreateMtomReader(buffer, offset, count, new Encoding[1] { encoding }, quotas);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(buffer, offset, count, encodings, null, quotas);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(buffer, offset, count, encodings, contentType, quotas, int.MaxValue, null);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType,
XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
}
public virtual bool CanCanonicalize
{
get
{
return false;
}
}
public virtual XmlDictionaryReaderQuotas Quotas
{
get
{
return XmlDictionaryReaderQuotas.Max;
}
}
public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void MoveToStartElement()
{
if (!IsStartElement())
XmlExceptionHelper.ThrowStartElementExpected(this);
}
public virtual void MoveToStartElement(string name)
{
if (!IsStartElement(name))
XmlExceptionHelper.ThrowStartElementExpected(this, name);
}
public virtual void MoveToStartElement(string localName, string namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual void MoveToStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual bool IsLocalName(string localName)
{
return this.LocalName == localName;
}
public virtual bool IsLocalName(XmlDictionaryString localName)
{
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName));
return IsLocalName(localName.Value);
}
public virtual bool IsNamespaceUri(string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
return this.NamespaceURI == namespaceUri;
}
public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
return IsNamespaceUri(namespaceUri.Value);
}
public virtual void ReadFullStartElement()
{
MoveToStartElement();
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this);
Read();
}
public virtual void ReadFullStartElement(string name)
{
MoveToStartElement(name);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, name);
Read();
}
public virtual void ReadFullStartElement(string localName, string namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadFullStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
Read();
}
public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return IsStartElement(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual int IndexOfLocalName(string[] localNames, string namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames));
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
if (this.NamespaceURI == namespaceUri)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
string value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value)
{
return i;
}
}
}
return -1;
}
public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames));
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
if (this.NamespaceURI == namespaceUri.Value)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
XmlDictionaryString value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value.Value)
{
return i;
}
}
}
return -1;
}
public virtual string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual bool TryGetBase64ContentLength(out int length)
{
length = 0;
return false;
}
public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual byte[] ReadContentAsBase64()
{
return ReadContentAsBase64(Quotas.MaxArrayLength, MaxInitialArrayLength);
}
internal byte[] ReadContentAsBase64(int maxByteArrayContentLength, int maxInitialCount)
{
int length;
if (TryGetBase64ContentLength(out length))
{
if (length <= maxInitialCount)
{
byte[] buffer = new byte[length];
int read = 0;
while (read < length)
{
int actual = ReadContentAsBase64(buffer, read, length - read);
if (actual == 0)
XmlExceptionHelper.ThrowBase64DataExpected(this);
read += actual;
}
return buffer;
}
}
return ReadContentAsBytes(true, maxByteArrayContentLength);
}
public override string ReadContentAsString()
{
return ReadContentAsString(Quotas.MaxStringContentLength);
}
protected string ReadContentAsString(int maxStringContentLength)
{
StringBuilder sb = null;
string result = string.Empty;
bool done = false;
while (true)
{
switch (this.NodeType)
{
case XmlNodeType.Attribute:
result = this.Value;
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
// merge text content
string value = this.Value;
if (result.Length == 0)
{
result = value;
}
else
{
if (sb == null)
sb = new StringBuilder(result);
sb.Append(value);
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (this.CanResolveEntity)
{
this.ResolveEntity();
break;
}
goto default;
case XmlNodeType.Element:
case XmlNodeType.EndElement:
default:
done = true;
break;
}
if (done)
break;
if (this.AttributeCount != 0)
ReadAttributeValue();
else
Read();
}
if (sb != null)
result = sb.ToString();
return result;
}
public override string ReadString()
{
return ReadString(Quotas.MaxStringContentLength);
}
protected string ReadString(int maxStringContentLength)
{
if (this.ReadState != ReadState.Interactive)
return string.Empty;
if (this.NodeType != XmlNodeType.Element)
MoveToElement();
if (this.NodeType == XmlNodeType.Element)
{
if (this.IsEmptyElement)
return string.Empty;
if (!Read())
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidOperation)));
if (this.NodeType == XmlNodeType.EndElement)
return string.Empty;
}
StringBuilder sb = null;
string result = string.Empty;
while (IsTextNode(this.NodeType))
{
string value = this.Value;
if (result.Length == 0)
{
result = value;
}
else
{
if (sb == null)
sb = new StringBuilder(result);
if (sb.Length > maxStringContentLength - value.Length)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
sb.Append(value);
}
if (!Read())
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidOperation)));
}
if (sb != null)
result = sb.ToString();
if (result.Length > maxStringContentLength)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
return result;
}
public virtual byte[] ReadContentAsBinHex()
{
return ReadContentAsBinHex(Quotas.MaxArrayLength);
}
protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength)
{
return ReadContentAsBytes(false, maxByteArrayContentLength);
}
private byte[] ReadContentAsBytes(bool base64, int maxByteArrayContentLength)
{
byte[][] buffers = new byte[32][];
byte[] buffer;
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
int count = 384;
int bufferCount = 0;
int totalRead = 0;
while (true)
{
buffer = new byte[count];
buffers[bufferCount++] = buffer;
int read = 0;
while (read < buffer.Length)
{
int actual;
if (base64)
actual = ReadContentAsBase64(buffer, read, buffer.Length - read);
else
actual = ReadContentAsBinHex(buffer, read, buffer.Length - read);
if (actual == 0)
break;
read += actual;
}
totalRead += read;
if (read < buffer.Length)
break;
count = count * 2;
}
buffer = new byte[totalRead];
int offset = 0;
for (int i = 0; i < bufferCount - 1; i++)
{
Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length);
offset += buffers[i].Length;
}
Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset);
return buffer;
}
protected bool IsTextNode(XmlNodeType nodeType)
{
return nodeType == XmlNodeType.Text ||
nodeType == XmlNodeType.Whitespace ||
nodeType == XmlNodeType.SignificantWhitespace ||
nodeType == XmlNodeType.CDATA ||
nodeType == XmlNodeType.Attribute;
}
public virtual int ReadContentAsChars(char[] chars, int offset, int count)
{
int read = 0;
while (true)
{
XmlNodeType nodeType = this.NodeType;
if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement)
break;
if (IsTextNode(nodeType))
{
read = ReadValueChunk(chars, offset, count);
if (read > 0)
break;
if (nodeType == XmlNodeType.Attribute /* || inAttributeText */)
break;
if (!Read())
break;
}
else
{
if (!Read())
break;
}
}
return read;
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
if (type == typeof(Guid[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
Guid[] guids = new Guid[values.Length];
for (int i = 0; i < values.Length; i++)
guids[i] = XmlConverter.ToGuid(values[i]);
return guids;
}
if (type == typeof(UniqueId[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
UniqueId[] uniqueIds = new UniqueId[values.Length];
for (int i = 0; i < values.Length; i++)
uniqueIds[i] = XmlConverter.ToUniqueId(values[i]);
return uniqueIds;
}
return base.ReadContentAs(type, namespaceResolver);
}
public virtual string ReadContentAsString(string[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(strings));
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
string value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value == s)
{
index = i;
return value;
}
}
return s;
}
public virtual string ReadContentAsString(XmlDictionaryString[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(strings));
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
XmlDictionaryString value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value.Value == s)
{
index = i;
return value.Value;
}
}
return s;
}
public override decimal ReadContentAsDecimal()
{
return XmlConverter.ToDecimal(ReadContentAsString());
}
public override Single ReadContentAsFloat()
{
return XmlConverter.ToSingle(ReadContentAsString());
}
public virtual UniqueId ReadContentAsUniqueId()
{
return XmlConverter.ToUniqueId(ReadContentAsString());
}
public virtual Guid ReadContentAsGuid()
{
return XmlConverter.ToGuid(ReadContentAsString());
}
public virtual TimeSpan ReadContentAsTimeSpan()
{
return XmlConverter.ToTimeSpan(ReadContentAsString());
}
public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri)
{
string prefix;
XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName);
namespaceUri = LookupNamespace(prefix);
if (namespaceUri == null)
XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix);
}
/* string, bool, int, long, float, double, decimal, DateTime, base64, binhex, uniqueID, object, list*/
public override string ReadElementContentAsString()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
string value;
if (isEmptyElement)
{
Read();
value = string.Empty;
}
else
{
ReadStartElement();
value = ReadContentAsString();
ReadEndElement();
}
return value;
}
public override bool ReadElementContentAsBoolean()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
bool value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToBoolean(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsBoolean();
ReadEndElement();
}
return value;
}
public override int ReadElementContentAsInt()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
int value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt32(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsInt();
ReadEndElement();
}
return value;
}
public override long ReadElementContentAsLong()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
long value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt64(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsLong();
ReadEndElement();
}
return value;
}
public override float ReadElementContentAsFloat()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
float value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToSingle(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsFloat();
ReadEndElement();
}
return value;
}
public override double ReadElementContentAsDouble()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
double value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDouble(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDouble();
ReadEndElement();
}
return value;
}
public override decimal ReadElementContentAsDecimal()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
decimal value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDecimal(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDecimal();
ReadEndElement();
}
return value;
}
public override DateTime ReadElementContentAsDateTime()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
DateTime value;
if (isEmptyElement)
{
Read();
try
{
value = DateTime.Parse(string.Empty, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsDateTimeOffset().DateTime;
ReadEndElement();
}
return value;
}
public virtual UniqueId ReadElementContentAsUniqueId()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
UniqueId value;
if (isEmptyElement)
{
Read();
try
{
value = new UniqueId(string.Empty);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsUniqueId();
ReadEndElement();
}
return value;
}
public virtual Guid ReadElementContentAsGuid()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
Guid value;
if (isEmptyElement)
{
Read();
try
{
value = new Guid(string.Empty);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsGuid();
ReadEndElement();
}
return value;
}
public virtual TimeSpan ReadElementContentAsTimeSpan()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
TimeSpan value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToTimeSpan(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsTimeSpan();
ReadEndElement();
}
return value;
}
public virtual byte[] ReadElementContentAsBase64()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = Array.Empty<byte>();
}
else
{
ReadStartElement();
buffer = ReadContentAsBase64();
ReadEndElement();
}
return buffer;
}
public virtual byte[] ReadElementContentAsBinHex()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = Array.Empty<byte>();
}
else
{
ReadStartElement();
buffer = ReadContentAsBinHex();
ReadEndElement();
}
return buffer;
}
public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri)
{
localName = LocalName;
namespaceUri = NamespaceURI;
}
public virtual bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
{
localName = null;
return false;
}
public virtual bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString namespaceUri)
{
namespaceUri = null;
return false;
}
public virtual bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
{
value = null;
return false;
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
public virtual bool IsStartArray(out Type type)
{
type = null;
return false;
}
public virtual bool TryGetArrayLength(out int count)
{
count = 0;
return false;
}
// Boolean
public virtual bool[] ReadBooleanArray(string localName, string namespaceUri)
{
return BooleanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual bool[] ReadBooleanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return BooleanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsBoolean();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int16
public virtual Int16[] ReadInt16Array(string localName, string namespaceUri)
{
return Int16ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int16[] ReadInt16Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int16ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int16[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
int i = ReadElementContentAsInt();
if (i < Int16.MinValue || i > Int16.MaxValue)
XmlExceptionHelper.ThrowConversionOverflow(this, i.ToString(NumberFormatInfo.CurrentInfo), "Int16");
array[offset + actual] = (Int16)i;
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int32
public virtual Int32[] ReadInt32Array(string localName, string namespaceUri)
{
return Int32ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int32[] ReadInt32Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int32ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int32[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsInt();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int64
public virtual Int64[] ReadInt64Array(string localName, string namespaceUri)
{
return Int64ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Int64[] ReadInt64Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int64ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Int64[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsLong();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Single
public virtual float[] ReadSingleArray(string localName, string namespaceUri)
{
return SingleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual float[] ReadSingleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return SingleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsFloat();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Double
public virtual double[] ReadDoubleArray(string localName, string namespaceUri)
{
return DoubleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual double[] ReadDoubleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DoubleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDouble();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Decimal
public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri)
{
return DecimalArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual decimal[] ReadDecimalArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DecimalArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDecimal();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// DateTime
public virtual DateTime[] ReadDateTimeArray(string localName, string namespaceUri)
{
return DateTimeArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual DateTime[] ReadDateTimeArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDateTime();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Guid
public virtual Guid[] ReadGuidArray(string localName, string namespaceUri)
{
return GuidArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Guid[] ReadGuidArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GuidArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsGuid();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// TimeSpan
public virtual TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri)
{
return TimeSpanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual TimeSpan[] ReadTimeSpanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return TimeSpanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsTimeSpan();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
public override void Close()
{
base.Dispose();
}
private class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo
{
private XmlReader _reader;
private XmlNamespaceManager _nsMgr;
public XmlWrappedReader(XmlReader reader, XmlNamespaceManager nsMgr)
{
_reader = reader;
_nsMgr = nsMgr;
}
public override int AttributeCount
{
get
{
return _reader.AttributeCount;
}
}
public override string BaseURI
{
get
{
return _reader.BaseURI;
}
}
public override bool CanReadBinaryContent
{
get { return _reader.CanReadBinaryContent; }
}
public override bool CanReadValueChunk
{
get { return _reader.CanReadValueChunk; }
}
public override void Close()
{
_reader.Dispose();
_nsMgr = null;
}
public override int Depth
{
get
{
return _reader.Depth;
}
}
public override bool EOF
{
get
{
return _reader.EOF;
}
}
public override string GetAttribute(int index)
{
return _reader.GetAttribute(index);
}
public override string GetAttribute(string name)
{
return _reader.GetAttribute(name);
}
public override string GetAttribute(string name, string namespaceUri)
{
return _reader.GetAttribute(name, namespaceUri);
}
public override bool HasValue
{
get
{
return _reader.HasValue;
}
}
public override bool IsDefault
{
get
{
return _reader.IsDefault;
}
}
public override bool IsEmptyElement
{
get
{
return _reader.IsEmptyElement;
}
}
public override bool IsStartElement(string name)
{
return _reader.IsStartElement(name);
}
public override bool IsStartElement(string localName, string namespaceUri)
{
return _reader.IsStartElement(localName, namespaceUri);
}
public override string LocalName
{
get
{
return _reader.LocalName;
}
}
public override string LookupNamespace(string namespaceUri)
{
return _reader.LookupNamespace(namespaceUri);
}
public override void MoveToAttribute(int index)
{
_reader.MoveToAttribute(index);
}
public override bool MoveToAttribute(string name)
{
return _reader.MoveToAttribute(name);
}
public override bool MoveToAttribute(string name, string namespaceUri)
{
return _reader.MoveToAttribute(name, namespaceUri);
}
public override bool MoveToElement()
{
return _reader.MoveToElement();
}
public override bool MoveToFirstAttribute()
{
return _reader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return _reader.MoveToNextAttribute();
}
public override string Name
{
get
{
return _reader.Name;
}
}
public override string NamespaceURI
{
get
{
return _reader.NamespaceURI;
}
}
public override XmlNameTable NameTable
{
get
{
return _reader.NameTable;
}
}
public override XmlNodeType NodeType
{
get
{
return _reader.NodeType;
}
}
public override string Prefix
{
get
{
return _reader.Prefix;
}
}
public override bool Read()
{
return _reader.Read();
}
public override bool ReadAttributeValue()
{
return _reader.ReadAttributeValue();
}
public override string ReadInnerXml()
{
return _reader.ReadInnerXml();
}
public override string ReadOuterXml()
{
return _reader.ReadOuterXml();
}
public override void ReadStartElement(string name)
{
_reader.ReadStartElement(name);
}
public override void ReadStartElement(string localName, string namespaceUri)
{
_reader.ReadStartElement(localName, namespaceUri);
}
public override void ReadEndElement()
{
_reader.ReadEndElement();
}
public override ReadState ReadState
{
get
{
return _reader.ReadState;
}
}
public override void ResolveEntity()
{
_reader.ResolveEntity();
}
public override string this[int index]
{
get
{
return _reader[index];
}
}
public override string this[string name]
{
get
{
return _reader[name];
}
}
public override string this[string name, string namespaceUri]
{
get
{
return _reader[name, namespaceUri];
}
}
public override string Value
{
get
{
return _reader.Value;
}
}
public override string XmlLang
{
get
{
return _reader.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return _reader.XmlSpace;
}
}
public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count)
{
return _reader.ReadElementContentAsBase64(buffer, offset, count);
}
public override int ReadContentAsBase64(byte[] buffer, int offset, int count)
{
return _reader.ReadContentAsBase64(buffer, offset, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count)
{
return _reader.ReadElementContentAsBinHex(buffer, offset, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int offset, int count)
{
return _reader.ReadContentAsBinHex(buffer, offset, count);
}
public override int ReadValueChunk(char[] chars, int offset, int count)
{
return _reader.ReadValueChunk(chars, offset, count);
}
public override Type ValueType
{
get
{
return _reader.ValueType;
}
}
public override Boolean ReadContentAsBoolean()
{
try
{
return _reader.ReadContentAsBoolean();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Boolean", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Boolean", exception));
}
}
public override DateTime ReadContentAsDateTime()
{
try
{
return _reader.ReadContentAsDateTimeOffset().DateTime;
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("DateTime", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("DateTime", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("DateTime", exception));
}
}
public override Decimal ReadContentAsDecimal()
{
try
{
return (Decimal)_reader.ReadContentAs(typeof(Decimal), null);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
}
public override Double ReadContentAsDouble()
{
try
{
return _reader.ReadContentAsDouble();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
}
public override Int32 ReadContentAsInt()
{
try
{
return _reader.ReadContentAsInt();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
}
public override Int64 ReadContentAsLong()
{
try
{
return _reader.ReadContentAsLong();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
}
public override Single ReadContentAsFloat()
{
try
{
return _reader.ReadContentAsFloat();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
}
public override string ReadContentAsString()
{
try
{
return _reader.ReadContentAsString();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("String", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("String", exception));
}
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
return _reader.ReadContentAs(type, namespaceResolver);
}
public bool HasLineInfo()
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return false;
return lineInfo.HasLineInfo();
}
public int LineNumber
{
get
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LineNumber;
}
}
public int LinePosition
{
get
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LinePosition;
}
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.Drawing.Drawing2D;
namespace Revit.SDK.Samples.PathReinforcement.CS
{
/// <summary>
/// This class stores the geometry information of path reinforcement.
/// </summary>
class Profile
{
/// <summary>
/// field used to store path reinforcement.
/// </summary>
private Autodesk.Revit.DB.Structure.PathReinforcement m_pathRein;
/// <summary>
/// field used to store external command data.
/// </summary>
private Autodesk.Revit.UI.ExternalCommandData m_commandData;
/// <summary>
/// field used to store the geometry curves of path reinforcement.
/// 3d data.
/// </summary>
private List<List<XYZ>> m_curves = new List<List<XYZ>>();
/// <summary>
/// store path 3D.
/// </summary>
private List<List<XYZ>> m_path = new List<List<XYZ>>();
/// <summary>
/// field used to store the bound of the curves of path reinforcement.
/// 2d data.
/// </summary>
private BoundingBoxUV m_box = new BoundingBoxUV();
/// <summary>
/// field used to store the geometry data of curves of path reinforcement.
/// 2d data.
/// </summary>
private List<List<UV>> m_point2d = new List<List<UV>>();
/// <summary>
/// store path 2D.
/// </summary>
private List<List<UV>> m_path2d = new List<List<UV>>();
/// <summary>
/// Constructor
/// </summary>
/// <param name="pathRein">selected path reinforcement element.</param>
/// <param name="commandData">External command data</param>
public Profile(Autodesk.Revit.DB.Structure.PathReinforcement pathRein, ExternalCommandData commandData)
{
m_pathRein = pathRein;
m_commandData = commandData;
Tessellate();
ComputeBound();
ComputePathTo2D();
}
/// <summary>
/// Draw the curves of path reinforcement.
/// </summary>
/// <param name="graphics">Gdi object, used to draw curves of path reinforcement.</param>
/// <param name="size">Bound to limit the size of the whole picture</param>
/// <param name="pen">Gdi object,determine the color of the line.</param>
public void Draw(Graphics graphics, Size size, Pen pen)
{
Autodesk.Revit.DB.UV delta = m_box.Max - m_box.Min;
float scaleX = size.Width / (float)delta.U;
float scaleY = size.Width / (float)delta.V;
float scale = scaleY > scaleX ? scaleX : scaleY;
scale *= 0.90f;
GraphicsContainer contain = graphics.BeginContainer();
{
//set graphics coordinate system to picture center
//and flip the yAxis.
graphics.Transform = new Matrix(1, 0, 0, -1, size.Width / 2, size.Height / 2);
//construct a matrix to transform the origin point to Bound center.
Autodesk.Revit.DB.UV center = (m_box.Min + m_box.Max) / 2;
Matrix toCenter = new Matrix(1, 0, 0, 1, -(float)center.U, -(float)center.V);
bool isDrawFinished = false;
List<List<UV>> point2d = m_point2d;
Pen tmpPen = pen;
while (!isDrawFinished)
{
foreach (List<UV> arr in point2d)
{
for (int i = 0; i < arr.Count - 1; i++)
{
//get the two connection points to draw a line between them.
Autodesk.Revit.DB.UV uv1 = arr[i];
Autodesk.Revit.DB.UV uv2 = arr[i + 1];
PointF[] points = new PointF[] {
new PointF((float)uv1.U, (float)uv1.V),
new PointF((float)uv2.U, (float)uv2.V) };
//transform points to bound center.
toCenter.TransformPoints(points);
//Zoom(Scale) the points to fit the picture box.
PointF pf1 = new PointF(points[0].X * scale, points[0].Y * scale);
PointF pf2 = new PointF(points[1].X * scale, points[1].Y * scale);
//draw a line between pf1 and pf2.
graphics.DrawLine(tmpPen, pf1, pf2);
}
}
if (point2d == m_path2d)
{
isDrawFinished = true;
}
point2d = m_path2d;
tmpPen = Pens.Blue;
}
}
graphics.EndContainer(contain);
}
/// <summary>
/// Transform 3d path to 2d path.
/// </summary>
/// <returns></returns>
private void ComputePathTo2D()
{
Matrix4 transform = GetActiveViewMatrix().Inverse();
foreach (List<XYZ> arr in m_path)
{
List<UV> uvarr = new List<UV>();
foreach (Autodesk.Revit.DB.XYZ xyz in arr)
{
Vector4 tmpVector = transform.Transform(new Vector4(xyz));
Autodesk.Revit.DB.UV tmpUv = new Autodesk.Revit.DB.UV(
tmpVector.X,
tmpVector.Y);
uvarr.Add(tmpUv);
}
m_path2d.Add(uvarr);
}
}
/// <summary>
/// Compute the bound of the curves of path reinforcement.
/// </summary>
private void ComputeBound()
{
//make the bound
Autodesk.Revit.DB.UV min = m_box.get_Bounds(0);
Autodesk.Revit.DB.UV max = m_box.get_Bounds(1);
Matrix4 transform = GetActiveViewMatrix().Inverse();
bool isFirst = true;
foreach (List<XYZ> arr in m_curves)
{
List<UV> uvarr = new List<UV>();
foreach (Autodesk.Revit.DB.XYZ xyz in arr)
{
Vector4 tmpVector = transform.Transform(new Vector4(xyz));
Autodesk.Revit.DB.UV tmpUv = new Autodesk.Revit.DB.UV(
tmpVector.X,
tmpVector.Y);
uvarr.Add(tmpUv);
if (isFirst)
{
isFirst = false;
min = new UV(tmpUv.U, tmpUv.V);
max = new UV(tmpUv.U, tmpUv.V);
}
if (tmpUv.U < min.U)
{
min = new UV(tmpUv.U, min.V);
}
else if (tmpUv.U > max.U)
{
max = new UV(tmpUv.U, max.V);
}
if (tmpUv.V < min.V)
{
min = new UV(min.U, tmpUv.V);
}
else if (tmpUv.V > max.V)
{
max = new UV(max.U, tmpUv.V);
}
}
m_point2d.Add(uvarr);
}
m_box.Min = min;
m_box.Max = max;
}
/// <summary>
/// Tessellate the curves of path reinforcement.
/// </summary>
private void Tessellate()
{
Options option = new Options();
option.DetailLevel = DetailLevels.Fine;
Autodesk.Revit.DB.GeometryElement geoElem = m_pathRein.get_Geometry(option);
GeometryObjectArray geoArray = geoElem.Objects;
foreach (GeometryObject geo in geoArray)
{
if (geo is Curve)
{
Curve curve = geo as Curve;
m_curves.Add(curve.Tessellate() as List<XYZ>);
}
}
foreach (ModelCurve modelCurve in m_pathRein.Curves)
{
m_path.Add(modelCurve.GeometryCurve.Tessellate() as List<XYZ>);
}
}
/// <summary>
/// Get view matrix from active view.
/// </summary>
/// <returns>view matrix</returns>
private Matrix4 GetActiveViewMatrix()
{
View activeView = m_commandData.Application.ActiveUIDocument.Document.ActiveView;
Autodesk.Revit.DB.XYZ vZAxis = activeView.ViewDirection;
Autodesk.Revit.DB.XYZ vXAxis = activeView.RightDirection;
Autodesk.Revit.DB.XYZ vYAxis = activeView.UpDirection;
return new Matrix4(new Vector4(vXAxis), new Vector4(vYAxis), new Vector4(vZAxis));
}
}
}
| |
//#define ASMMouse
#if ASMMouse
//#define DebugMouse
using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.IL2CPU.API;
using Cosmos.Compiler.Assembler;
using Cosmos.Compiler.Assembler.X86;
using Cosmos.Core;
namespace Cosmos.Hardware
{
class AsmMouse
{
#region Native mouse implementation
#region EnableMouseASM
private class EnableMouseASM : AssemblerMethod
{
public override void AssembleNew(object aAssembler, object aMethodInfo)
{
XS.Mov(XSRegisters.BL, 0xa8);
XS.Call("send_mouse_cmd");
XS.Call("mouse_read");
XS.Noop();
XS.Mov(XSRegisters.BL, 0x20);
XS.Call("send_mouse_cmd");
XS.Call("mouse_read");
XS.Or(XSRegisters.AL, 3);
XS.Mov(XSRegisters.BL, 0x60);
XS.Push(XSRegisters.EAX);
XS.Call("send_mouse_cmd");
XS.Pop(XSRegisters.EAX);
XS.Call("mouse_write");
XS.Noop();
XS.Mov(XSRegisters.BL, 0xd4);
XS.Call("send_mouse_cmd");
XS.Mov(XSRegisters.AL, 0xf4);
XS.Call("mouse_write");
XS.Call("mouse_read");
#region mouse_read
XS.Label("mouse_read");
{
XS.Push(XSRegisters.ECX);
XS.Push(XSRegisters.EDX);
XS.Mov(XSRegisters.ECX, 0xffff);
XS.Label("mouse_read_loop");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x64,
Size = 8
};
XS.Test(XSRegisters.AL, 1);
XS.Jump(ConditionalTestEnum.NotZero, "mouse_read_ready");
new Loop
{
DestinationLabel = "mouse_read_loop"
};
XS.Mov(XSRegisters.AH, 1);
XS.Jump("mouse_read_exit");
}
XS.Label("mouse_read_ready");
{
XS.Push(XSRegisters.ECX);
XS.Mov(XSRegisters.ECX, 32);
}
XS.Label("mouse_read_delay");
{
new Loop
{
DestinationLabel = "mouse_read_delay"
};
XS.Pop(XSRegisters.ECX);
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x60,
Size = 8
};
XS.Xor(XSRegisters.AH, XSRegisters.RegistersEnum.AH);
}
XS.Label("mouse_read_exit");
{
XS.Pop(XSRegisters.EDX);
XS.Pop(XSRegisters.ECX);
XS.Return();
}
}
#endregion
#region mouse_write
XS.Label("mouse_write");
{
XS.Push(XSRegisters.ECX);
XS.Push(XSRegisters.EDX);
XS.Mov(XSRegisters.BH, XSRegisters.RegistersEnum.AL);
XS.Mov(XSRegisters.ECX, 0xffff);
XS.Label("mouse_write_loop1");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x64,
Size = 8
};
XS.Test(XSRegisters.AL, 32);
XS.Jump(ConditionalTestEnum.Zero, "mouse_write_ok1");
new Loop
{
DestinationLabel = "mouse_write_loop1"
};
XS.Mov(XSRegisters.AH, 1);
XS.Jump("mouse_write_exit");
}
XS.Label("mouse_write_ok1");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x60,
Size = 8
};
XS.Mov(XSRegisters.ECX, 0xffff);
}
XS.Label("mouse_write_loop");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x64,
Size = 8
};
XS.Test(XSRegisters.AL, 2);
XS.Jump(ConditionalTestEnum.Zero, "mouse_write_ok");
new Loop
{
DestinationLabel = "mouse_write_loop"
};
XS.Mov(XSRegisters.AH, 1);
XS.Jump("mouse_write_exit");
}
XS.Label("mouse_write_ok");
{
XS.Mov(XSRegisters.AL, XSRegisters.RegistersEnum.BH);
new Out2Port
{
DestinationValue = 0x60,
SourceReg = RegistersEnum.AL,
Size = 8
};
XS.Mov(XSRegisters.ECX, 0xffff);
}
XS.Label("mouse_write_loop3");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x64,
Size = 8
};
XS.Test(XSRegisters.AL, 2);
XS.Jump(ConditionalTestEnum.Zero, "mouse_write_ok3");
new Loop
{
DestinationLabel = "mouse_write_loop3"
};
XS.Mov(XSRegisters.AH, 1);
XS.Jump("mouse_write_exit");
}
XS.Label("mouse_write_ok3");
{
XS.Mov(XSRegisters.AH, 0x08);
}
XS.Label("mouse_write_loop4");
{
XS.Mov(XSRegisters.ECX, 0xffff);
}
XS.Label("mouse_write_loop5");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x64,
Size = 8
};
XS.Test(XSRegisters.AL, 1);
XS.Jump(ConditionalTestEnum.NotZero, "mouse_write_ok4");
new Loop
{
DestinationLabel = "mouse_write_loop5"
};
XS.Dec(XSRegisters.AH);
XS.Jump(ConditionalTestEnum.NotZero, "mouse_write_loop4");
}
XS.Label("mouse_write_ok4");
{
XS.Xor(XSRegisters.AH, XSRegisters.RegistersEnum.AH);
}
XS.Label("mouse_write_exit");
{
XS.Pop(XSRegisters.EDX);
XS.Pop(XSRegisters.ECX);
XS.Return();
}
}
#endregion
#region send_mouse_cmd
XS.Label("send_mouse_cmd");
{
XS.Mov(XSRegisters.ECX, 0xffff);
XS.Label("mouse_cmd_wait");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x64,
Size = 8
};
XS.Test(XSRegisters.AL, 2);
XS.Jump(ConditionalTestEnum.Zero, "mouse_cmd_send");
new Loop
{
DestinationLabel = "mouse_cmd_wait"
};
XS.Jump("mouse_cmd_error");
}
XS.Label("mouse_cmd_send");
{
XS.Mov(XSRegisters.AL, XSRegisters.RegistersEnum.BL);
new Out2Port
{
#if DebugMouse
SourceValue = 0x64,
DestinationReg = RegistersEnum.AL,
#else
DestinationValue = 0x64,
SourceReg = RegistersEnum.AL,
#endif
Size = 8
};
XS.Mov(XSRegisters.ECX, 0xffff);
}
XS.Label("mouse_cmd_accept");
{
new In2Port
{
DestinationReg = RegistersEnum.AL,
SourceValue = 0x64,
Size = 8
};
XS.Test(XSRegisters.AL, 0x02);
XS.Jump(ConditionalTestEnum.Zero, "mouse_cmd_ok");
new Loop
{
DestinationLabel = "mouse_cmd_accept"
};
}
XS.Label("mouse_cmd_error");
{
XS.Mov(XSRegisters.AH, 0x01);
XS.Jump("mouse_cmd_exit");
}
XS.Label("mouse_cmd_ok");
{
XS.Xor(XSRegisters.AH, XSRegisters.RegistersEnum.AH);
}
XS.Label("mouse_cmd_exit");
{
XS.Return();
}
}
#endregion
}
}
#endregion
private static class InternalMouseEnable
{
public static void EnableMouse() { }
}
[Plug(Target = typeof(global::Cosmos.Hardware.AsmMouse.InternalMouseEnable))]
private static class InternalMousePlugged
{
[PlugMethod(Assembler = typeof(global::Cosmos.Hardware.AsmMouse.EnableMouseASM))]
public static void EnableMouse() { }
}
#endregion
private IOPort p60 = new IOPort(0x60);
private IOPort p64 = new IOPort(0x64);
/// <summary>
/// The X location of the mouse.
/// </summary>
public int X;
/// <summary>
/// The Y location of the mouse.
/// </summary>
public int Y;
/// <summary>
/// The state the mouse is currently in.
/// </summary>
public MouseState Buttons;
/// <summary>
/// This is the required call to start
/// the mouse receiving interrupts.
/// </summary>
public void Initialize()
{
AsmMouse.InternalMouseEnable.EnableMouse();
Cosmos.Core.INTs.SetIrqHandler(12, new INTs.InterruptDelegate(HandleMouse));
}
/// <summary>
/// The possible states of a mouse.
/// </summary>
public enum MouseState
{
/// <summary>
/// No button is pressed.
/// </summary>
None = 0,
/// <summary>
/// The left mouse button is pressed.
/// </summary>
Left = 1,
/// <summary>
/// The right mouse button is pressed.
/// </summary>
Right = 2,
/// <summary>
/// The middle mouse button is pressed.
/// </summary>
Middle = 4
}
private byte mouse_cycle = 0;
private int[] mouse_byte = new int[4];
/// <summary>
/// This is the default mouse handling code.
/// </summary>
/// <param name="context"></param>
public void HandleMouse(ref INTs.IRQContext context)
{
switch (mouse_cycle)
{
case 0:
mouse_byte[0] = p60.Byte;
if ((mouse_byte[0] & 0x8) == 0x8)
mouse_cycle++;
break;
case 1:
mouse_byte[1] = p60.Byte;
mouse_cycle++;
break;
case 2:
mouse_byte[2] = p60.Byte;
mouse_cycle = 0;
if ((mouse_byte[0] & 0x10) == 0x10)
X -= mouse_byte[1] ^ 0xff;
else
X += mouse_byte[1];
if ((mouse_byte[0] & 0x20) == 0x20)
Y += mouse_byte[2] ^ 0xff;
else
Y -= mouse_byte[2];
if (X < 0)
X = 0;
else if (X > 319)
X = 319;
if (Y < 0)
Y = 0;
else if (Y > 199)
Y = 199;
Buttons = (MouseState)(mouse_byte[0] & 0x7);
break;
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Threading;
namespace System.ComponentModel
{
/// <devdoc>
/// <para>Specifies the default value for a property.</para>
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
[AttributeUsage(AttributeTargets.All)]
public class DefaultValueAttribute : Attribute
{
/// <devdoc>
/// This is the default value.
/// </devdoc>
private object _value;
// Delegate ad hoc created 'TypeDescriptor.ConvertFromInvariantString' reflection object cache
static object s_convertFromInvariantString;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class, converting the
/// specified value to the
/// specified type, and using the U.S. English culture as the
/// translation
/// context.</para>
/// </devdoc>
public DefaultValueAttribute(Type type, string value)
{
// The try/catch here is because attributes should never throw exceptions. We would fail to
// load an otherwise normal class.
try
{
if (TryConvertFromInvariantString(type, value, out object convertedValue))
{
_value = convertedValue;
}
else if (type.IsSubclassOf(typeof(Enum)))
{
_value = Enum.Parse(type, value, true);
}
else if (type == typeof(TimeSpan))
{
_value = TimeSpan.Parse(value);
}
else
{
_value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
return;
// Looking for ad hoc created TypeDescriptor.ConvertFromInvariantString(Type, string)
bool TryConvertFromInvariantString(Type typeToConvert, string stringValue, out object conversionResult)
{
conversionResult = null;
// lazy init reflection objects
if (s_convertFromInvariantString == null)
{
Type typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false);
Volatile.Write(ref s_convertFromInvariantString, typeDescriptorType == null ? new object() : Delegate.CreateDelegate(typeof(Func<Type, string, object>), typeDescriptorType, "ConvertFromInvariantString", ignoreCase: false));
}
if (!(s_convertFromInvariantString is Func<Type, string, object> convertFromInvariantString))
return false;
conversionResult = convertFromInvariantString(typeToConvert, stringValue);
return true;
}
}
catch
{
}
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a Unicode
/// character.</para>
/// </devdoc>
public DefaultValueAttribute(char value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using an 8-bit unsigned
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(byte value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 16-bit signed
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(short value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 32-bit signed
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(int value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 64-bit signed
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(long value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a
/// single-precision floating point
/// number.</para>
/// </devdoc>
public DefaultValueAttribute(float value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a
/// double-precision floating point
/// number.</para>
/// </devdoc>
public DefaultValueAttribute(double value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.Boolean'/>
/// value.</para>
/// </devdoc>
public DefaultValueAttribute(bool value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.String'/>.</para>
/// </devdoc>
public DefaultValueAttribute(string value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/>
/// class.</para>
/// </devdoc>
public DefaultValueAttribute(object value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.SByte'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(sbyte value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt16'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(ushort value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt32'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(uint value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt64'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(ulong value)
{
_value = value;
}
/// <devdoc>
/// <para>
/// Gets the default value of the property this
/// attribute is
/// bound to.
/// </para>
/// </devdoc>
public virtual object Value
{
get
{
return _value;
}
}
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
DefaultValueAttribute other = obj as DefaultValueAttribute;
if (other != null)
{
if (Value != null)
{
return Value.Equals(other.Value);
}
else
{
return (other.Value == null);
}
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected void SetValue(object value)
{
_value = value;
}
}
}
| |
// -------------------------------------------------------------------------------------------
// <copyright file="PriceMatrix.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// -------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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 Sitecore.Ecommerce.PriceMatrix
{
using System;
using System.IO;
using System.Xml.Serialization;
using Sitecore.Data;
using Sitecore.Data.Items;
/// <summary>
/// IPriceMatrixItem contains sites.
/// </summary>
[Serializable]
public class PriceMatrix
{
/// <summary>
/// </summary>
[XmlElement("structure", typeof(Category))]
public Category MainCategory;
/// <summary>
/// </summary>
/// <param name="mainCategory">
/// </param>
public PriceMatrix(Category mainCategory)
{
this.MainCategory = mainCategory;
}
/// <summary>
/// </summary>
public PriceMatrix()
{
this.MainCategory = new Category();
}
/// <summary>
/// </summary>
/// <param name="category">
/// </param>
public void AddCategory(Category category)
{
category.Parent = this.MainCategory;
this.MainCategory.AddCategory(category);
}
/// <summary>
/// </summary>
/// <param name="categoryItem">
/// </param>
public void AddItem(CategoryItem categoryItem)
{
categoryItem.Parent = this.MainCategory;
this.MainCategory.AddItem(categoryItem);
}
/// <summary>
/// </summary>
/// <param name="query">
/// </param>
/// <returns>
/// </returns>
public CategoryItem GetDefaultPriceFromCategory(string query)
{
IPriceMatrixItem priceMatrixItem = this.SelectSingleItem(query);
var category = (Category)priceMatrixItem;
Item priceMatrix = Sitecore.Context.Database.SelectSingleItem("/*/system/Modules/*[@@templatekey='configuration']").Children["PriceMatrix"];
if (priceMatrix != null)
{
Item currentPriceItem = priceMatrix.Axes.SelectSingleItem(query);
if (currentPriceItem != null)
{
string id = currentPriceItem["defaultPrice"];
Item priceItem = null;
if (!string.IsNullOrEmpty(id))
{
priceItem = priceMatrix.Database.GetItem(id);
}
else
{
if (currentPriceItem.Children.Count > 0)
{
priceItem = currentPriceItem.Children[0];
}
}
if (priceItem != null)
{
string priceName = priceItem.Name;
return category.GetItem(priceName);
}
}
}
return null;
}
/// <summary>
/// Query language:
/// "./name/name"
/// </summary>
/// <param name="query">
/// </param>
/// <returns>
/// </returns>
public IPriceMatrixItem SelectSingleItem(string query)
{
string[] axes = query.Split('/');
IPriceMatrixItem current = null;
for (int i = 0; i < axes.Length; i++)
{
string name = axes[i];
if (!(i == 0 && name.Contains(".")))
{
if (!string.IsNullOrEmpty(name))
{
current = this.GetElement(current, axes[i]);
if (current == null)
{
return null;
}
}
else
{
return null;
}
}
}
return current;
}
/// <summary>
/// </summary>
/// <param name="priceMatrixItem">
/// </param>
/// <param name="id">
/// </param>
/// <returns>
/// </returns>
public IPriceMatrixItem GetElement(IPriceMatrixItem priceMatrixItem, string id)
{
if (priceMatrixItem == null)
{
priceMatrixItem = this.MainCategory;
}
if (priceMatrixItem is Category)
{
Category category = this.GetCategory(priceMatrixItem, id);
if (category != null)
{
return category;
}
return this.GetItem(priceMatrixItem, id);
}
return null;
}
/// <summary>
/// </summary>
/// <param name="id">
/// </param>
/// <returns>
/// </returns>
public IPriceMatrixItem GetElement(string id)
{
Category category = this.GetCategory(id);
if (category != null)
{
return category;
}
return this.GetItem(id);
}
/// <summary>
/// </summary>
/// <param name="item">
/// </param>
/// <param name="id">
/// </param>
/// <returns>
/// </returns>
private Category GetCategory(IPriceMatrixItem item, string id)
{
if (item is Category)
{
return ((Category)item).GetCategory(id);
}
return null;
}
/// <summary>
/// </summary>
/// <param name="id">
/// </param>
/// <returns>
/// </returns>
public Category GetCategory(string id)
{
return this.MainCategory.GetCategory(id);
}
/// <summary>
/// </summary>
/// <param name="item">
/// </param>
/// <param name="id">
/// </param>
/// <returns>
/// </returns>
private CategoryItem GetItem(IPriceMatrixItem item, string id)
{
if (item is Category)
{
return ((Category)item).GetItem(id);
}
return null;
}
/// <summary>
/// </summary>
/// <param name="id">
/// </param>
/// <returns>
/// </returns>
public CategoryItem GetItem(string id)
{
return this.MainCategory.GetItem(id);
}
/// <summary>
/// </summary>
/// <param name="xml">
/// </param>
/// <returns>
/// </returns>
public static PriceMatrix Load(string xml)
{
if (string.IsNullOrEmpty(xml))
{
return new PriceMatrix();
}
var serializer = new XmlSerializer(typeof(PriceMatrix));
TextReader tr = new StringReader(xml);
PriceMatrix priceMatrixItem = null;
try
{
priceMatrixItem = (PriceMatrix)serializer.Deserialize(tr);
}
catch (InvalidOperationException)
{
}
finally
{
tr.Close();
}
return priceMatrixItem;
}
/*public int Remove(string idsToKeep)
{
string[] ids = idsToKeep.Split('|');
string removeIds = "";
for (int i = 0; i < SiteItems.Count; i++)
{
Category site = SiteItems[i];
if (!idsToKeep.Contains(site.Id))
{
removeIds += site.Id + "|";
}
}
ids = removeIds.Split('|');
foreach (string id in ids)
{
SiteItems.Remove(GetSite(id));
}
return ids.Length;
}*/
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using JsonFx.Json;
using JsonFx.Serialization;
namespace JsonFx.EcmaScript
{
/// <summary>
/// Formats data as full ECMAScript objects, rather than the limited set of JSON objects.
/// </summary>
public class EcmaScriptFormatter : JsonWriter.JsonFormatter
{
#region Constants
private static readonly DateTime EcmaScriptEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
private const string EcmaScriptDateCtor1 = "new Date({0})";
private const string EcmaScriptDateCtor7 = "new Date({0:0000},{1},{2},{3},{4},{5},{6})";
private const string EmptyRegExpLiteral = "(?:)";
private const char RegExpLiteralDelim = '/';
private const char OperatorCharEscape = '\\';
private const string NamespaceDelim = ".";
private static readonly char[] NamespaceDelims = { '.' };
private const string RootDeclarationDebug =
@"
/* namespace {1} */
var {0};";
private const string RootDeclaration = @"var {0};";
private const string NamespaceCheck =
@"if(""undefined""===typeof {0}){{{0}={{}};}}";
private const string NamespaceCheckDebug =
@"
if (""undefined"" === typeof {0}) {{
{0} = {{}};
}}";
private static readonly IList<string> BrowserObjects = new List<string>(new string[]
{
"console",
"document",
"event",
"frames",
"history",
"location",
"navigator",
"opera",
"screen",
"window"
});
#endregion Constants
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="settings"></param>
/// <remarks>
/// Defaults to encoding < chars for improved embedding within script blocks
/// </remarks>
public EcmaScriptFormatter(DataWriterSettings settings)
: base(settings)
{
}
#endregion Init
#region Namespace Methods
/// <summary>
/// Emits a block of script ensuring that a namespace is declared
/// </summary>
/// <param name="writer">the output writer</param>
/// <param name="ident">the namespace to ensure</param>
/// <param name="namespaces">list of namespaces already emitted</param>
/// <param name="debug">determines if should emit pretty-printed</param>
/// <returns>if was a namespaced identifier</returns>
public static bool WriteNamespaceDeclaration(TextWriter writer, string ident, List<string> namespaces, bool prettyPrint)
{
if (String.IsNullOrEmpty(ident))
{
return false;
}
if (namespaces == null)
{
namespaces = new List<string>();
}
string[] nsParts = ident.Split(EcmaScriptFormatter.NamespaceDelims, StringSplitOptions.RemoveEmptyEntries);
string ns = nsParts[0];
bool isNested = false;
for (int i=0; i<nsParts.Length-1; i++)
{
isNested = true;
if (i > 0)
{
ns += EcmaScriptFormatter.NamespaceDelim;
ns += nsParts[i];
}
if (namespaces.Contains(ns) ||
EcmaScriptFormatter.BrowserObjects.Contains(ns))
{
// don't emit multiple checks for same namespace
continue;
}
// make note that we've emitted this namespace before
namespaces.Add(ns);
if (i == 0)
{
if (prettyPrint)
{
writer.Write(EcmaScriptFormatter.RootDeclarationDebug, ns,
String.Join(NamespaceDelim, nsParts, 0, nsParts.Length-1));
}
else
{
writer.Write(EcmaScriptFormatter.RootDeclaration, ns);
}
}
if (prettyPrint)
{
writer.WriteLine(EcmaScriptFormatter.NamespaceCheckDebug, ns);
}
else
{
writer.Write(EcmaScriptFormatter.NamespaceCheck, ns);
}
}
if (prettyPrint && isNested)
{
writer.WriteLine();
}
return isNested;
}
#endregion Namespace Methods
#region JsonFormatter Methods
protected override void WriteNaN(TextWriter writer)
{
writer.Write(JsonGrammar.KeywordNaN);
}
protected override void WriteNegativeInfinity(TextWriter writer)
{
writer.Write('-');
writer.Write(JsonGrammar.KeywordInfinity);
}
protected override void WritePositiveInfinity(TextWriter writer)
{
writer.Write(JsonGrammar.KeywordInfinity);
}
protected override void WritePrimitive(TextWriter writer, object value)
{
if (value is DateTime)
{
// write as ECMAScript Date constructor
EcmaScriptFormatter.WriteEcmaScriptDate(writer, (DateTime)value);
return;
}
if (value is Regex)
{
EcmaScriptFormatter.WriteEcmaScriptRegExp(writer, (Regex)value);
return;
}
base.WritePrimitive(writer, value);
}
protected override void WritePropertyName(TextWriter writer, string propertyName)
{
if (EcmaScriptIdentifier.IsValidIdentifier(propertyName, false))
{
// write out without quoting
writer.Write(propertyName);
}
else
{
// write out as an escaped string
base.WritePropertyName(writer, propertyName);
}
}
#endregion JsonFormatter Methods
#region Formatting Methods
public static void WriteEcmaScriptDate(TextWriter writer, DateTime value)
{
if (value.Kind == DateTimeKind.Unspecified)
{
// unknown timezones serialize directly to become browser-local
writer.Write(
EcmaScriptFormatter.EcmaScriptDateCtor7,
value.Year, // yyyy
value.Month-1, // 0-11
value.Day, // 1-31
value.Hour, // 0-23
value.Minute, // 0-60
value.Second, // 0-60
value.Millisecond); // 0-999
return;
}
if (value.Kind == DateTimeKind.Local)
{
// convert server-local to UTC
value = value.ToUniversalTime();
}
// find the time since Jan 1, 1970
TimeSpan duration = value.Subtract(EcmaScriptFormatter.EcmaScriptEpoch);
// get the total milliseconds
long ticks = (long)duration.TotalMilliseconds;
// write out as a Date constructor
writer.Write(
EcmaScriptFormatter.EcmaScriptDateCtor1,
ticks);
}
/// <summary>
/// Outputs a .NET Regex as an ECMAScript RegExp literal.
/// Defaults to global matching off.
/// </summary>
/// <param name="writer"></param>
/// <param name="regex"></param>
/// <remarks>
/// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
/// </remarks>
public static void WriteEcmaScriptRegExp(TextWriter writer, Regex regex)
{
EcmaScriptFormatter.WriteEcmaScriptRegExp(writer, regex, false);
}
/// <summary>
/// Outputs a .NET Regex as an ECMAScript RegExp literal.
/// </summary>
/// <param name="writer"></param>
/// <param name="regex"></param>
/// <param name="isGlobal"></param>
/// <remarks>
/// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
/// </remarks>
public static void WriteEcmaScriptRegExp(TextWriter writer, Regex regex, bool isGlobal)
{
if (regex == null)
{
writer.Write(JsonGrammar.KeywordNull);
return;
}
// Regex.ToString() returns the original pattern
string pattern = regex.ToString();
if (String.IsNullOrEmpty(pattern))
{
// must output something otherwise becomes a code comment
pattern = EcmaScriptFormatter.EmptyRegExpLiteral;
}
string modifiers = isGlobal ? "g" : "";
switch (regex.Options & (RegexOptions.IgnoreCase|RegexOptions.Multiline))
{
case RegexOptions.IgnoreCase:
{
modifiers += "i";
break;
}
case RegexOptions.Multiline:
{
modifiers += "m";
break;
}
case RegexOptions.IgnoreCase|RegexOptions.Multiline:
{
modifiers += "im";
break;
}
}
writer.Write(EcmaScriptFormatter.RegExpLiteralDelim);
int length = pattern.Length;
int start = 0;
for (int i = start; i < length; i++)
{
switch (pattern[i])
{
case EcmaScriptFormatter.RegExpLiteralDelim:
{
writer.Write(pattern.Substring(start, i - start));
start = i + 1;
writer.Write(EcmaScriptFormatter.OperatorCharEscape);
writer.Write(pattern[i]);
break;
}
}
}
writer.Write(pattern.Substring(start, length - start));
writer.Write(EcmaScriptFormatter.RegExpLiteralDelim);
writer.Write(modifiers);
}
#endregion Writer Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable sorted set implementation.
/// </summary>
/// <typeparam name="T">The type of elements in the set.</typeparam>
/// <devremarks>
/// We implement <see cref="IReadOnlyList{T}"/> because it adds an ordinal indexer.
/// We implement <see cref="IList{T}"/> because it gives us <see cref="IList{T}.IndexOf"/>, which is important for some folks.
/// </devremarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))]
public sealed partial class ImmutableSortedSet<T> : IImmutableSet<T>, ISortKeyCollection<T>, IReadOnlyList<T>, IList<T>, ISet<T>, IList, IStrongEnumerable<T, ImmutableSortedSet<T>.Enumerator>
{
/// <summary>
/// This is the factor between the small collection's size and the large collection's size in a bulk operation,
/// under which recreating the entire collection using a fast method rather than some incremental update
/// (that requires tree rebalancing) is preferable.
/// </summary>
private const float RefillOverIncrementalThreshold = 0.15f;
/// <summary>
/// An empty sorted set with the default sort comparer.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableSortedSet<T> Empty = new ImmutableSortedSet<T>();
/// <summary>
/// The root node of the AVL tree that stores this set.
/// </summary>
private readonly Node _root;
/// <summary>
/// The comparer used to sort elements in this set.
/// </summary>
private readonly IComparer<T> _comparer;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedSet{T}"/> class.
/// </summary>
/// <param name="comparer">The comparer.</param>
internal ImmutableSortedSet(IComparer<T> comparer = null)
{
_root = Node.EmptyNode;
_comparer = comparer ?? Comparer<T>.Default;
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedSet{T}"/> class.
/// </summary>
/// <param name="root">The root of the AVL tree with the contents of this set.</param>
/// <param name="comparer">The comparer.</param>
private ImmutableSortedSet(Node root, IComparer<T> comparer)
{
Requires.NotNull(root, nameof(root));
Requires.NotNull(comparer, nameof(comparer));
root.Freeze();
_root = root;
_comparer = comparer;
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public ImmutableSortedSet<T> Clear()
{
return _root.IsEmpty ? this : Empty.WithComparer(_comparer);
}
/// <summary>
/// Gets the maximum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The maximum value in the set.</value>
public T Max
{
get { return _root.Max; }
}
/// <summary>
/// Gets the minimum value in the collection, as defined by the comparer.
/// </summary>
/// <value>The minimum value in the set.</value>
public T Min
{
get { return _root.Min; }
}
#region IImmutableSet<T> Properties
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public bool IsEmpty
{
get { return _root.IsEmpty; }
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public int Count
{
get { return _root.Count; }
}
#endregion
#region ISortKeyCollection<T> Properties
/// <summary>
/// See the <see cref="ISortKeyCollection{T}"/> interface.
/// </summary>
public IComparer<T> KeyComparer
{
get { return _comparer; }
}
#endregion
/// <summary>
/// Gets the root node (for testing purposes).
/// </summary>
internal IBinaryTree Root
{
get { return _root; }
}
#region IReadOnlyList<T> Indexers
/// <summary>
/// Gets the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>The element at the given position.</returns>
public T this[int index]
{
get
{
#if !NETSTANDARD10
return _root.ItemRef(index);
#else
return _root[index];
#endif
}
}
#if !NETSTANDARD10
/// <summary>
/// Gets a read-only reference of the element of the set at the given index.
/// </summary>
/// <param name="index">The 0-based index of the element in the set to return.</param>
/// <returns>A read-only reference of the element at the given position.</returns>
public ref readonly T ItemRef(int index)
{
return ref _root.ItemRef(index);
}
#endif
#endregion
#region Public methods
/// <summary>
/// Creates a collection with the same contents as this collection that
/// can be efficiently mutated across multiple operations using standard
/// mutable interfaces.
/// </summary>
/// <remarks>
/// This is an O(1) operation and results in only a single (small) memory allocation.
/// The mutable collection that is returned is *not* thread-safe.
/// </remarks>
[Pure]
public Builder ToBuilder()
{
// We must not cache the instance created here and return it to various callers.
// Those who request a mutable collection must get references to the collection
// that version independently of each other.
return new Builder(this);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedSet<T> Add(T value)
{
bool mutated;
return this.Wrap(_root.Add(value, _comparer, out mutated));
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedSet<T> Remove(T value)
{
bool mutated;
return this.Wrap(_root.Remove(value, _comparer, out mutated));
}
/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
/// <param name="equalValue">The value to search for.</param>
/// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// a value that has more complete data than the value you currently have, although their
/// comparer functions indicate they are equal.
/// </remarks>
[Pure]
public bool TryGetValue(T equalValue, out T actualValue)
{
Node searchResult = _root.Search(equalValue, _comparer);
if (searchResult.IsEmpty)
{
actualValue = equalValue;
return false;
}
else
{
actualValue = searchResult.Key;
return true;
}
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedSet<T> Intersect(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
var newSet = this.Clear();
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (this.Contains(item))
{
newSet = newSet.Add(item);
}
}
Debug.Assert(newSet != null);
return newSet;
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedSet<T> Except(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
var result = _root;
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
bool mutated;
result = result.Remove(item, _comparer, out mutated);
}
return this.Wrap(result);
}
/// <summary>
/// Produces a set that contains elements either in this set or a given sequence, but not both.
/// </summary>
/// <param name="other">The other sequence of items.</param>
/// <returns>The new set.</returns>
[Pure]
public ImmutableSortedSet<T> SymmetricExcept(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
var otherAsSet = ImmutableSortedSet.CreateRange(_comparer, other);
var result = this.Clear();
foreach (T item in this)
{
if (!otherAsSet.Contains(item))
{
result = result.Add(item);
}
}
foreach (T item in otherAsSet)
{
if (!this.Contains(item))
{
result = result.Add(item);
}
}
return result;
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedSet<T> Union(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
ImmutableSortedSet<T> immutableSortedSet;
if (TryCastToImmutableSortedSet(other, out immutableSortedSet) && immutableSortedSet.KeyComparer == this.KeyComparer) // argument is a compatible immutable sorted set
{
if (immutableSortedSet.IsEmpty)
{
return this;
}
else if (this.IsEmpty)
{
// Adding the argument to this collection is equivalent to returning the argument.
return immutableSortedSet;
}
else if (immutableSortedSet.Count > this.Count)
{
// We're adding a larger set to a smaller set, so it would be faster to simply
// add the smaller set to the larger set.
return immutableSortedSet.Union(this);
}
}
int count;
if (this.IsEmpty || (other.TryGetCount(out count) && (this.Count + count) * RefillOverIncrementalThreshold > this.Count))
{
// The payload being added is so large compared to this collection's current size
// that we likely won't see much memory reuse in the node tree by performing an
// incremental update. So just recreate the entire node tree since that will
// likely be faster.
return this.LeafToRootRefill(other);
}
return this.UnionIncremental(other);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[Pure]
public ImmutableSortedSet<T> WithComparer(IComparer<T> comparer)
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
if (comparer == _comparer)
{
return this;
}
else
{
var result = new ImmutableSortedSet<T>(Node.EmptyNode, comparer);
result = result.Union(this);
Debug.Assert(result != null);
return result;
}
}
/// <summary>
/// Checks whether a given sequence of items entirely describe the contents of this set.
/// </summary>
/// <param name="other">The sequence of items to check against this set.</param>
/// <returns>A value indicating whether the sets are equal.</returns>
[Pure]
public bool SetEquals(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
if (object.ReferenceEquals(this, other))
{
return true;
}
var otherSet = new SortedSet<T>(other, this.KeyComparer);
if (this.Count != otherSet.Count)
{
return false;
}
int matches = 0;
foreach (T item in otherSet)
{
if (!this.Contains(item))
{
return false;
}
matches++;
}
return matches == this.Count;
}
/// <summary>
/// Determines whether the current set is a property (strict) subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct subset of other; otherwise, false.</returns>
[Pure]
public bool IsProperSubsetOf(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
if (this.IsEmpty)
{
return other.Any();
}
// To determine whether everything we have is also in another sequence,
// we enumerate the sequence and "tag" whether it's in this collection,
// then consider whether every element in this collection was tagged.
// Since this collection is immutable we cannot directly tag. So instead
// we simply count how many "hits" we have and ensure it's equal to the
// size of this collection. Of course for this to work we need to ensure
// the uniqueness of items in the given sequence, so we create a set based
// on the sequence first.
var otherSet = new SortedSet<T>(other, this.KeyComparer);
if (this.Count >= otherSet.Count)
{
return false;
}
int matches = 0;
bool extraFound = false;
foreach (T item in otherSet)
{
if (this.Contains(item))
{
matches++;
}
else
{
extraFound = true;
}
if (matches == this.Count && extraFound)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether the current set is a correct superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct superset of other; otherwise, false.</returns>
[Pure]
public bool IsProperSupersetOf(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
if (this.IsEmpty)
{
return false;
}
int count = 0;
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
count++;
if (!this.Contains(item))
{
return false;
}
}
return this.Count > count;
}
/// <summary>
/// Determines whether a set is a subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of other; otherwise, false.</returns>
[Pure]
public bool IsSubsetOf(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
if (this.IsEmpty)
{
return true;
}
// To determine whether everything we have is also in another sequence,
// we enumerate the sequence and "tag" whether it's in this collection,
// then consider whether every element in this collection was tagged.
// Since this collection is immutable we cannot directly tag. So instead
// we simply count how many "hits" we have and ensure it's equal to the
// size of this collection. Of course for this to work we need to ensure
// the uniqueness of items in the given sequence, so we create a set based
// on the sequence first.
var otherSet = new SortedSet<T>(other, this.KeyComparer);
int matches = 0;
foreach (T item in otherSet)
{
if (this.Contains(item))
{
matches++;
}
}
return matches == this.Count;
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
[Pure]
public bool IsSupersetOf(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (!this.Contains(item))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and other share at least one common element; otherwise, false.</returns>
[Pure]
public bool Overlaps(IEnumerable<T> other)
{
Requires.NotNull(other, nameof(other));
if (this.IsEmpty)
{
return false;
}
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (this.Contains(item))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns an <see cref="IEnumerable{T}"/> that iterates over this
/// collection in reverse order.
/// </summary>
/// <returns>
/// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}"/>
/// in reverse order.
/// </returns>
[Pure]
public IEnumerable<T> Reverse()
{
return new ReverseEnumerable(_root);
}
/// <summary>
/// Gets the position within this set that the specified value does or would appear.
/// </summary>
/// <param name="item">The value whose position is being sought.</param>
/// <returns>
/// The index of the specified <paramref name="item"/> in the sorted set,
/// if <paramref name="item"/> is found. If <paramref name="item"/> is not
/// found and <paramref name="item"/> is less than one or more elements in this set,
/// a negative number which is the bitwise complement of the index of the first
/// element that is larger than value. If <paramref name="item"/> is not found
/// and <paramref name="item"/> is greater than any of the elements in the set,
/// a negative number which is the bitwise complement of (the index of the last
/// element plus 1).
/// </returns>
public int IndexOf(T item)
{
return _root.IndexOf(item, _comparer);
}
#endregion
#region IImmutableSet<T> Members
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
public bool Contains(T value)
{
return _root.Contains(value, _comparer);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Clear()
{
return this.Clear();
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Add(T value)
{
return this.Add(value);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Remove(T value)
{
return this.Remove(value);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other)
{
return this.Intersect(other);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other)
{
return this.Except(other);
}
/// <summary>
/// Produces a set that contains elements either in this set or a given sequence, but not both.
/// </summary>
/// <param name="other">The other sequence of items.</param>
/// <returns>The new set.</returns>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other)
{
return this.SymmetricExcept(other);
}
/// <summary>
/// See the <see cref="IImmutableSet{T}"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other)
{
return this.Union(other);
}
#endregion
#region ISet<T> Members
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
bool ISet<T>.Add(T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.ExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.IntersectWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.SymmetricExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.UnionWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
#endregion
#region ICollection<T> members
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
_root.CopyTo(array, arrayIndex);
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
#endregion
#region IList<T> methods
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
T IList<T>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException();
}
#endregion
#region IList properties
/// <summary>
/// Gets a value indicating whether the <see cref="IList"/> has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IList"/> has a fixed size; otherwise, false.</returns>
bool IList.IsFixedSize
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IList.IsReadOnly
{
get { return true; }
}
#endregion
#region ICollection Properties
/// <summary>
/// See <see cref="ICollection"/>.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// See the <see cref="ICollection"/> interface.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
#endregion
#region IList methods
/// <summary>
/// Adds an item to the <see cref="IList"/>.
/// </summary>
/// <param name="value">The object to add to the <see cref="IList"/>.</param>
/// <returns>
/// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection,
/// </returns>
/// <exception cref="System.NotSupportedException"></exception>
int IList.Add(object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Clears this instance.
/// </summary>
/// <exception cref="System.NotSupportedException"></exception>
void IList.Clear()
{
throw new NotSupportedException();
}
/// <summary>
/// Determines whether the <see cref="IList"/> contains a specific value.
/// </summary>
/// <param name="value">The object to locate in the <see cref="IList"/>.</param>
/// <returns>
/// true if the <see cref="object"/> is found in the <see cref="IList"/>; otherwise, false.
/// </returns>
bool IList.Contains(object value)
{
return this.Contains((T)value);
}
/// <summary>
/// Determines the index of a specific item in the <see cref="IList"/>.
/// </summary>
/// <param name="value">The object to locate in the <see cref="IList"/>.</param>
/// <returns>
/// The index of <paramref name="value"/> if found in the list; otherwise, -1.
/// </returns>
int IList.IndexOf(object value)
{
return this.IndexOf((T)value);
}
/// <summary>
/// Inserts an item to the <see cref="IList"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param>
/// <param name="value">The object to insert into the <see cref="IList"/>.</param>
/// <exception cref="System.NotSupportedException"></exception>
void IList.Insert(int index, object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="IList"/>.
/// </summary>
/// <param name="value">The object to remove from the <see cref="IList"/>.</param>
/// <exception cref="System.NotSupportedException"></exception>
void IList.Remove(object value)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes at.
/// </summary>
/// <param name="index">The index.</param>
/// <exception cref="System.NotSupportedException"></exception>
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="System.Object"/>.
/// </value>
/// <param name="index">The index.</param>
/// <exception cref="System.NotSupportedException"></exception>
object IList.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(); }
}
#endregion
#region ICollection Methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
_root.CopyTo(array, index);
}
#endregion
#region IEnumerable<T> Members
/// <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>
[ExcludeFromCodeCoverage]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.IsEmpty ?
Enumerable.Empty<T>().GetEnumerator() :
this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <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>
[ExcludeFromCodeCoverage]
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <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>
/// <remarks>
/// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable
/// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool,
/// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk
/// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data
/// corruption and/or exceptions.
/// </remarks>
public Enumerator GetEnumerator()
{
return _root.GetEnumerator();
}
/// <summary>
/// Discovers an immutable sorted set for a given value, if possible.
/// </summary>
private static bool TryCastToImmutableSortedSet(IEnumerable<T> sequence, out ImmutableSortedSet<T> other)
{
other = sequence as ImmutableSortedSet<T>;
if (other != null)
{
return true;
}
var builder = sequence as Builder;
if (builder != null)
{
other = builder.ToImmutable();
return true;
}
return false;
}
/// <summary>
/// Creates a new sorted set wrapper for a node tree.
/// </summary>
/// <param name="root">The root of the collection.</param>
/// <param name="comparer">The comparer used to build the tree.</param>
/// <returns>The immutable sorted set instance.</returns>
[Pure]
private static ImmutableSortedSet<T> Wrap(Node root, IComparer<T> comparer)
{
return root.IsEmpty
? ImmutableSortedSet<T>.Empty.WithComparer(comparer)
: new ImmutableSortedSet<T>(root, comparer);
}
/// <summary>
/// Adds items to this collection using the standard spine rewrite and tree rebalance technique.
/// </summary>
/// <param name="items">The items to add.</param>
/// <returns>The new collection.</returns>
/// <remarks>
/// This method is least demanding on memory, providing the great chance of memory reuse
/// and does not require allocating memory large enough to store all items contiguously.
/// It's performance is optimal for additions that do not significantly dwarf the existing
/// size of this collection.
/// </remarks>
[Pure]
private ImmutableSortedSet<T> UnionIncremental(IEnumerable<T> items)
{
Requires.NotNull(items, nameof(items));
// Let's not implement in terms of ImmutableSortedSet.Add so that we're
// not unnecessarily generating a new wrapping set object for each item.
var result = _root;
foreach (var item in items.GetEnumerableDisposable<T, Enumerator>())
{
bool mutated;
result = result.Add(item, _comparer, out mutated);
}
return this.Wrap(result);
}
/// <summary>
/// Creates a wrapping collection type around a root node.
/// </summary>
/// <param name="root">The root node to wrap.</param>
/// <returns>A wrapping collection type for the new tree.</returns>
[Pure]
private ImmutableSortedSet<T> Wrap(Node root)
{
if (root != _root)
{
return root.IsEmpty ? this.Clear() : new ImmutableSortedSet<T>(root, _comparer);
}
else
{
return this;
}
}
/// <summary>
/// Creates an immutable sorted set with the contents from this collection and a sequence of elements.
/// </summary>
/// <param name="addedItems">The sequence of elements to add to this set.</param>
/// <returns>The immutable sorted set.</returns>
[Pure]
private ImmutableSortedSet<T> LeafToRootRefill(IEnumerable<T> addedItems)
{
Requires.NotNull(addedItems, nameof(addedItems));
// Rather than build up the immutable structure in the incremental way,
// build it in such a way as to generate minimal garbage, by assembling
// the immutable binary tree from leaf to root. This requires
// that we know the length of the item sequence in advance, sort it,
// and can index into that sequence like a list, so the limited
// garbage produced is a temporary mutable data structure we use
// as a reference when creating the immutable one.
// Produce the initial list containing all elements, including any duplicates.
List<T> list;
if (this.IsEmpty)
{
// If the additional items enumerable list is known to be empty, too,
// then just return this empty instance.
int count;
if (addedItems.TryGetCount(out count) && count == 0)
{
return this;
}
// Otherwise, construct a list from the items. The Count could still
// be zero, in which case, again, just return this empty instance.
list = new List<T>(addedItems);
if (list.Count == 0)
{
return this;
}
}
else
{
// Build the list from this set and then add the additional items.
// Even if the additional items is empty, this set isn't, so we know
// the resulting list will not be empty.
list = new List<T>(this);
list.AddRange(addedItems);
}
Debug.Assert(list.Count > 0);
// Sort the list and remove duplicate entries.
IComparer<T> comparer = this.KeyComparer;
list.Sort(comparer);
int index = 1;
for (int i = 1; i < list.Count; i++)
{
if (comparer.Compare(list[i], list[i - 1]) != 0)
{
list[index++] = list[i];
}
}
list.RemoveRange(index, list.Count - index);
// Use the now sorted list of unique items to construct a new sorted set.
Node root = Node.NodeTreeFromList(list.AsOrderedCollection(), 0, list.Count);
return this.Wrap(root);
}
/// <summary>
/// An reverse enumerable of a sorted set.
/// </summary>
private class ReverseEnumerable : IEnumerable<T>
{
/// <summary>
/// The root node to enumerate.
/// </summary>
private readonly Node _root;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.ReverseEnumerable"/> class.
/// </summary>
/// <param name="root">The root of the data structure to reverse enumerate.</param>
internal ReverseEnumerable(Node root)
{
Requires.NotNull(root, nameof(root));
_root = root;
}
/// <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>
public IEnumerator<T> GetEnumerator()
{
return _root.Reverse();
}
/// <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>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
$Pref::WorldEditor::FileSpec = "Torque Mission Files (*.mis)|*.mis|All Files (*.*)|*.*|";
//////////////////////////////////////////////////////////////////////////
// File Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorFileMenu::onMenuSelect(%this)
{
%this.enableItem(2, EditorIsDirty());
}
//////////////////////////////////////////////////////////////////////////
// Package that gets temporarily activated to toggle editor after mission loading.
// Deactivates itself.
package BootEditor {
function GameConnection::initialControlSet( %this )
{
Parent::initialControlSet( %this );
toggleEditor( true );
deactivatePackage( "BootEditor" );
}
};
//////////////////////////////////////////////////////////////////////////
/// Checks the various dirty flags and returns true if the
/// mission or other related resources need to be saved.
function EditorIsDirty()
{
// We kept a hard coded test here, but we could break these
// into the registered tools if we wanted to.
%isDirty = ( isObject( "ETerrainEditor" ) && ( ETerrainEditor.isMissionDirty || ETerrainEditor.isDirty ) )
|| ( isObject( "EWorldEditor" ) && EWorldEditor.isDirty )
|| ( isObject( "ETerrainPersistMan" ) && ETerrainPersistMan.hasDirty() );
// Give the editor plugins a chance to set the dirty flag.
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
%isDirty |= %obj.isDirty();
}
return %isDirty;
}
/// Clears all the dirty state without saving.
function EditorClearDirty()
{
EWorldEditor.isDirty = false;
ETerrainEditor.isDirty = false;
ETerrainEditor.isMissionDirty = false;
ETerrainPersistMan.clearAll();
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
%obj.clearDirty();
}
}
function EditorQuitGame()
{
if( EditorIsDirty())
{
MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before quitting?", "EditorSaveMissionMenu(); quit();", "quit();", "" );
}
else
quit();
}
function EditorExitMission()
{
if( EditorIsDirty())
{
MessageBoxYesNoCancel("Level Modified", "Would you like to save your changes before exiting?", "EditorDoExitMission(true);", "EditorDoExitMission(false);", "");
}
else
EditorDoExitMission(false);
}
function EditorDoExitMission(%saveFirst)
{
if(%saveFirst)
{
EditorSaveMissionMenu();
}
else
{
EditorClearDirty();
}
if (isObject( MainMenuGui ))
Editor.close("MainMenuGui");
disconnect();
}
function EditorOpenTorsionProject( %projectFile )
{
// Make sure we have a valid path to the Torsion installation.
%torsionPath = EditorSettings.value( "WorldEditor/torsionPath" );
if( !isFile( %torsionPath ) )
{
MessageBoxOK(
"Torsion Not Found",
"Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences."
);
return;
}
// Determine the path to the .torsion file.
if( %projectFile $= "" )
{
%projectName = fileBase( getExecutableName() );
%projectFile = makeFullPath( %projectName @ ".torsion" );
if( !isFile( %projectFile ) )
{
%projectFile = findFirstFile( "*.torsion", false );
if( !isFile( %projectFile ) )
{
MessageBoxOK(
"Project File Not Found",
"Cannot find .torsion project file in '" @ getMainDotCsDir() @ "'."
);
return;
}
}
}
// Open the project in Torsion.
shellExecute( %torsionPath, "\"" @ %projectFile @ "\"" );
}
function EditorOpenFileInTorsion( %file, %line )
{
// Make sure we have a valid path to the Torsion installation.
%torsionPath = EditorSettings.value( "WorldEditor/torsionPath" );
if( !isFile( %torsionPath ) )
{
MessageBoxOK(
"Torsion Not Found",
"Torsion not found at '" @ %torsionPath @ "'. Please set the correct path in the preferences."
);
return;
}
// If no file was specified, take the current mission file.
if( %file $= "" )
%file = makeFullPath( $Server::MissionFile );
// Open the file in Torsion.
%args = "\"" @ %file;
if( %line !$= "" )
%args = %args @ ":" @ %line;
%args = %args @ "\"";
shellExecute( %torsionPath, %args );
}
function EditorOpenDeclarationInTorsion( %object )
{
%fileName = %object.getFileName();
if( %fileName $= "" )
return;
EditorOpenFileInTorsion( makeFullPath( %fileName ), %object.getDeclarationLine() );
}
function EditorNewLevel( %file )
{
%saveFirst = false;
if ( EditorIsDirty() )
{
error(knob);
%saveFirst = MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @
$Server::MissionFile @ "\" before creating a new mission?", "SaveDontSave", "Question") == $MROk;
}
if(%saveFirst)
EditorSaveMission();
// Clear dirty flags first to avoid duplicate dialog box from EditorOpenMission()
if( isObject( Editor ) )
{
EditorClearDirty();
Editor.getUndoManager().clearAll();
}
if( %file $= "" )
%file = EditorSettings.value( "WorldEditor/newLevelFile" );
if( !$missionRunning )
{
activatePackage( "BootEditor" );
StartLevel( %file );
}
else
EditorOpenMission(%file);
//EWorldEditor.isDirty = true;
//ETerrainEditor.isDirty = true;
EditorGui.saveAs = true;
}
function EditorSaveMissionMenu()
{
if(EditorGui.saveAs)
EditorSaveMissionAs();
else
EditorSaveMission();
}
function EditorSaveMission()
{
// just save the mission without renaming it
// first check for dirty and read-only files:
if((EWorldEditor.isDirty || ETerrainEditor.isMissionDirty) && !isWriteableFileName($Server::MissionFile))
{
MessageBox("Error", "Mission file \""@ $Server::MissionFile @ "\" is read-only. Continue?", "Ok", "Stop");
return false;
}
if(ETerrainEditor.isDirty)
{
// Find all of the terrain files
initContainerTypeSearch($TypeMasks::TerrainObjectType);
while ((%terrainObject = containerSearchNext()) != 0)
{
if (!isWriteableFileName(%terrainObject.terrainFile))
{
if (MessageBox("Error", "Terrain file \""@ %terrainObject.terrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk)
continue;
else
return false;
}
}
}
// now write the terrain and mission files out:
if(EWorldEditor.isDirty || ETerrainEditor.isMissionDirty)
MissionGroup.save($Server::MissionFile);
if(ETerrainEditor.isDirty)
{
// Find all of the terrain files
initContainerTypeSearch($TypeMasks::TerrainObjectType);
while ((%terrainObject = containerSearchNext()) != 0)
%terrainObject.save(%terrainObject.terrainFile);
}
ETerrainPersistMan.saveDirty();
// Give EditorPlugins a chance to save.
for ( %i = 0; %i < EditorPluginSet.getCount(); %i++ )
{
%obj = EditorPluginSet.getObject(%i);
if ( %obj.isDirty() )
%obj.onSaveMission( $Server::MissionFile );
}
EditorClearDirty();
EditorGui.saveAs = false;
return true;
}
function EditorSaveMissionAs( %missionName )
{
// If we didn't get passed a new mission name then
// prompt the user for one.
if ( %missionName $= "" )
{
%dlg = new SaveFileDialog()
{
Filters = $Pref::WorldEditor::FileSpec;
DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory");
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if(%ret)
{
// Immediately override/set the levelsDirectory
EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) );
%missionName = %dlg.FileName;
}
%dlg.delete();
if(! %ret)
return;
}
if( fileExt( %missionName ) !$= ".mis" )
%missionName = %missionName @ ".mis";
EWorldEditor.isDirty = true;
%saveMissionFile = $Server::MissionFile;
$Server::MissionFile = %missionName;
%copyTerrainsFailed = false;
// Rename all the terrain files. Save all previous names so we can
// reset them if saving fails.
%newMissionName = fileBase(%missionName);
%oldMissionName = fileBase(%saveMissionFile);
initContainerTypeSearch( $TypeMasks::TerrainObjectType );
%savedTerrNames = new ScriptObject();
for( %i = 0;; %i ++ )
{
%terrainObject = containerSearchNext();
if( !%terrainObject )
break;
%savedTerrNames.array[ %i ] = %terrainObject.terrainFile;
%terrainFilePath = makeRelativePath( filePath( %terrainObject.terrainFile ), getMainDotCsDir() );
%terrainFileName = fileName( %terrainObject.terrainFile );
// Workaround to have terrains created in an unsaved "New Level..." mission
// moved to the correct place.
if( EditorGui.saveAs && %terrainFilePath $= "tools/art/terrains" )
%terrainFilePath = "art/terrains";
// Try and follow the existing naming convention.
// If we can't, use systematic terrain file names.
if( strstr( %terrainFileName, %oldMissionName ) >= 0 )
%terrainFileName = strreplace( %terrainFileName, %oldMissionName, %newMissionName );
else
%terrainFileName = %newMissionName @ "_" @ %i @ ".ter";
%newTerrainFile = %terrainFilePath @ "/" @ %terrainFileName;
if (!isWriteableFileName(%newTerrainFile))
{
if (MessageBox("Error", "Terrain file \""@ %newTerrainFile @ "\" is read-only. Continue?", "Ok", "Stop") == $MROk)
continue;
else
{
%copyTerrainsFailed = true;
break;
}
}
if( !%terrainObject.save( %newTerrainFile ) )
{
error( "Failed to save '" @ %newTerrainFile @ "'" );
%copyTerrainsFailed = true;
break;
}
%terrainObject.terrainFile = %newTerrainFile;
}
ETerrainEditor.isDirty = false;
// Save the mission.
if(%copyTerrainsFailed || !EditorSaveMission())
{
// It failed, so restore the mission and terrain filenames.
$Server::MissionFile = %saveMissionFile;
initContainerTypeSearch( $TypeMasks::TerrainObjectType );
for( %i = 0;; %i ++ )
{
%terrainObject = containerSearchNext();
if( !%terrainObject )
break;
%terrainObject.terrainFile = %savedTerrNames.array[ %i ];
}
}
%savedTerrNames.delete();
}
function EditorOpenMission(%filename)
{
if( EditorIsDirty())
{
// "EditorSaveBeforeLoad();", "getLoadFilename(\"*.mis\", \"EditorDoLoadMission\");"
if(MessageBox("Mission Modified", "Would you like to save changes to the current mission \"" @
$Server::MissionFile @ "\" before opening a new mission?", SaveDontSave, Question) == $MROk)
{
if(! EditorSaveMission())
return;
}
}
if(%filename $= "")
{
%dlg = new OpenFileDialog()
{
Filters = $Pref::WorldEditor::FileSpec;
DefaultPath = EditorSettings.value("LevelInformation/levelsDirectory");
ChangePath = false;
MustExist = true;
};
%ret = %dlg.Execute();
if(%ret)
{
// Immediately override/set the levelsDirectory
EditorSettings.setValue( "LevelInformation/levelsDirectory", collapseFilename(filePath( %dlg.FileName )) );
%filename = %dlg.FileName;
}
%dlg.delete();
if(! %ret)
return;
}
// close the current editor, it will get cleaned up by MissionCleanup
if( isObject( "Editor" ) )
Editor.close( LoadingGui );
EditorClearDirty();
// If we haven't yet connnected, create a server now.
// Otherwise just load the mission.
if( !$missionRunning )
{
activatePackage( "BootEditor" );
StartLevel( %filename );
}
else
{
loadMission( %filename, true ) ;
pushInstantGroup();
// recreate and open the editor
Editor::create();
MissionCleanup.add( Editor );
MissionCleanup.add( Editor.getUndoManager() );
EditorGui.loadingMission = true;
Editor.open();
popInstantGroup();
}
}
function EditorExportToCollada()
{
%dlg = new SaveFileDialog()
{
Filters = "COLLADA Files (*.dae)|*.dae|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%exportFile = %dlg.FileName;
}
if( fileExt( %exportFile ) !$= ".dae" )
%exportFile = %exportFile @ ".dae";
%dlg.delete();
if ( !%ret )
return;
if ( EditorGui.currentEditor.getId() == ShapeEditorPlugin.getId() )
ShapeEdShapeView.exportToCollada( %exportFile );
else
EWorldEditor.colladaExportSelection( %exportFile );
}
function EditorMakePrefab()
{
%dlg = new SaveFileDialog()
{
Filters = "Prefab Files (*.prefab)|*.prefab|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%saveFile = %dlg.FileName;
}
if( fileExt( %saveFile ) !$= ".prefab" )
%saveFile = %saveFile @ ".prefab";
%dlg.delete();
if ( !%ret )
return;
EWorldEditor.makeSelectionPrefab( %saveFile );
EditorTree.buildVisibleTree( true );
}
function EditorExplodePrefab()
{
//echo( "EditorExplodePrefab()" );
EWorldEditor.explodeSelectedPrefab();
EditorTree.buildVisibleTree( true );
}
function makeSelectedAMesh()
{
%dlg = new SaveFileDialog()
{
Filters = "Collada file (*.dae)|*.dae|";
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = false;
OverwritePrompt = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%saveFile = %dlg.FileName;
}
if( fileExt( %saveFile ) !$= ".dae" )
%saveFile = %saveFile @ ".dae";
%dlg.delete();
if ( !%ret )
return;
EWorldEditor.makeSelectionAMesh( %saveFile );
EditorTree.buildVisibleTree( true );
}
function EditorTakeControlOfEntity()
{
%object = EWorldEditor.getSelectedObject(0);
switchCamera(localClientConnection, %object);
switchControlObject(localClientConnection, %object);
}
function EditorMount()
{
echo( "EditorMount" );
%size = EWorldEditor.getSelectionSize();
if ( %size != 2 )
return;
%a = EWorldEditor.getSelectedObject(0);
%b = EWorldEditor.getSelectedObject(1);
//%a.mountObject( %b, 0 );
EWorldEditor.mountRelative( %a, %b );
}
function EditorUnmount()
{
echo( "EditorUnmount" );
%obj = EWorldEditor.getSelectedObject(0);
%obj.unmount();
}
//////////////////////////////////////////////////////////////////////////
// View Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorViewMenu::onMenuSelect( %this )
{
%this.checkItem( 1, EWorldEditor.renderOrthoGrid );
}
//////////////////////////////////////////////////////////////////////////
// Edit Menu Handlers
//////////////////////////////////////////////////////////////////////////
function EditorEditMenu::onMenuSelect( %this )
{
// UndoManager is in charge of enabling or disabling the undo/redo items.
Editor.getUndoManager().updateUndoMenu( %this );
// SICKHEAD: It a perfect world we would abstract
// cut/copy/paste with a generic selection object
// which would know how to process itself.
// Give the active editor a chance at fixing up
// the state of the edit menu.
// Do we really need this check here?
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.onEditMenuSelect( %this );
}
//////////////////////////////////////////////////////////////////////////
function EditorMenuEditDelete()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleDelete();
}
function EditorMenuEditDeselect()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleDeselect();
}
function EditorMenuEditCut()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleCut();
}
function EditorMenuEditCopy()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handleCopy();
}
function EditorMenuEditPaste()
{
if ( isObject( EditorGui.currentEditor ) )
EditorGui.currentEditor.handlePaste();
}
//////////////////////////////////////////////////////////////////////////
// Window Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorToolsMenu::onSelectItem(%this, %id)
{
%toolName = getField( %this.item[%id], 2 );
EditorGui.setEditor(%toolName, %paletteName );
%this.checkRadioItem(0, %this.getItemCount(), %id);
return true;
}
function EditorToolsMenu::setupDefaultState(%this)
{
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
// Camera Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorCameraMenu::onSelectItem(%this, %id, %text)
{
if(%id == 0 || %id == 1)
{
// Handle the Free Camera/Orbit Camera toggle
%this.checkRadioItem(0, 1, %id);
}
return Parent::onSelectItem(%this, %id, %text);
}
function EditorCameraMenu::setupDefaultState(%this)
{
// Set the Free Camera/Orbit Camera check marks
%this.checkRadioItem(0, 1, 0);
Parent::setupDefaultState(%this);
}
function EditorFreeCameraTypeMenu::onSelectItem(%this, %id, %text)
{
// Handle the camera type radio
%this.checkRadioItem(0, 2, %id);
return Parent::onSelectItem(%this, %id, %text);
}
function EditorFreeCameraTypeMenu::setupDefaultState(%this)
{
// Set the camera type check marks
%this.checkRadioItem(0, 2, 0);
Parent::setupDefaultState(%this);
}
function EditorCameraSpeedMenu::onSelectItem(%this, %id, %text)
{
// Grab and set speed
%speed = getField( %this.item[%id], 2 );
$Camera::movementSpeed = %speed;
// Update Editor
%this.checkRadioItem(0, 6, %id);
// Update Toolbar TextEdit
EWorldEditorCameraSpeed.setText( $Camera::movementSpeed );
// Update Toolbar Slider
CameraSpeedDropdownCtrlContainer-->Slider.setValue( $Camera::movementSpeed );
return true;
}
function EditorCameraSpeedMenu::setupDefaultState(%this)
{
// Setup camera speed gui's. Both menu and editorgui
%this.setupGuiControls();
//Grab and set speed
%defaultSpeed = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeed");
if( %defaultSpeed $= "" )
{
// Update Editor with default speed
%defaultSpeed = 25;
}
$Camera::movementSpeed = %defaultSpeed;
// Update Toolbar TextEdit
EWorldEditorCameraSpeed.setText( %defaultSpeed );
// Update Toolbar Slider
CameraSpeedDropdownCtrlContainer-->Slider.setValue( %defaultSpeed );
Parent::setupDefaultState(%this);
}
function EditorCameraSpeedMenu::setupGuiControls(%this)
{
// Default levelInfo params
%minSpeed = 5;
%maxSpeed = 200;
%speedA = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMin");
%speedB = EditorSettings.value("LevelInformation/levels/" @ EditorGui.levelName @ "/cameraSpeedMax");
if( %speedA < %speedB )
{
if( %speedA == 0 )
{
if( %speedB > 1 )
%minSpeed = 1;
else
%minSpeed = 0.1;
}
else
{
%minSpeed = %speedA;
}
%maxSpeed = %speedB;
}
// Set up the camera speed items
%inc = ( (%maxSpeed - %minSpeed) / (%this.getItemCount() - 1) );
for( %i = 0; %i < %this.getItemCount(); %i++)
%this.item[%i] = setField( %this.item[%i], 2, (%minSpeed + (%inc * %i)));
// Set up min/max camera slider range
eval("CameraSpeedDropdownCtrlContainer-->Slider.range = \"" @ %minSpeed @ " " @ %maxSpeed @ "\";");
}
//////////////////////////////////////////////////////////////////////////
// Tools Menu Handler
//////////////////////////////////////////////////////////////////////////
function EditorUtilitiesMenu::onSelectItem(%this, %id, %text)
{
return Parent::onSelectItem(%this, %id, %text);
}
//////////////////////////////////////////////////////////////////////////
// World Menu Handler Object Menu
//////////////////////////////////////////////////////////////////////////
function EditorWorldMenu::onMenuSelect(%this)
{
%selSize = EWorldEditor.getSelectionSize();
%lockCount = EWorldEditor.getSelectionLockCount();
%hideCount = EWorldEditor.getSelectionHiddenCount();
%this.enableItem(0, %lockCount < %selSize); // Lock Selection
%this.enableItem(1, %lockCount > 0); // Unlock Selection
%this.enableItem(3, %hideCount < %selSize); // Hide Selection
%this.enableItem(4, %hideCount > 0); // Show Selection
%this.enableItem(6, %selSize > 1 && %lockCount == 0); // Align bounds
%this.enableItem(7, %selSize > 1 && %lockCount == 0); // Align center
%this.enableItem(9, %selSize > 0 && %lockCount == 0); // Reset Transforms
%this.enableItem(10, %selSize > 0 && %lockCount == 0); // Reset Selected Rotation
%this.enableItem(11, %selSize > 0 && %lockCount == 0); // Reset Selected Scale
%this.enableItem(12, %selSize > 0 && %lockCount == 0); // Transform Selection
%this.enableItem(14, %selSize > 0 && %lockCount == 0); // Drop Selection
%this.enableItem(17, %selSize > 0); // Make Prefab
%this.enableItem(18, %selSize > 0); // Explode Prefab
%this.enableItem(20, %selSize > 1); // Mount
%this.enableItem(21, %selSize > 0); // Unmount
}
//////////////////////////////////////////////////////////////////////////
function EditorDropTypeMenu::onSelectItem(%this, %id, %text)
{
// This sets up which drop script function to use when
// a drop type is selected in the menu.
EWorldEditor.dropType = getField(%this.item[%id], 2);
%this.checkRadioItem(0, (%this.getItemCount() - 1), %id);
return true;
}
function EditorDropTypeMenu::setupDefaultState(%this)
{
// Check the radio item for the currently set drop type.
%numItems = %this.getItemCount();
%dropTypeIndex = 0;
for( ; %dropTypeIndex < %numItems; %dropTypeIndex ++ )
if( getField( %this.item[ %dropTypeIndex ], 2 ) $= EWorldEditor.dropType )
break;
// Default to screenCenter if we didn't match anything.
if( %dropTypeIndex > (%numItems - 1) )
%dropTypeIndex = 4;
%this.checkRadioItem( 0, (%numItems - 1), %dropTypeIndex );
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
function EditorAlignBoundsMenu::onSelectItem(%this, %id, %text)
{
// Have the editor align all selected objects by the selected bounds.
EWorldEditor.alignByBounds(getField(%this.item[%id], 2));
return true;
}
function EditorAlignBoundsMenu::setupDefaultState(%this)
{
// Allow the parent to set the menu's default state
Parent::setupDefaultState(%this);
}
//////////////////////////////////////////////////////////////////////////
function EditorAlignCenterMenu::onSelectItem(%this, %id, %text)
{
// Have the editor align all selected objects by the selected axis.
EWorldEditor.alignByAxis(getField(%this.item[%id], 2));
return true;
}
function EditorAlignCenterMenu::setupDefaultState(%this)
{
// Allow the parent to set the menu's default state
Parent::setupDefaultState(%this);
}
| |
using Signum.Entities.Processes;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.Reflection;
using System;
using System.Linq;
using System.Reflection;
namespace Signum.Entities.MachineLearning
{
[Serializable, EntityKind(EntityKind.Part, EntityData.Master)]
public class NeuralNetworkSettingsEntity : Entity, IPredictorAlgorithmSettings
{
[StringLengthValidator(Max = 100)]
public string? Device { get; set; }
public PredictionType PredictionType { get; set; }
[PreserveOrder]
[NoRepeatValidator]
public MList<NeuralNetworkHidenLayerEmbedded> HiddenLayers { get; set; } = new MList<NeuralNetworkHidenLayerEmbedded>();
public NeuralNetworkActivation OutputActivation { get; set; }
public NeuralNetworkInitializer OutputInitializer { get; set; }
public NeuralNetworkLearner Learner { get; set; }
public NeuralNetworkEvalFunction LossFunction { get; set; }
public NeuralNetworkEvalFunction EvalErrorFunction { get; set; }
[DecimalsValidator(5), NumberIsValidator(ComparisonType.GreaterThan, 0)]
public double LearningRate { get; set; } = 0.2;
[DecimalsValidator(5), NumberIsValidator(ComparisonType.GreaterThan, 0)]
public double? LearningMomentum { get; set; } = null;
public bool? LearningUnitGain { get; set; }
[DecimalsValidator(5), NumberIsValidator(ComparisonType.GreaterThan, 0)]
public double? LearningVarianceMomentum { get; set; } = null;
[NumberIsValidator(ComparisonType.GreaterThan, 0)]
public int MinibatchSize { get; set; } = 1000;
[NumberIsValidator(ComparisonType.GreaterThan, 0)]
public int NumMinibatches { get; set; } = 100;
[Unit("Minibaches"), NumberIsValidator(ComparisonType.GreaterThan, 0)]
public int BestResultFromLast { get; set; } = 10;
[Unit("Minibaches"), NumberIsValidator(ComparisonType.GreaterThan, 0)]
public int SaveProgressEvery { get; set; } = 5;
[Unit("Minibaches"), NumberIsValidator(ComparisonType.GreaterThan, 0)]
public int SaveValidationProgressEvery { get; set; } = 10;
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(SaveValidationProgressEvery))
{
if (SaveValidationProgressEvery % SaveProgressEvery != 0)
{
return PredictorMessage._0ShouldBeDivisibleBy12.NiceToString(pi.NiceName(), ReflectionTools.GetPropertyInfo(() => SaveProgressEvery).NiceName(), SaveProgressEvery);
}
}
if (pi.Name == nameof(OutputActivation))
{
if (OutputActivation == NeuralNetworkActivation.ReLU || OutputActivation == NeuralNetworkActivation.Sigmoid)
{
var p = this.GetParentEntity<PredictorEntity>();
var errors = p.MainQuery.Columns.Where(a => a.Usage == PredictorColumnUsage.Output && a.Encoding.Is(DefaultColumnEncodings.NormalizeZScore)).Select(a => a.Token).ToList();
errors.AddRange(p.SubQueries.SelectMany(sq => sq.Columns).Where(a => a.Usage == PredictorSubQueryColumnUsage.Output && a.Encoding.Is(DefaultColumnEncodings.NormalizeZScore)).Select(a => a.Token).ToList());
if (errors.Any())
return PredictorMessage._0CanNotBe1Because2Use3.NiceToString(pi.NiceName(), OutputActivation.NiceToString(), errors.CommaAnd(), DefaultColumnEncodings.NormalizeZScore.NiceToString());
}
}
string? Validate(NeuralNetworkEvalFunction function)
{
bool lossIsClassification = function == NeuralNetworkEvalFunction.CrossEntropyWithSoftmax || function == NeuralNetworkEvalFunction.ClassificationError;
bool typeIsClassification = this.PredictionType == PredictionType.Classification || this.PredictionType == PredictionType.MultiClassification;
if (lossIsClassification != typeIsClassification)
return PredictorMessage._0IsNotCompatibleWith12.NiceToString(function.NiceToString(), this.NicePropertyName(a => a.PredictionType), this.PredictionType.NiceToString());
return null;
}
if (pi.Name == nameof(LossFunction))
{
return Validate(LossFunction);
}
if (pi.Name == nameof(EvalErrorFunction))
{
return Validate(EvalErrorFunction);
}
return base.PropertyValidation(pi);
}
public IPredictorAlgorithmSettings Clone() => new NeuralNetworkSettingsEntity
{
Device = Device,
PredictionType = PredictionType,
HiddenLayers = HiddenLayers.Select(hl => hl.Clone()).ToMList(),
OutputActivation = OutputActivation,
OutputInitializer = OutputInitializer,
LossFunction = LossFunction,
EvalErrorFunction = EvalErrorFunction,
Learner = Learner,
LearningRate = LearningRate,
LearningMomentum = LearningMomentum,
LearningUnitGain = LearningUnitGain,
LearningVarianceMomentum = LearningVarianceMomentum,
MinibatchSize = MinibatchSize,
NumMinibatches = NumMinibatches,
BestResultFromLast = BestResultFromLast,
SaveProgressEvery = SaveProgressEvery,
SaveValidationProgressEvery = SaveValidationProgressEvery,
};
}
public enum PredictionType
{
Regression,
MultiRegression,
Classification,
MultiClassification,
}
[Serializable]
public class NeuralNetworkHidenLayerEmbedded : EmbeddedEntity
{
[Unit("Neurons")]
public int Size { get; set; }
public NeuralNetworkActivation Activation { get; set; }
public NeuralNetworkInitializer Initializer { get; set; }
internal NeuralNetworkHidenLayerEmbedded Clone() => new NeuralNetworkHidenLayerEmbedded
{
Size = Size,
Activation = Activation,
Initializer = Initializer
};
}
public enum NeuralNetworkActivation
{
None,
ReLU,
Sigmoid,
Tanh
}
public enum NeuralNetworkInitializer
{
Zero,
GlorotNormal,
GlorotUniform,
HeNormal,
HeUniform,
Normal,
TruncateNormal,
Uniform,
Xavier,
}
public enum NeuralNetworkLearner
{
Adam,
AdaDelta,
AdaGrad,
FSAdaGrad,
RMSProp,
MomentumSGD,
SGD,
}
public enum NeuralNetworkEvalFunction
{
CrossEntropyWithSoftmax,
ClassificationError,
SquaredError,
MeanAbsoluteError,
MeanAbsolutePercentageError,
}
[Serializable, EntityKind(EntityKind.Part, EntityData.Transactional)]
public class AutoconfigureNeuralNetworkEntity : Entity, IProcessDataEntity
{
public Lite<PredictorEntity> InitialPredictor { get; set; }
public bool ExploreLearner { get; set; }
public bool ExploreLearningValues { get; set; }
public bool ExploreHiddenLayers { get; set; }
public bool ExploreOutputLayer { get; set; }
public int MaxLayers { get; set; } = 2;
public int MinNeuronsPerLayer { get; set; } = 5;
public int MaxNeuronsPerLayer { get; set; } = 20;
[Unit("seconds")]
public long? OneTrainingDuration { get; set; }
public int Generations { get; set; } = 10;
public int Population { get; set; } = 10;
[Format("p")]
public double SurvivalRate { get; set; } = 0.4;
[Format("p")]
public double InitialMutationProbability { get; set; } = 0.1;
public int? Seed { get; set; }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
internal class OVFTest
{
static public volatile bool rtv;
static OVFTest()
{
rtv = Environment.TickCount != 0;
}
private static sbyte Test_sbyte(sbyte a)
{
try
{
checked
{
#if OP_DIV
a = (sbyte)(a / 0.5);
#elif OP_ADD
a = (sbyte)(a + a);
#elif OP_SUB
a = (sbyte)(-1 - a - a);
#else
a = (sbyte)(a * 2);
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (sbyte)(a / 0.5);
#elif OP_ADD
a = (sbyte)(a + a);
#elif OP_SUB
a = (sbyte)(-1 - a - a);
#else
a = (sbyte)(a * 2);
#endif
}
}
}
private static byte Test_byte(byte a)
{
try
{
checked
{
#if OP_DIV
a = (byte)(a / 0.5);
#elif OP_ADD
a = (byte)(a + a);
#elif OP_SUB
a = (byte)(0 - a - a);
#else
a = (byte)(a * 2);
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (byte)(a / 0.5);
#elif OP_ADD
a = (byte)(a + a);
#elif OP_SUB
a = (byte)(0 - a - a);
#else
a = (byte)(a * 2);
#endif
}
}
}
private static short Test_short(short a)
{
try
{
checked
{
#if OP_DIV
a = (short)(a / 0.5);
#elif OP_ADD
a = (short)(a + a);
#elif OP_SUB
a = (short)(-1 - a - a);
#else
a = (short)(a * 2);
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (short)(a / 0.5);
#elif OP_ADD
a = (short)(a + a);
#elif OP_SUB
a = (short)(-1 - a - a);
#else
a = (short)(a * 2);
#endif
}
}
}
private static ushort Test_ushort(ushort a)
{
try
{
checked
{
#if OP_DIV
a = (ushort)(a / 0.5);
#elif OP_ADD
a = (ushort)(a + a);
#elif OP_SUB
a = (ushort)(0 - a - a);
#else
a = (ushort)(a * 2);
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (ushort)(a / 0.5);
#elif OP_ADD
a = (ushort)(a + a);
#elif OP_SUB
a = (ushort)(0 - a - a);
#else
a = (ushort)(a * 2);
#endif
}
}
}
private static int Test_int(int a)
{
try
{
checked
{
#if OP_DIV
a = (int)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = -1 - a - a;
#else
a = a * 2;
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (int)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = -1 - a - a;
#else
a = a * 2;
#endif
}
}
}
private static uint Test_uint(uint a)
{
try
{
checked
{
#if OP_DIV
a = (uint)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = 0U - a - a;
#else
a = a * 2U;
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (uint)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = 0U - a - a;
#else
a = a * 2U;
#endif
}
}
}
private static long Test_long(long a)
{
try
{
checked
{
#if OP_DIV
a = (long)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = -1L - a - a;
#else
a = a * 2L;
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (long)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = -1L - a - a;
#else
a = a * 2L;
#endif
}
}
}
private static ulong Test_ulong(ulong a)
{
try
{
checked
{
#if OP_DIV
a = (ulong)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = 0UL - a - a;
#else
a = a * 2UL;
#endif
return a;
}
}
catch (System.OverflowException)
{
return a;
}
finally
{
checked
{
#if OP_DIV
a = (ulong)(a / 0.5);
#elif OP_ADD
a = a + a;
#elif OP_SUB
a = 0UL - a - a;
#else
a = a * 2UL;
#endif
}
}
}
private static int Main(string[] args)
{
#if OP_DIV
const string op = "div.ovf";
#elif OP_ADD
const string op = "add.ovf";
#elif OP_SUB
const string op = "sub.ovf";
#else
const string op = "mul.ovf";
#endif
Console.WriteLine("Runtime Checks [OP: {0}]", op);
int check = 8;
try
{
Console.Write("Type 'byte' . . : ");
byte a = Test_byte((byte)(OVFTest.rtv ? 1 + byte.MaxValue / 2 : 0));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
try
{
Console.Write("Type 'sbyte'. . : ");
sbyte a = Test_sbyte((sbyte)(OVFTest.rtv ? 1 + sbyte.MaxValue / 2 : 0));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
try
{
Console.Write("Type 'short'. . : ");
short a = Test_short((short)(OVFTest.rtv ? 1 + short.MaxValue / 2 : 0));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
try
{
Console.Write("Type 'ushort' . : ");
ushort a = Test_ushort((ushort)(OVFTest.rtv ? 1 + ushort.MaxValue / 2 : 0));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
try
{
Console.Write("Type 'int'. . . : ");
int a = Test_int((int)(OVFTest.rtv ? 1 + int.MaxValue / 2 : 0));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
try
{
Console.Write("Type 'uint' . . : ");
uint a = Test_uint((uint)(OVFTest.rtv ? 1U + uint.MaxValue / 2U : 0U));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
try
{
Console.Write("Type 'long' . . : ");
long a = Test_long((long)(OVFTest.rtv ? 1L + long.MaxValue / 2L : 0L));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
try
{
Console.Write("Type 'ulong'. . : ");
ulong a = Test_ulong((ulong)(OVFTest.rtv ? 1UL + ulong.MaxValue / 2UL : 0UL));
Console.WriteLine("failed! - a = " + a);
}
catch (System.OverflowException)
{
Console.WriteLine("passed");
check--;
}
return check == 0 ? 100 : 1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Helios.Buffers;
using Helios.Exceptions;
using Helios.Serialization;
using Helios.Topology;
using Helios.Tracing;
using Helios.Util.Concurrency;
namespace Helios.Net.Connections
{
public class TcpConnection : UnstreamedConnectionBase
{
protected Socket _client;
public TcpConnection(NetworkEventLoop eventLoop, INode node, TimeSpan timeout, IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator, int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
: base(eventLoop, node, timeout, encoder, decoder, allocator, bufferSize)
{
InitClient();
}
public TcpConnection(NetworkEventLoop eventLoop, INode node, IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator, int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
: base(eventLoop, node, encoder, decoder, allocator, bufferSize)
{
InitClient();
}
public TcpConnection(Socket client, int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
: base(bufferSize)
{
InitClient(client);
}
public TcpConnection(Socket client, IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator, int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
: base(bufferSize)
{
InitClient(client);
Encoder = encoder;
Decoder = decoder;
Allocator = allocator;
}
public override TransportType Transport { get { return TransportType.Tcp; } }
public override bool Blocking
{
get { return _client.Blocking; }
set { _client.Blocking = value; }
}
public bool NoDelay
{
get { return _client.NoDelay; }
set { _client.NoDelay = value; }
}
public int Linger
{
get { return _client.LingerState.Enabled ? _client.LingerState.LingerTime : 0; }
set { _client.LingerState = new LingerOption(value > 0, value); }
}
public int SendBufferSize
{
get { return _client.SendBufferSize; }
set { _client.SendBufferSize = value; }
}
public int ReceiveBufferSize
{
get { return _client.ReceiveBufferSize; }
set { _client.ReceiveBufferSize = value; }
}
public bool ReuseAddress
{
get { return !_client.ExclusiveAddressUse; }
set { _client.ExclusiveAddressUse = !value; }
}
public bool KeepAlive
{
get { return ((int)_client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive) == 1); }
set { _client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, value ? 1 : 0); }
}
public override bool IsOpen()
{
var client = _client;
if (client == null) return false;
try
{
return client.Connected;
}
catch //suppress exceptions for when the socket disconnect spins
{
return false;
}
}
public override int Available
{
get
{
if (!IsOpen()) return 0;
return _client.Available;
}
}
#if NET35 || NET40
public override Task<bool> OpenAsync()
{
CheckWasDisposed();
return TaskRunner.Run<bool>(() =>
{
Open();
return true;
});
}
#else
public override async Task<bool> OpenAsync()
{
CheckWasDisposed();
if (IsOpen()) return await Task.Run(() => true);
if (RemoteHost == null || RemoteHost.Host == null)
{
throw new HeliosConnectionException(ExceptionType.NotOpen, "Cannot open a connection to a null Node or null Node.Host");
}
if (RemoteHost.Port <= 0)
{
throw new HeliosConnectionException(ExceptionType.NotOpen, "Cannot open a connection to an invalid port");
}
if (_client == null)
InitClient();
var connectTask = Task.Factory.FromAsync(
(callback, state) => _client.BeginConnect(RemoteHost.Host, RemoteHost.Port, callback, state),
result => _client.EndConnect(result),
TaskCreationOptions.None
);
return await connectTask.ContinueWith(x =>
{
var result = x.IsCompleted && !x.IsFaulted && !x.IsCanceled;
if (result)
{
SetLocal(_client);
InvokeConnectIfNotNull(RemoteHost);
}
return result;
}, TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);
}
#endif
public override void Configure(IConnectionConfig config)
{
if (config.HasOption<int>("receiveBufferSize"))
ReceiveBufferSize = config.GetOption<int>("receiveBufferSize");
if (config.HasOption<int>("sendBufferSize"))
SendBufferSize = config.GetOption<int>("sendBufferSize");
if (config.HasOption<bool>("reuseAddress"))
ReuseAddress = config.GetOption<bool>("reuseAddress");
if (config.HasOption<bool>("tcpNoDelay"))
NoDelay = config.GetOption<bool>("tcpNoDelay");
if (config.HasOption<bool>("keepAlive"))
KeepAlive = config.GetOption<bool>("keepAlive");
if (config.HasOption<bool>("linger") && config.GetOption<bool>("linger"))
Linger = 10;
else
Linger = 0;
if (config.HasOption<TimeSpan>("connectTimeout"))
Timeout = config.GetOption<TimeSpan>("connectTimeout");
}
public override void Open()
{
CheckWasDisposed();
if (IsOpen()) return;
if (RemoteHost == null || RemoteHost.Host == null)
{
throw new HeliosConnectionException(ExceptionType.NotOpen, "Cannot open a connection to a null Node or null Node.Host");
}
if (RemoteHost.Port <= 0)
{
throw new HeliosConnectionException(ExceptionType.NotOpen, "Cannot open a connection to an invalid port");
}
if (_client == null)
InitClient();
var ar = _client.BeginConnect(RemoteHost.Host, RemoteHost.Port, null, null);
if (ar.AsyncWaitHandle.WaitOne(Timeout))
{
try
{
_client.EndConnect(ar);
HeliosTrace.Instance.TcpClientConnectSuccess();
}
catch (SocketException ex)
{
HeliosTrace.Instance.TcpClientConnectFailure(ex.Message);
throw new HeliosConnectionException(ExceptionType.NotOpen, ex);
}
}
else
{
_client.Close();
HeliosTrace.Instance.TcpClientConnectFailure("Timed out on connect");
throw new HeliosConnectionException(ExceptionType.TimedOut, "Timed out on connect");
}
SetLocal(_client);
InvokeConnectIfNotNull(RemoteHost);
}
protected override void BeginReceiveInternal()
{
var receiveState = CreateNetworkState(_client, RemoteHost);
_client.BeginReceive(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ReceiveCallback, receiveState);
}
public override void Close(Exception reason)
{
InvokeDisconnectIfNotNull(RemoteHost, new HeliosConnectionException(ExceptionType.Closed, reason));
if (_client == null || WasDisposed || !IsOpen())
return;
_client.Close();
EventLoop.Shutdown(TimeSpan.FromSeconds(2));
_client = null;
}
public override void Close()
{
Close(null);
}
protected override void SendInternal(byte[] buffer, int index, int length, INode destination)
{
try
{
if (WasDisposed || !_client.Connected)
{
Close();
return;
}
var buf = Allocator.Buffer(length);
buf.WriteBytes(buffer, index, length);
List<IByteBuf> encodedMessages;
Encoder.Encode(this, buf, out encodedMessages);
foreach (var message in encodedMessages)
{
var bytesToSend = message.ToArray();
var bytesSent = 0;
while (bytesSent < bytesToSend.Length)
{
bytesSent += _client.Send(bytesToSend, bytesSent, bytesToSend.Length - bytesSent,
SocketFlags.None);
}
HeliosTrace.Instance.TcpClientSend(bytesSent);
HeliosTrace.Instance.TcpClientSendSuccess();
}
}
catch (SocketException ex)
{
HeliosTrace.Instance.TcpClientSendFailure();
Close(ex);
}
catch (Exception ex)
{
HeliosTrace.Instance.TcpClientSendFailure();
InvokeErrorIfNotNull(ex);
}
}
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (!WasDisposed)
{
if (disposing)
{
if (_client != null)
{
((IDisposable)_client).Dispose();
_client = null;
EventLoop.Dispose();
}
}
}
WasDisposed = true;
}
#endregion
private void InitClient(Socket client)
{
_client = client;
_client.NoDelay = true;
_client.ReceiveTimeout = Timeout.Seconds;
_client.SendTimeout = Timeout.Seconds;
_client.ReceiveBufferSize = BufferSize;
var ipAddress = (IPEndPoint)_client.RemoteEndPoint;
RemoteHost = Binding = NodeBuilder.FromEndpoint(ipAddress);
Local = NodeBuilder.FromEndpoint((IPEndPoint)_client.LocalEndPoint);
}
private void InitClient()
{
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
{
ReceiveTimeout = Timeout.Seconds,
SendTimeout = Timeout.Seconds,
ReceiveBufferSize = BufferSize
};
RemoteHost = Binding;
}
/// <summary>
/// After a TCP connection is successfully established, set the value of the local node
/// to whatever port / IP was assigned.
/// </summary>
protected void SetLocal(Socket client)
{
var localEndpoint = (IPEndPoint)client.LocalEndPoint;
Local = NodeBuilder.FromEndpoint(localEndpoint);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.