context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//------------------------------------------------------------------------------ // <copyright file="XPathParser.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace MS.Internal.Xml.XPath { using System; using System.Xml; using System.Xml.XPath; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; internal class XPathParser { XPathScanner scanner; private XPathParser(XPathScanner scanner) { this.scanner = scanner; } public static AstNode ParseXPathExpresion(string xpathExpresion) { XPathScanner scanner = new XPathScanner(xpathExpresion); XPathParser parser = new XPathParser(scanner); AstNode result = parser.ParseExpresion(null); if (scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(Res.Xp_InvalidToken, scanner.SourceText); } return result; } public static AstNode ParseXPathPattern(string xpathPattern) { XPathScanner scanner = new XPathScanner(xpathPattern); XPathParser parser = new XPathParser(scanner); AstNode result = parser.ParsePattern(null); if (scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(Res.Xp_InvalidToken, scanner.SourceText); } return result; } // --------------- Expresion Parsing ---------------------- //The recursive is like //ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpresion //So put 200 limitation here will max cause about 2000~3000 depth stack. private int parseDepth = 0; private const int MaxParseDepth = 200; private AstNode ParseExpresion(AstNode qyInput) { if (++parseDepth > MaxParseDepth) { throw XPathException.Create(Res.Xp_QueryTooComplex); } AstNode result = ParseOrExpr(qyInput); --parseDepth; return result; } //>> OrExpr ::= ( OrExpr 'or' )? AndExpr private AstNode ParseOrExpr(AstNode qyInput) { AstNode opnd = ParseAndExpr(qyInput); do { if (! TestOp("or")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput)); }while (true); } //>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr private AstNode ParseAndExpr(AstNode qyInput) { AstNode opnd = ParseEqualityExpr(qyInput); do { if (! TestOp("and")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput)); }while (true); } //>> EqualityOp ::= '=' | '!=' //>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr private AstNode ParseEqualityExpr(AstNode qyInput) { AstNode opnd = ParseRelationalExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ : this.scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput)); }while (true); } //>> RelationalOp ::= '<' | '>' | '<=' | '>=' //>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr private AstNode ParseRelationalExpr(AstNode qyInput) { AstNode opnd = ParseAdditiveExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT : this.scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE : this.scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT : this.scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput)); }while (true); } //>> AdditiveOp ::= '+' | '-' //>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr private AstNode ParseAdditiveExpr(AstNode qyInput) { AstNode opnd = ParseMultiplicativeExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS : this.scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput)); }while (true); } //>> MultiplicativeOp ::= '*' | 'div' | 'mod' //>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr private AstNode ParseMultiplicativeExpr(AstNode qyInput) { AstNode opnd = ParseUnaryExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL : TestOp("div") ? Operator.Op.DIV : TestOp("mod") ? Operator.Op.MOD : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput)); }while (true); } //>> UnaryExpr ::= UnionExpr | '-' UnaryExpr private AstNode ParseUnaryExpr(AstNode qyInput) { bool minus = false; while (this.scanner.Kind == XPathScanner.LexKind.Minus) { NextLex(); minus = !minus; } if (minus) { return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1)); } else { return ParseUnionExpr(qyInput); } } //>> UnionExpr ::= ( UnionExpr '|' )? PathExpr private AstNode ParseUnionExpr(AstNode qyInput) { AstNode opnd = ParsePathExpr(qyInput); do { if (this.scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); AstNode opnd2 = ParsePathExpr(qyInput); CheckNodeSet(opnd.ReturnType); CheckNodeSet(opnd2.ReturnType); opnd = new Operator(Operator.Op.UNION, opnd, opnd2); }while (true); } private static bool IsNodeType(XPathScanner scaner) { return ( scaner.Prefix.Length == 0 && ( scaner.Name == "node" || scaner.Name == "text" || scaner.Name == "processing-instruction" || scaner.Name == "comment" ) ); } //>> PathOp ::= '/' | '//' //>> PathExpr ::= LocationPath | //>> FilterExpr ( PathOp RelativeLocationPath )? private AstNode ParsePathExpr(AstNode qyInput) { AstNode opnd; if (IsPrimaryExpr(this.scanner)) { // in this moment we shoud distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr) opnd = ParseFilterExpr(qyInput); if (this.scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); opnd = ParseRelativeLocationPath(opnd); } else if (this.scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } } else { opnd = ParseLocationPath(null); } return opnd; } //>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate private AstNode ParseFilterExpr(AstNode qyInput) { AstNode opnd = ParsePrimaryExpr(qyInput); while (this.scanner.Kind == XPathScanner.LexKind.LBracket) { // opnd must be a query opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } //>> Predicate ::= '[' Expr ']' private AstNode ParsePredicate(AstNode qyInput) { AstNode opnd; // we have predicates. Check that input type is NodeSet CheckNodeSet(qyInput.ReturnType); PassToken(XPathScanner.LexKind.LBracket); opnd = ParseExpresion(qyInput); PassToken(XPathScanner.LexKind.RBracket); return opnd; } //>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath private AstNode ParseLocationPath(AstNode qyInput) { if (this.scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); AstNode opnd = new Root(); if (IsStep(this.scanner.Kind)) { opnd = ParseRelativeLocationPath(opnd); } return opnd; } else if (this.scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root())); } else { return ParseRelativeLocationPath(qyInput); } } // ParseLocationPath //>> PathOp ::= '/' | '//' //>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step private AstNode ParseRelativeLocationPath(AstNode qyInput) { AstNode opnd = qyInput; do { opnd = ParseStep(opnd); if (XPathScanner.LexKind.SlashSlash == this.scanner.Kind) { NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); } else if (XPathScanner.LexKind.Slash == this.scanner.Kind) { NextLex(); } else { break; } } while (true); return opnd; } private static bool IsStep(XPathScanner.LexKind lexKind) { return ( lexKind == XPathScanner.LexKind.Dot || lexKind == XPathScanner.LexKind.DotDot || lexKind == XPathScanner.LexKind.At || lexKind == XPathScanner.LexKind.Axe || lexKind == XPathScanner.LexKind.Star || lexKind == XPathScanner.LexKind.Name // NodeTest is also Name ); } //>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate* private AstNode ParseStep(AstNode qyInput) { AstNode opnd; if (XPathScanner.LexKind.Dot == this.scanner.Kind) { //>> '.' NextLex(); opnd = new Axis(Axis.AxisType.Self, qyInput); } else if (XPathScanner.LexKind.DotDot == this.scanner.Kind) { //>> '..' NextLex(); opnd = new Axis(Axis.AxisType.Parent, qyInput); } else { //>> ( AxisName '::' | '@' )? NodeTest Predicate* Axis.AxisType axisType = Axis.AxisType.Child; switch (this.scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(this.scanner); NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : // axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but othervise Axes doesn't work /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == this.scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } } return opnd; } //>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')' private AstNode ParseNodeTest(AstNode qyInput, Axis.AxisType axisType, XPathNodeType nodeType) { string nodeName, nodePrefix; switch (this.scanner.Kind) { case XPathScanner.LexKind.Name : if (this.scanner.CanBeFunction && IsNodeType(this.scanner)) { nodePrefix = string.Empty; nodeName = string.Empty; nodeType = ( this.scanner.Name == "comment" ? XPathNodeType.Comment : this.scanner.Name == "text" ? XPathNodeType.Text : this.scanner.Name == "node" ? XPathNodeType.All : this.scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction : /* default: */ XPathNodeType.Root ); Debug.Assert(nodeType != XPathNodeType.Root); NextLex(); PassToken(XPathScanner.LexKind.LParens); if (nodeType == XPathNodeType.ProcessingInstruction) { if (this.scanner.Kind != XPathScanner.LexKind.RParens) { //>> 'processing-instruction (' Literal ')' CheckToken(XPathScanner.LexKind.String); nodeName = this.scanner.StringValue; NextLex(); } } PassToken(XPathScanner.LexKind.RParens); } else { nodePrefix = this.scanner.Prefix; nodeName = this.scanner.Name; NextLex(); if (nodeName == "*") { nodeName = string.Empty; } } break; case XPathScanner.LexKind.Star : nodePrefix = string.Empty; nodeName = string.Empty; NextLex(); break; default : throw XPathException.Create(Res.Xp_NodeSetExpected, this.scanner.SourceText); } return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType); } private static bool IsPrimaryExpr(XPathScanner scanner) { return ( scanner.Kind == XPathScanner.LexKind.String || scanner.Kind == XPathScanner.LexKind.Number || scanner.Kind == XPathScanner.LexKind.Dollar || scanner.Kind == XPathScanner.LexKind.LParens || scanner.Kind == XPathScanner.LexKind.Name && scanner.CanBeFunction && ! IsNodeType(scanner) ); } //>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall private AstNode ParsePrimaryExpr(AstNode qyInput) { Debug.Assert(IsPrimaryExpr(this.scanner)); AstNode opnd = null; switch (this.scanner.Kind) { case XPathScanner.LexKind.String: opnd = new Operand(this.scanner.StringValue); NextLex(); break; case XPathScanner.LexKind.Number: opnd = new Operand(this.scanner.NumberValue); NextLex(); break; case XPathScanner.LexKind.Dollar: NextLex(); CheckToken(XPathScanner.LexKind.Name); opnd = new Variable(this.scanner.Name, this.scanner.Prefix); NextLex(); break; case XPathScanner.LexKind.LParens: NextLex(); opnd = ParseExpresion(qyInput); if (opnd.Type != AstNode.AstType.ConstantOperand) { opnd = new Group(opnd); } PassToken(XPathScanner.LexKind.RParens); break; case XPathScanner.LexKind.Name : if (this.scanner.CanBeFunction && ! IsNodeType(this.scanner)) { opnd = ParseMethod(null); } break; } Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex."); return opnd; } private AstNode ParseMethod(AstNode qyInput) { ArrayList argList = new ArrayList(); string name = this.scanner.Name; string prefix = this.scanner.Prefix; PassToken(XPathScanner.LexKind.Name); PassToken(XPathScanner.LexKind.LParens); if (this.scanner.Kind != XPathScanner.LexKind.RParens) { do { argList.Add(ParseExpresion(qyInput)); if (this.scanner.Kind == XPathScanner.LexKind.RParens) { break; } PassToken(XPathScanner.LexKind.Comma); }while (true); } PassToken(XPathScanner.LexKind.RParens); if (prefix.Length == 0) { ParamInfo pi = (ParamInfo) functionTable[name]; if (pi != null) { int argCount = argList.Count; if (argCount < pi.Minargs) { throw XPathException.Create(Res.Xp_InvalidNumArgs, name, this.scanner.SourceText); } if (pi.FType == Function.FunctionType.FuncConcat) { for (int i = 0; i < argCount; i ++) { AstNode arg = (AstNode)argList[i]; if (arg.ReturnType != XPathResultType.String) { arg = new Function(Function.FunctionType.FuncString, arg); } argList[i] = arg; } } else { if (pi.Maxargs < argCount) { throw XPathException.Create(Res.Xp_InvalidNumArgs, name, this.scanner.SourceText); } if (pi.ArgTypes.Length < argCount) { argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs) } for (int i = 0; i < argCount; i ++) { AstNode arg = (AstNode)argList[i]; if ( pi.ArgTypes[i] != XPathResultType.Any && pi.ArgTypes[i] != arg.ReturnType ) { switch (pi.ArgTypes[i]) { case XPathResultType.NodeSet : if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any) ) { throw XPathException.Create(Res.Xp_InvalidArgumentType, name, this.scanner.SourceText); } break; case XPathResultType.String : arg = new Function(Function.FunctionType.FuncString, arg); break; case XPathResultType.Number : arg = new Function(Function.FunctionType.FuncNumber, arg); break; case XPathResultType.Boolean : arg = new Function(Function.FunctionType.FuncBoolean, arg); break; } argList[i] = arg; } } } return new Function(pi.FType, argList); } } return new Function(prefix, name, argList); } // --------------- Pattern Parsing ---------------------- //>> Pattern ::= ( Pattern '|' )? LocationPathPattern private AstNode ParsePattern(AstNode qyInput) { AstNode opnd = ParseLocationPathPattern(qyInput); do { if (this.scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern(qyInput)); }while (true); } //>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern //>> | IdKeyPattern (('/' | '//') RelativePathPattern)? private AstNode ParseLocationPathPattern(AstNode qyInput) { AstNode opnd = null; switch (this.scanner.Kind) { case XPathScanner.LexKind.Slash : NextLex(); opnd = new Root(); if (this.scanner.Kind == XPathScanner.LexKind.Eof || this.scanner.Kind == XPathScanner.LexKind.Union) { return opnd; } break; case XPathScanner.LexKind.SlashSlash : NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root()); break; case XPathScanner.LexKind.Name : if (this.scanner.CanBeFunction) { opnd = ParseIdKeyPattern(qyInput); if (opnd != null) { switch (this.scanner.Kind) { case XPathScanner.LexKind.Slash : NextLex(); break; case XPathScanner.LexKind.SlashSlash : NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); break; default : return opnd; } } } break; } return ParseRelativePathPattern(opnd); } //>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')' private AstNode ParseIdKeyPattern(AstNode qyInput) { Debug.Assert(this.scanner.CanBeFunction); ArrayList argList = new ArrayList(); if (this.scanner.Prefix.Length == 0) { if (this.scanner.Name == "id") { ParamInfo pi = (ParamInfo) functionTable["id"]; NextLex();; PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(this.scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function(pi.FType, argList); } if (this.scanner.Name == "key") { NextLex(); PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(this.scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.Comma); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(this.scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function("", "key", argList); } } return null; } //>> PathOp ::= '/' | '//' //>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern private AstNode ParseRelativePathPattern(AstNode qyInput) { AstNode opnd = ParseStepPattern(qyInput); if (XPathScanner.LexKind.SlashSlash == this.scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } else if (XPathScanner.LexKind.Slash == this.scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(opnd); } return opnd; } //>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate* //>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::' private AstNode ParseStepPattern(AstNode qyInput) { AstNode opnd; Axis.AxisType axisType = Axis.AxisType.Child; switch (this.scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(this.scanner); if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute) { throw XPathException.Create(Res.Xp_InvalidToken, scanner.SourceText); } NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == this.scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } // --------------- Helper methods ---------------------- void CheckToken(XPathScanner.LexKind t) { if (this.scanner.Kind != t) { throw XPathException.Create(Res.Xp_InvalidToken, this.scanner.SourceText); } } void PassToken(XPathScanner.LexKind t) { CheckToken(t); NextLex(); } void NextLex() { this.scanner.NextLex(); } private bool TestOp(string op) { return ( this.scanner.Kind == XPathScanner.LexKind.Name && this.scanner.Prefix.Length == 0 && this.scanner.Name.Equals(op) ); } void CheckNodeSet(XPathResultType t) { if (t != XPathResultType.NodeSet && t != XPathResultType.Any) { throw XPathException.Create(Res.Xp_NodeSetExpected, this.scanner.SourceText); } } // ---------------------------------------------------------------- static readonly XPathResultType[] temparray1 = {}; static readonly XPathResultType[] temparray2 = {XPathResultType.NodeSet}; static readonly XPathResultType[] temparray3 = {XPathResultType.Any}; static readonly XPathResultType[] temparray4 = {XPathResultType.String}; static readonly XPathResultType[] temparray5 = {XPathResultType.String, XPathResultType.String}; static readonly XPathResultType[] temparray6 = {XPathResultType.String, XPathResultType.Number, XPathResultType.Number}; static readonly XPathResultType[] temparray7 = {XPathResultType.String, XPathResultType.String, XPathResultType.String}; static readonly XPathResultType[] temparray8 = {XPathResultType.Boolean}; static readonly XPathResultType[] temparray9 = {XPathResultType.Number}; private class ParamInfo { private Function.FunctionType ftype; private int minargs; private int maxargs; private XPathResultType[] argTypes; public Function.FunctionType FType { get { return this.ftype; } } public int Minargs { get { return this.minargs; } } public int Maxargs { get { return this.maxargs; } } public XPathResultType[] ArgTypes { get { return this.argTypes; } } internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes) { this.ftype = ftype; this.minargs = minargs; this.maxargs = maxargs; this.argTypes = argTypes; } } //ParamInfo private static Hashtable functionTable = CreateFunctionTable(); private static Hashtable CreateFunctionTable(){ Hashtable table = new Hashtable(36); table.Add("last" , new ParamInfo(Function.FunctionType.FuncLast , 0, 0, temparray1)); table.Add("position" , new ParamInfo(Function.FunctionType.FuncPosition , 0, 0, temparray1)); table.Add("name" , new ParamInfo(Function.FunctionType.FuncName , 0, 1, temparray2)); table.Add("namespace-uri" , new ParamInfo(Function.FunctionType.FuncNameSpaceUri , 0, 1, temparray2)); table.Add("local-name" , new ParamInfo(Function.FunctionType.FuncLocalName , 0, 1, temparray2)); table.Add("count" , new ParamInfo(Function.FunctionType.FuncCount , 1, 1, temparray2)); table.Add("id" , new ParamInfo(Function.FunctionType.FuncID , 1, 1, temparray3)); table.Add("string" , new ParamInfo(Function.FunctionType.FuncString , 0, 1, temparray3)); table.Add("concat" , new ParamInfo(Function.FunctionType.FuncConcat , 2, 100, temparray4)); table.Add("starts-with" , new ParamInfo(Function.FunctionType.FuncStartsWith , 2, 2, temparray5)); table.Add("contains" , new ParamInfo(Function.FunctionType.FuncContains , 2, 2, temparray5)); table.Add("substring-before" , new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, temparray5)); table.Add("substring-after" , new ParamInfo(Function.FunctionType.FuncSubstringAfter , 2, 2, temparray5)); table.Add("substring" , new ParamInfo(Function.FunctionType.FuncSubstring , 2, 3, temparray6)); table.Add("string-length" , new ParamInfo(Function.FunctionType.FuncStringLength , 0, 1, temparray4)); table.Add("normalize-space" , new ParamInfo(Function.FunctionType.FuncNormalize , 0, 1, temparray4)); table.Add("translate" , new ParamInfo(Function.FunctionType.FuncTranslate , 3, 3, temparray7)); table.Add("boolean" , new ParamInfo(Function.FunctionType.FuncBoolean , 1, 1, temparray3)); table.Add("not" , new ParamInfo(Function.FunctionType.FuncNot , 1, 1, temparray8)); table.Add("true" , new ParamInfo(Function.FunctionType.FuncTrue , 0, 0 ,temparray8)); table.Add("false" , new ParamInfo(Function.FunctionType.FuncFalse , 0, 0, temparray8)); table.Add("lang" , new ParamInfo(Function.FunctionType.FuncLang , 1, 1, temparray4)); table.Add("number" , new ParamInfo(Function.FunctionType.FuncNumber , 0, 1, temparray3)); table.Add("sum" , new ParamInfo(Function.FunctionType.FuncSum , 1, 1, temparray2)); table.Add("floor" , new ParamInfo(Function.FunctionType.FuncFloor , 1, 1, temparray9)); table.Add("ceiling" , new ParamInfo(Function.FunctionType.FuncCeiling , 1, 1, temparray9)); table.Add("round" , new ParamInfo(Function.FunctionType.FuncRound , 1, 1, temparray9)); return table; } private static Hashtable AxesTable = CreateAxesTable(); private static Hashtable CreateAxesTable() { Hashtable table = new Hashtable(13); table.Add("ancestor" , Axis.AxisType.Ancestor ); table.Add("ancestor-or-self" , Axis.AxisType.AncestorOrSelf ); table.Add("attribute" , Axis.AxisType.Attribute ); table.Add("child" , Axis.AxisType.Child ); table.Add("descendant" , Axis.AxisType.Descendant ); table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf ); table.Add("following" , Axis.AxisType.Following ); table.Add("following-sibling" , Axis.AxisType.FollowingSibling ); table.Add("namespace" , Axis.AxisType.Namespace ); table.Add("parent" , Axis.AxisType.Parent ); table.Add("preceding" , Axis.AxisType.Preceding ); table.Add("preceding-sibling" , Axis.AxisType.PrecedingSibling ); table.Add("self" , Axis.AxisType.Self ); return table; } private Axis.AxisType GetAxis(XPathScanner scaner) { Debug.Assert(scaner.Kind == XPathScanner.LexKind.Axe); object axis = AxesTable[scaner.Name]; if (axis == null) { throw XPathException.Create(Res.Xp_InvalidToken, scanner.SourceText); } return (Axis.AxisType) axis; } } }
// 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; using System.Text; using Microsoft.Xml; using Microsoft.Xml.Schema; using Microsoft.Xml.XPath; using System.Diagnostics; namespace MS.Internal.Xml.Cache { /// <summary> /// The 0th node in each page contains a non-null reference to an XPathNodePageInfo internal class that provides /// information about that node's page. The other fields in the 0th node are undefined and should never /// be used. /// </summary> sealed internal class XPathNodePageInfo { private int _pageNum; private int _nodeCount; private XPathNode[] _pagePrev; private XPathNode[] _pageNext; /// <summary> /// Constructor. /// </summary> public XPathNodePageInfo(XPathNode[] pagePrev, int pageNum) { _pagePrev = pagePrev; _pageNum = pageNum; _nodeCount = 1; // Every node page contains PageInfo at 0th position } /// <summary> /// Return the sequential page number of the page containing nodes that share this information atom. /// </summary> public int PageNumber { get { return _pageNum; } } /// <summary> /// Return the number of nodes allocated in this page. /// </summary> public int NodeCount { get { return _nodeCount; } set { _nodeCount = value; } } /// <summary> /// Return the previous node page in the document. /// </summary> public XPathNode[] PreviousPage { get { return _pagePrev; } } /// <summary> /// Return the next node page in the document. /// </summary> public XPathNode[] NextPage { get { return _pageNext; } set { _pageNext = value; } } } /// <summary> /// There is a great deal of redundancy in typical Xml documents. Even in documents with thousands or millions /// of nodes, there are a small number of common names and types. And since nodes are allocated in pages in /// document order, nodes on the same page with the same name and type are likely to have the same sibling and /// parent pages as well. /// Redundant information is shared by creating immutable, atomized objects. This is analogous to the /// string.Intern() operation. If a node's name, type, or parent/sibling pages are modified, then a new /// InfoAtom needs to be obtained, since other nodes may still be referencing the old InfoAtom. /// </summary> sealed internal class XPathNodeInfoAtom { private string _localName; private string _namespaceUri; private string _prefix; private string _baseUri; private XPathNode[] _pageParent; private XPathNode[] _pageSibling; private XPathNode[] _pageSimilar; private XPathDocument _doc; private int _lineNumBase; private int _linePosBase; private int _hashCode; private int _localNameHash; private XPathNodeInfoAtom _next; private XPathNodePageInfo _pageInfo; /// <summary> /// Construct information for the 0th node in each page. The only field which is defined is this.pageInfo, /// and it contains information about that page (pageNum, nextPage, etc.). /// </summary> public XPathNodeInfoAtom(XPathNodePageInfo pageInfo) { _pageInfo = pageInfo; } /// <summary> /// Construct a new shared information atom. This method should only be used by the XNodeInfoTable. /// </summary> public XPathNodeInfoAtom(string localName, string namespaceUri, string prefix, string baseUri, XPathNode[] pageParent, XPathNode[] pageSibling, XPathNode[] pageSimilar, XPathDocument doc, int lineNumBase, int linePosBase) { Init(localName, namespaceUri, prefix, baseUri, pageParent, pageSibling, pageSimilar, doc, lineNumBase, linePosBase); } /// <summary> /// Initialize an existing shared information atom. This method should only be used by the XNodeInfoTable. /// </summary> public void Init(string localName, string namespaceUri, string prefix, string baseUri, XPathNode[] pageParent, XPathNode[] pageSibling, XPathNode[] pageSimilar, XPathDocument doc, int lineNumBase, int linePosBase) { Debug.Assert(localName != null && namespaceUri != null && prefix != null && doc != null); _localName = localName; _namespaceUri = namespaceUri; _prefix = prefix; _baseUri = baseUri; _pageParent = pageParent; _pageSibling = pageSibling; _pageSimilar = pageSimilar; _doc = doc; _lineNumBase = lineNumBase; _linePosBase = linePosBase; _next = null; _pageInfo = null; _hashCode = 0; _localNameHash = 0; for (int i = 0; i < _localName.Length; i++) _localNameHash += (_localNameHash << 7) ^ _localName[i]; } /// <summary> /// Returns information about the node page. Only the 0th node on each page has this property defined. /// </summary> public XPathNodePageInfo PageInfo { get { return _pageInfo; } } /// <summary> /// Return the local name part of nodes that share this information atom. /// </summary> public string LocalName { get { return _localName; } } /// <summary> /// Return the namespace name part of nodes that share this information atom. /// </summary> public string NamespaceUri { get { return _namespaceUri; } } /// <summary> /// Return the prefix name part of nodes that share this information atom. /// </summary> public string Prefix { get { return _prefix; } } /// <summary> /// Return the base Uri of nodes that share this information atom. /// </summary> public string BaseUri { get { return _baseUri; } } /// <summary> /// Return the page containing the next sibling of nodes that share this information atom. /// </summary> public XPathNode[] SiblingPage { get { return _pageSibling; } } /// <summary> /// Return the page containing the next element having a name which has same hashcode as this element. /// </summary> public XPathNode[] SimilarElementPage { get { return _pageSimilar; } } /// <summary> /// Return the page containing the parent of nodes that share this information atom. /// </summary> public XPathNode[] ParentPage { get { return _pageParent; } } /// <summary> /// Return the page containing the owner document of nodes that share this information atom. /// </summary> public XPathDocument Document { get { return _doc; } } /// <summary> /// Return the line number to which a line number offset stored in the XPathNode is added. /// </summary> public int LineNumberBase { get { return _lineNumBase; } } /// <summary> /// Return the line position to which a line position offset stored in the XPathNode is added. /// </summary> public int LinePositionBase { get { return _linePosBase; } } /// <summary> /// Return cached hash code of the local name of nodes which share this information atom. /// </summary> public int LocalNameHashCode { get { return _localNameHash; } } /// <summary> /// Link together InfoAtoms that hash to the same hashtable bucket (should only be used by XPathNodeInfoTable) /// </summary> public XPathNodeInfoAtom Next { get { return _next; } set { _next = value; } } /// <summary> /// Return this information atom's hash code, previously computed for performance. /// </summary> public override int GetHashCode() { if (_hashCode == 0) { int hashCode; // Start with local name hashCode = _localNameHash; // Add page indexes if (_pageSibling != null) hashCode += (hashCode << 7) ^ _pageSibling[0].PageInfo.PageNumber; if (_pageParent != null) hashCode += (hashCode << 7) ^ _pageParent[0].PageInfo.PageNumber; if (_pageSimilar != null) hashCode += (hashCode << 7) ^ _pageSimilar[0].PageInfo.PageNumber; // Save hashcode. Don't save 0, so that it won't ever be recomputed. _hashCode = ((hashCode == 0) ? 1 : hashCode); } return _hashCode; } /// <summary> /// Return true if this InfoAtom has the same values as another InfoAtom. /// </summary> public override bool Equals(object other) { XPathNodeInfoAtom that = other as XPathNodeInfoAtom; Debug.Assert(that != null); Debug.Assert((object)_doc == (object)that._doc); Debug.Assert(_pageInfo == null); // Assume that name parts are atomized if (this.GetHashCode() == that.GetHashCode()) { if ((object)_localName == (object)that._localName && (object)_pageSibling == (object)that._pageSibling && (object)_namespaceUri == (object)that._namespaceUri && (object)_pageParent == (object)that._pageParent && (object)_pageSimilar == (object)that._pageSimilar && (object)_prefix == (object)that._prefix && (object)_baseUri == (object)that._baseUri && _lineNumBase == that._lineNumBase && _linePosBase == that._linePosBase) { return true; } } return false; } /// <summary> /// Return InfoAtom formatted as a string: /// hash=xxx, {http://my.com}foo:bar, parent=1, sibling=1, lineNum=0, linePos=0 /// </summary> public override string ToString() { StringBuilder bldr = new StringBuilder(); bldr.Append("hash="); bldr.Append(GetHashCode()); bldr.Append(", "); if (_localName.Length != 0) { bldr.Append('{'); bldr.Append(_namespaceUri); bldr.Append('}'); if (_prefix.Length != 0) { bldr.Append(_prefix); bldr.Append(':'); } bldr.Append(_localName); bldr.Append(", "); } if (_pageParent != null) { bldr.Append("parent="); bldr.Append(_pageParent[0].PageInfo.PageNumber); bldr.Append(", "); } if (_pageSibling != null) { bldr.Append("sibling="); bldr.Append(_pageSibling[0].PageInfo.PageNumber); bldr.Append(", "); } if (_pageSimilar != null) { bldr.Append("similar="); bldr.Append(_pageSimilar[0].PageInfo.PageNumber); bldr.Append(", "); } bldr.Append("lineNum="); bldr.Append(_lineNumBase); bldr.Append(", "); bldr.Append("linePos="); bldr.Append(_linePosBase); return bldr.ToString(); } } /// <summary> /// An atomization table for XPathNodeInfoAtom. /// </summary> sealed internal class XPathNodeInfoTable { private XPathNodeInfoAtom[] _hashTable; private int _sizeTable; private XPathNodeInfoAtom _infoCached; #if DEBUG private const int DefaultTableSize = 2; #else private const int DefaultTableSize = 32; #endif /// <summary> /// Constructor. /// </summary> public XPathNodeInfoTable() { _hashTable = new XPathNodeInfoAtom[DefaultTableSize]; _sizeTable = 0; } /// <summary> /// Create a new XNodeInfoAtom and ensure it is atomized in the table. /// </summary> public XPathNodeInfoAtom Create(string localName, string namespaceUri, string prefix, string baseUri, XPathNode[] pageParent, XPathNode[] pageSibling, XPathNode[] pageSimilar, XPathDocument doc, int lineNumBase, int linePosBase) { XPathNodeInfoAtom info; // If this.infoCached already exists, then reuse it; else create new InfoAtom if (_infoCached == null) { info = new XPathNodeInfoAtom(localName, namespaceUri, prefix, baseUri, pageParent, pageSibling, pageSimilar, doc, lineNumBase, linePosBase); } else { info = _infoCached; _infoCached = info.Next; info.Init(localName, namespaceUri, prefix, baseUri, pageParent, pageSibling, pageSimilar, doc, lineNumBase, linePosBase); } return Atomize(info); } /// <summary> /// Add a shared information item to the atomization table. If a matching item already exists, then that /// instance is returned. Otherwise, a new item is created. Thus, if itemX and itemY have both been added /// to the same InfoTable: /// 1. itemX.Equals(itemY) != true /// 2. (object) itemX != (object) itemY /// </summary> private XPathNodeInfoAtom Atomize(XPathNodeInfoAtom info) { XPathNodeInfoAtom infoNew, infoNext; // Search for existing XNodeInfoAtom in the table infoNew = _hashTable[info.GetHashCode() & (_hashTable.Length - 1)]; while (infoNew != null) { if (info.Equals(infoNew)) { // Found existing atom, so return that. Reuse "info". info.Next = _infoCached; _infoCached = info; return infoNew; } infoNew = infoNew.Next; } // Expand table and rehash if necessary if (_sizeTable >= _hashTable.Length) { XPathNodeInfoAtom[] oldTable = _hashTable; _hashTable = new XPathNodeInfoAtom[oldTable.Length * 2]; for (int i = 0; i < oldTable.Length; i++) { infoNew = oldTable[i]; while (infoNew != null) { infoNext = infoNew.Next; AddInfo(infoNew); infoNew = infoNext; } } } // Can't find an existing XNodeInfoAtom, so use the one that was passed in AddInfo(info); return info; } /// <summary> /// Add a previously constructed InfoAtom to the table. If a collision occurs, then insert "info" /// as the head of a linked list. /// </summary> private void AddInfo(XPathNodeInfoAtom info) { int idx = info.GetHashCode() & (_hashTable.Length - 1); info.Next = _hashTable[idx]; _hashTable[idx] = info; _sizeTable++; } /// <summary> /// Return InfoAtomTable formatted as a string. /// </summary> public override string ToString() { StringBuilder bldr = new StringBuilder(); XPathNodeInfoAtom infoAtom; for (int i = 0; i < _hashTable.Length; i++) { bldr.AppendFormat("{0,4}: ", i); infoAtom = _hashTable[i]; while (infoAtom != null) { if ((object)infoAtom != (object)_hashTable[i]) bldr.Append("\n "); bldr.Append(infoAtom); infoAtom = infoAtom.Next; } bldr.Append('\n'); } return bldr.ToString(); } } }
using PlayFab.PfEditor.EditorModels; using PlayFab.PfEditor.Json; using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; namespace PlayFab.PfEditor { [InitializeOnLoad] public class PlayFabEditorDataService : UnityEditor.Editor { #region EditorPref data classes public class PlayFab_DeveloperAccountDetails { public static string Name = "PlayFab_DeveloperAccountDetails"; public string email; public string devToken; public List<Studio> studios; public PlayFab_DeveloperAccountDetails() { studios = null; // Null means not fetched, empty is a possible return result from GetStudios } } public class PlayFab_DeveloperEnvironmentDetails { public static string Name = "PlayFab_DeveloperEnvironmentDetails"; public string selectedStudio; public Dictionary<string, string> titleData; public Dictionary<string, string> titleInternalData; public string sdkPath; public string edexPath; public string localCloudScriptPath; public PlayFab_DeveloperEnvironmentDetails() { titleData = new Dictionary<string, string>(); titleInternalData = new Dictionary<string, string>(); } } public class PlayFab_SharedSettingsProxy { private readonly PropertyInfo _titleId; private readonly PropertyInfo _developerSecretKey; private readonly PropertyInfo _webRequestType; private readonly PropertyInfo _compressApiData; private readonly PropertyInfo _keepAlive; private readonly PropertyInfo _timeOut; public string TitleId { get { return (string)_titleId.GetValue(null, null); } set { _titleId.SetValue(null, value, null); } } public string DeveloperSecretKey { get { return (string)_developerSecretKey.GetValue(null, null); } set { _developerSecretKey.SetValue(null, value, null); } } public PlayFabEditorSettings.WebRequestType WebRequestType { get { return (PlayFabEditorSettings.WebRequestType)_webRequestType.GetValue(null, null); } set { _webRequestType.SetValue(null, (int)value, null); } } public bool CompressApiData { get { return (bool)_compressApiData.GetValue(null, null); } set { _compressApiData.SetValue(null, value, null); } } public bool KeepAlive { get { return (bool)_keepAlive.GetValue(null, null); } set { _keepAlive.SetValue(null, value, null); } } public int TimeOut { get { return (int)_timeOut.GetValue(null, null); } set { _timeOut.SetValue(null, value, null); } } public PlayFab_SharedSettingsProxy() { var playFabSettingsType = PlayFabEditorSDKTools.GetPlayFabSettings(); if (playFabSettingsType == null) return; var settingProperties = playFabSettingsType.GetProperties(); foreach (var eachProperty in settingProperties) { var lcName = eachProperty.Name.ToLowerInvariant(); switch (lcName) { case "titleid": _titleId = eachProperty; break; case "developersecretkey": _developerSecretKey = eachProperty; break; case "requesttype": _webRequestType = eachProperty; break; case "compressapidata": _compressApiData = eachProperty; break; case "requestkeepalive": _keepAlive = eachProperty; break; case "requesttimeout": _timeOut = eachProperty; break; } } } } public class PlayFab_EditorSettings { public static string Name = "PlayFab_EditorSettings"; private bool _isEdExShown; private string _latestSdkVersion; private string _latestEdExVersion; private DateTime _lastSdkVersionCheck; private DateTime _lastEdExVersionCheck; public bool isEdExShown { get { return _isEdExShown; } set { _isEdExShown = value; Save(); } } public string latestSdkVersion { get { return _latestSdkVersion; } set { _latestSdkVersion = value; _lastSdkVersionCheck = DateTime.UtcNow; Save(); } } public string latestEdExVersion { get { return _latestEdExVersion; } set { _latestEdExVersion = value; _lastEdExVersionCheck = DateTime.UtcNow; Save(); } } public DateTime lastSdkVersionCheck { get { return _lastSdkVersionCheck; } } public DateTime lastEdExVersionCheck { get { return _lastEdExVersionCheck; } } public static void Save() { SaveToEditorPrefs(EditorSettings, Name); } } public class PlayFab_EditorView { public static string Name = "PlayFab_EditorView"; private int _currentMainMenu; private int _currentSubMenu; public int currentMainMenu { get { return _currentMainMenu; } set { _currentMainMenu = value; Save(); } } public int currentSubMenu { get { return _currentSubMenu; } set { _currentSubMenu = value; Save(); } } private static void Save() { SaveToEditorPrefs(EditorView, Name); } } #endregion EditorPref data classes public static PlayFab_DeveloperAccountDetails AccountDetails; public static PlayFab_DeveloperEnvironmentDetails EnvDetails; public static PlayFab_SharedSettingsProxy SharedSettings = new PlayFab_SharedSettingsProxy(); public static PlayFab_EditorSettings EditorSettings; public static PlayFab_EditorView EditorView; private static string KeyPrefix { get { var dataPath = Application.dataPath; var lastIndex = dataPath.LastIndexOf('/'); var secondToLastIndex = dataPath.LastIndexOf('/', lastIndex - 1); return dataPath.Substring(secondToLastIndex, lastIndex - secondToLastIndex); } } private static bool _IsDataLoaded = false; public static bool IsDataLoaded { get { return _IsDataLoaded && AccountDetails != null && EnvDetails != null && EditorSettings != null && EditorView != null; } } public static Title ActiveTitle { get { if (AccountDetails != null && AccountDetails.studios != null && AccountDetails.studios.Count > 0 && EnvDetails != null) { if (string.IsNullOrEmpty(EnvDetails.selectedStudio) || EnvDetails.selectedStudio == PlayFabEditorHelper.STUDIO_OVERRIDE) return new Title { Id = SharedSettings.TitleId, SecretKey = SharedSettings.DeveloperSecretKey, GameManagerUrl = PlayFabEditorHelper.GAMEMANAGER_URL }; if (string.IsNullOrEmpty(EnvDetails.selectedStudio) || string.IsNullOrEmpty(SharedSettings.TitleId)) return null; int studioIndex; int titleIndex; if (DoesTitleExistInStudios(SharedSettings.TitleId, out studioIndex, out titleIndex)) return AccountDetails.studios[studioIndex].Titles[titleIndex]; } return null; } } private static void SaveToEditorPrefs(object obj, string key) { var json = JsonWrapper.SerializeObject(obj); EditorPrefs.SetString(KeyPrefix + key, json); } public static void SaveAccountDetails() { SaveToEditorPrefs(AccountDetails, PlayFab_DeveloperAccountDetails.Name); } public static void SaveEnvDetails(bool updateToScriptableObj = true) { SaveToEditorPrefs(EnvDetails, PlayFab_DeveloperEnvironmentDetails.Name); if (updateToScriptableObj) UpdateScriptableObject(); } private static TResult LoadFromEditorPrefs<TResult>(string key) where TResult : class, new() { if (!EditorPrefs.HasKey(KeyPrefix + key)) return new TResult(); var serialized = EditorPrefs.GetString(KeyPrefix + key); var result = JsonWrapper.DeserializeObject<TResult>(serialized); if (result != null) return JsonWrapper.DeserializeObject<TResult>(serialized); return new TResult(); } public static void LoadAllData() { if (IsDataLoaded) return; AccountDetails = LoadFromEditorPrefs<PlayFab_DeveloperAccountDetails>(PlayFab_DeveloperAccountDetails.Name); EnvDetails = LoadFromEditorPrefs<PlayFab_DeveloperEnvironmentDetails>(PlayFab_DeveloperEnvironmentDetails.Name); EditorSettings = LoadFromEditorPrefs<PlayFab_EditorSettings>(PlayFab_EditorSettings.Name); EditorView = LoadFromEditorPrefs<PlayFab_EditorView>(PlayFab_EditorView.Name); _IsDataLoaded = true; PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnDataLoaded, "Complete"); } private static void UpdateScriptableObject() { var playfabSettingsType = PlayFabEditorSDKTools.GetPlayFabSettings(); if (playfabSettingsType == null || !PlayFabEditorSDKTools.IsInstalled || !PlayFabEditorSDKTools.isSdkSupported) return; var props = playfabSettingsType.GetProperties(); foreach (var property in props) { switch (property.Name.ToLowerInvariant()) { case "productionenvironmenturl": property.SetValue(null, PlayFabEditorHelper.TITLE_ENDPOINT, null); break; } } var getSoMethod = playfabSettingsType.GetMethod("GetSharedSettingsObjectPrivate", BindingFlags.NonPublic | BindingFlags.Static); if (getSoMethod != null) { var so = getSoMethod.Invoke(null, new object[0]) as ScriptableObject; if (so != null) EditorUtility.SetDirty(so); } AssetDatabase.SaveAssets(); } public static void RemoveEditorPrefs() { EditorPrefs.DeleteKey(KeyPrefix + PlayFab_EditorSettings.Name); EditorPrefs.DeleteKey(KeyPrefix + PlayFab_DeveloperEnvironmentDetails.Name); EditorPrefs.DeleteKey(KeyPrefix + PlayFab_DeveloperAccountDetails.Name); EditorPrefs.DeleteKey(KeyPrefix + PlayFab_EditorView.Name); } public static bool DoesTitleExistInStudios(string searchFor) //out Studio studio { if (AccountDetails.studios == null) return false; searchFor = searchFor.ToLower(); foreach (var studio in AccountDetails.studios) if (studio.Titles != null) foreach (var title in studio.Titles) if (title.Id.ToLower() == searchFor) return true; return false; } private static bool DoesTitleExistInStudios(string searchFor, out int studioIndex, out int titleIndex) //out Studio studio { studioIndex = 0; // corresponds to our _OVERRIDE_ titleIndex = -1; if (AccountDetails.studios == null) return false; for (var studioIdx = 0; studioIdx < AccountDetails.studios.Count; studioIdx++) { for (var titleIdx = 0; titleIdx < AccountDetails.studios[studioIdx].Titles.Length; titleIdx++) { if (AccountDetails.studios[studioIdx].Titles[titleIdx].Id.ToLower() == searchFor.ToLower()) { studioIndex = studioIdx; titleIndex = titleIdx; return true; } } } return false; } public static void RefreshStudiosList() { if (AccountDetails.studios != null) AccountDetails.studios.Clear(); PlayFabEditorApi.GetStudios(new GetStudiosRequest(), (getStudioResult) => { if (AccountDetails.studios == null) AccountDetails.studios = new List<Studio>(); foreach (var eachStudio in getStudioResult.Studios) AccountDetails.studios.Add(eachStudio); AccountDetails.studios.Add(Studio.OVERRIDE); SaveAccountDetails(); }, PlayFabEditorHelper.SharedErrorCallback); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Input; namespace Avalonia.Controls { /// <summary> /// Defines vertical or horizontal orientation. /// </summary> public enum Orientation { /// <summary> /// Vertical orientation. /// </summary> Vertical, /// <summary> /// Horizontal orientation. /// </summary> Horizontal, } /// <summary> /// A panel which lays out its children horizontally or vertically. /// </summary> public class StackPanel : Panel, INavigableContainer { /// <summary> /// Defines the <see cref="Gap"/> property. /// </summary> public static readonly StyledProperty<double> GapProperty = AvaloniaProperty.Register<StackPanel, double>(nameof(Gap)); /// <summary> /// Defines the <see cref="Orientation"/> property. /// </summary> public static readonly StyledProperty<Orientation> OrientationProperty = AvaloniaProperty.Register<StackPanel, Orientation>(nameof(Orientation)); /// <summary> /// Initializes static members of the <see cref="StackPanel"/> class. /// </summary> static StackPanel() { AffectsMeasure(GapProperty); AffectsMeasure(OrientationProperty); } /// <summary> /// Gets or sets the size of the gap to place between child controls. /// </summary> public double Gap { get { return GetValue(GapProperty); } set { SetValue(GapProperty, value); } } /// <summary> /// Gets or sets the orientation in which child controls will be layed out. /// </summary> public Orientation Orientation { get { return GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } /// <summary> /// Gets the next control in the specified direction. /// </summary> /// <param name="direction">The movement direction.</param> /// <param name="from">The control from which movement begins.</param> /// <returns>The control.</returns> IInputElement INavigableContainer.GetControl(NavigationDirection direction, IInputElement from) { var fromControl = from as IControl; return (fromControl != null) ? GetControlInDirection(direction, fromControl) : null; } /// <summary> /// Gets the next control in the specified direction. /// </summary> /// <param name="direction">The movement direction.</param> /// <param name="from">The control from which movement begins.</param> /// <returns>The control.</returns> protected virtual IInputElement GetControlInDirection(NavigationDirection direction, IControl from) { var horiz = Orientation == Orientation.Horizontal; int index = Children.IndexOf((IControl)from); switch (direction) { case NavigationDirection.First: index = 0; break; case NavigationDirection.Last: index = Children.Count - 1; break; case NavigationDirection.Next: ++index; break; case NavigationDirection.Previous: --index; break; case NavigationDirection.Left: index = horiz ? index - 1 : -1; break; case NavigationDirection.Right: index = horiz ? index + 1 : -1; break; case NavigationDirection.Up: index = horiz ? -1 : index - 1; break; case NavigationDirection.Down: index = horiz ? -1 : index + 1; break; default: index = -1; break; } if (index >= 0 && index < Children.Count) { return Children[index]; } else { return null; } } /// <summary> /// Measures the control. /// </summary> /// <param name="availableSize">The available size.</param> /// <returns>The desired size of the control.</returns> protected override Size MeasureOverride(Size availableSize) { double childAvailableWidth = double.PositiveInfinity; double childAvailableHeight = double.PositiveInfinity; if (Orientation == Orientation.Vertical) { childAvailableWidth = availableSize.Width; if (!double.IsNaN(Width)) { childAvailableWidth = Width; } childAvailableWidth = Math.Min(childAvailableWidth, MaxWidth); childAvailableWidth = Math.Max(childAvailableWidth, MinWidth); } else { childAvailableHeight = availableSize.Height; if (!double.IsNaN(Height)) { childAvailableHeight = Height; } childAvailableHeight = Math.Min(childAvailableHeight, MaxHeight); childAvailableHeight = Math.Max(childAvailableHeight, MinHeight); } double measuredWidth = 0; double measuredHeight = 0; double gap = Gap; foreach (Control child in Children) { child.Measure(new Size(childAvailableWidth, childAvailableHeight)); Size size = child.DesiredSize; if (Orientation == Orientation.Vertical) { measuredHeight += size.Height + gap; measuredWidth = Math.Max(measuredWidth, size.Width); } else { measuredWidth += size.Width + gap; measuredHeight = Math.Max(measuredHeight, size.Height); } } return new Size(measuredWidth, measuredHeight); } /// <summary> /// Arranges the control's children. /// </summary> /// <param name="finalSize">The size allocated to the control.</param> /// <returns>The space taken.</returns> protected override Size ArrangeOverride(Size finalSize) { var orientation = Orientation; double arrangedWidth = finalSize.Width; double arrangedHeight = finalSize.Height; double gap = Gap; if (Orientation == Orientation.Vertical) { arrangedHeight = 0; } else { arrangedWidth = 0; } foreach (Control child in Children) { double childWidth = child.DesiredSize.Width; double childHeight = child.DesiredSize.Height; if (orientation == Orientation.Vertical) { double width = Math.Max(childWidth, arrangedWidth); Rect childFinal = new Rect(0, arrangedHeight, width, childHeight); ArrangeChild(child, childFinal, finalSize, orientation); arrangedWidth = Math.Max(arrangedWidth, childWidth); arrangedHeight += childHeight + gap; } else { double height = Math.Max(childHeight, arrangedHeight); Rect childFinal = new Rect(arrangedWidth, 0, childWidth, height); ArrangeChild(child, childFinal, finalSize, orientation); arrangedWidth += childWidth + gap; arrangedHeight = Math.Max(arrangedHeight, childHeight); } } if (orientation == Orientation.Vertical) { arrangedHeight = Math.Max(arrangedHeight - gap, finalSize.Height); } else { arrangedWidth = Math.Max(arrangedWidth - gap, finalSize.Width); } return new Size(arrangedWidth, arrangedHeight); } internal virtual void ArrangeChild( IControl child, Rect rect, Size panelSize, Orientation orientation) { child.Arrange(rect); } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected]) // 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class WhileStatement : ConditionalStatement { protected Block _block; protected Block _orBlock; protected Block _thenBlock; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public WhileStatement CloneNode() { return (WhileStatement)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public WhileStatement CleanClone() { return (WhileStatement)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.WhileStatement; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnWhileStatement(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( WhileStatement)node; if (!Node.Matches(_modifier, other._modifier)) return NoMatch("WhileStatement._modifier"); if (!Node.Matches(_condition, other._condition)) return NoMatch("WhileStatement._condition"); if (!Node.Matches(_block, other._block)) return NoMatch("WhileStatement._block"); if (!Node.Matches(_orBlock, other._orBlock)) return NoMatch("WhileStatement._orBlock"); if (!Node.Matches(_thenBlock, other._thenBlock)) return NoMatch("WhileStatement._thenBlock"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_modifier == existing) { this.Modifier = (StatementModifier)newNode; return true; } if (_condition == existing) { this.Condition = (Expression)newNode; return true; } if (_block == existing) { this.Block = (Block)newNode; return true; } if (_orBlock == existing) { this.OrBlock = (Block)newNode; return true; } if (_thenBlock == existing) { this.ThenBlock = (Block)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { WhileStatement clone = (WhileStatement)FormatterServices.GetUninitializedObject(typeof(WhileStatement)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _modifier) { clone._modifier = _modifier.Clone() as StatementModifier; clone._modifier.InitializeParent(clone); } if (null != _condition) { clone._condition = _condition.Clone() as Expression; clone._condition.InitializeParent(clone); } if (null != _block) { clone._block = _block.Clone() as Block; clone._block.InitializeParent(clone); } if (null != _orBlock) { clone._orBlock = _orBlock.Clone() as Block; clone._orBlock.InitializeParent(clone); } if (null != _thenBlock) { clone._thenBlock = _thenBlock.Clone() as Block; clone._thenBlock.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _modifier) { _modifier.ClearTypeSystemBindings(); } if (null != _condition) { _condition.ClearTypeSystemBindings(); } if (null != _block) { _block.ClearTypeSystemBindings(); } if (null != _orBlock) { _orBlock.ClearTypeSystemBindings(); } if (null != _thenBlock) { _thenBlock.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block Block { get { if (_block == null) { _block = new Block(); _block.InitializeParent(this); } return _block; } set { if (_block != value) { _block = value; if (null != _block) { _block.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block OrBlock { get { return _orBlock; } set { if (_orBlock != value) { _orBlock = value; if (null != _orBlock) { _orBlock.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block ThenBlock { get { return _thenBlock; } set { if (_thenBlock != value) { _thenBlock = value; if (null != _thenBlock) { _thenBlock.InitializeParent(this); } } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace MigAz.Azure.UserControls { partial class TargetTreeView { /// <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() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TargetTreeView)); this.treeTargetARM = new System.Windows.Forms.TreeView(); this.label1 = new System.Windows.Forms.Label(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.virtualNetworkMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.asdfasdfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.resourceGroupMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newLoadBalancerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newPublicIPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newAvailabilitySetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newStorageAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newVirtualNetworkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.virtualNetworkMenuStrip.SuspendLayout(); this.resourceGroupMenuStrip.SuspendLayout(); this.SuspendLayout(); // // treeTargetARM // this.treeTargetARM.AllowDrop = true; this.treeTargetARM.Enabled = false; this.treeTargetARM.Location = new System.Drawing.Point(5, 45); this.treeTargetARM.Name = "treeTargetARM"; this.treeTargetARM.Size = new System.Drawing.Size(128, 129); this.treeTargetARM.TabIndex = 58; this.treeTargetARM.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeTargetARM_ItemDrag); this.treeTargetARM.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TargetTreeView_AfterSelect); this.treeTargetARM.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeTargetARM_DragDrop); this.treeTargetARM.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeTargetARM_DragEnter); this.treeTargetARM.KeyUp += new System.Windows.Forms.KeyEventHandler(this.treeTargetARM_KeyUp); this.treeTargetARM.MouseClick += new System.Windows.Forms.MouseEventHandler(this.treeTargetARM_MouseClick); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(5, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(150, 20); this.label1.TabIndex = 59; this.label1.Text = "Target Resource(s):"; // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "ResourceGroup"); this.imageList1.Images.SetKeyName(1, "Disk"); this.imageList1.Images.SetKeyName(2, "LoadBalancer"); this.imageList1.Images.SetKeyName(3, "NetworkInterface"); this.imageList1.Images.SetKeyName(4, "NetworkSecurityGroup"); this.imageList1.Images.SetKeyName(5, "PublicIp"); this.imageList1.Images.SetKeyName(6, "StorageAccount"); this.imageList1.Images.SetKeyName(7, "VirtualMachine"); this.imageList1.Images.SetKeyName(8, "AvailabilitySet"); this.imageList1.Images.SetKeyName(9, "VirtualNetwork"); this.imageList1.Images.SetKeyName(10, "RouteTable"); this.imageList1.Images.SetKeyName(11, "VirtualMachineImage"); // // virtualNetworkMenuStrip // this.virtualNetworkMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); this.virtualNetworkMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.asdfasdfToolStripMenuItem, this.toolStripMenuItem1, this.removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem}); this.virtualNetworkMenuStrip.Name = "virtualNetworkMenuStrip"; this.virtualNetworkMenuStrip.Size = new System.Drawing.Size(504, 70); // // asdfasdfToolStripMenuItem // this.asdfasdfToolStripMenuItem.Name = "asdfasdfToolStripMenuItem"; this.asdfasdfToolStripMenuItem.Size = new System.Drawing.Size(503, 30); this.asdfasdfToolStripMenuItem.Text = "New &Subnet"; this.asdfasdfToolStripMenuItem.Click += new System.EventHandler(this.asdfasdfToolStripMenuItem_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(500, 6); // // removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem // this.removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem.Name = "removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem"; this.removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem.Size = new System.Drawing.Size(503, 30); this.removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem.Text = "Remove Virtual Network from Target Resource Group"; this.removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem.Click += new System.EventHandler(this.removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem_Click); // // resourceGroupMenuStrip // this.resourceGroupMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); this.resourceGroupMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem}); this.resourceGroupMenuStrip.Name = "resourceGroupMenuStrip"; this.resourceGroupMenuStrip.Size = new System.Drawing.Size(199, 67); // // newToolStripMenuItem // this.newToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newAvailabilitySetToolStripMenuItem, this.newLoadBalancerToolStripMenuItem, this.newPublicIPToolStripMenuItem, this.newStorageAccountToolStripMenuItem, this.newVirtualNetworkToolStripMenuItem}); this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.Size = new System.Drawing.Size(198, 30); this.newToolStripMenuItem.Text = "&New"; // // newLoadBalancerToolStripMenuItem // this.newLoadBalancerToolStripMenuItem.Image = global::MigAz.Azure.Properties.Resources.LoadBalancer; this.newLoadBalancerToolStripMenuItem.Name = "newLoadBalancerToolStripMenuItem"; this.newLoadBalancerToolStripMenuItem.Size = new System.Drawing.Size(227, 30); this.newLoadBalancerToolStripMenuItem.Text = "Load Balancer"; this.newLoadBalancerToolStripMenuItem.Click += new System.EventHandler(this.newLoadBalancerToolStripMenuItem_Click); // // newPublicIPToolStripMenuItem // this.newPublicIPToolStripMenuItem.Image = global::MigAz.Azure.Properties.Resources.PublicIp; this.newPublicIPToolStripMenuItem.Name = "newPublicIPToolStripMenuItem"; this.newPublicIPToolStripMenuItem.Size = new System.Drawing.Size(227, 30); this.newPublicIPToolStripMenuItem.Text = "Public IP"; this.newPublicIPToolStripMenuItem.Click += new System.EventHandler(this.newPublicIPToolStripMenuItem_Click); // // newAvailabilitySetToolStripMenuItem // this.newAvailabilitySetToolStripMenuItem.Image = global::MigAz.Azure.Properties.Resources.AvailabilitySet; this.newAvailabilitySetToolStripMenuItem.Name = "newAvailabilitySetToolStripMenuItem"; this.newAvailabilitySetToolStripMenuItem.Size = new System.Drawing.Size(227, 30); this.newAvailabilitySetToolStripMenuItem.Text = "Availability Set"; this.newAvailabilitySetToolStripMenuItem.Click += new System.EventHandler(this.newAvailabilitySetToolStripMenuItem_Click); // // newStorageAccountToolStripMenuItem // this.newStorageAccountToolStripMenuItem.Image = global::MigAz.Azure.Properties.Resources.StorageAccount; this.newStorageAccountToolStripMenuItem.Name = "newStorageAccountToolStripMenuItem"; this.newStorageAccountToolStripMenuItem.Size = new System.Drawing.Size(227, 30); this.newStorageAccountToolStripMenuItem.Text = "Storage Account"; this.newStorageAccountToolStripMenuItem.Click += new System.EventHandler(this.newStorageAccountToolStripMenuItem_Click); // // newVirtualNetworkToolStripMenuItem // this.newVirtualNetworkToolStripMenuItem.Image = global::MigAz.Azure.Properties.Resources.VirtualNetwork; this.newVirtualNetworkToolStripMenuItem.Name = "newVirtualNetworkToolStripMenuItem"; this.newVirtualNetworkToolStripMenuItem.Size = new System.Drawing.Size(227, 30); this.newVirtualNetworkToolStripMenuItem.Text = "Virtual Network"; this.newVirtualNetworkToolStripMenuItem.Click += new System.EventHandler(this.newVirtualNetworkToolStripMenuItem_Click); // // TargetTreeView // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label1); this.Controls.Add(this.treeTargetARM); this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.Name = "TargetTreeView"; this.Size = new System.Drawing.Size(378, 374); this.Resize += new System.EventHandler(this.TargetTreeView_Resize); this.virtualNetworkMenuStrip.ResumeLayout(false); this.resourceGroupMenuStrip.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TreeView treeTargetARM; private System.Windows.Forms.Label label1; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ContextMenuStrip virtualNetworkMenuStrip; private System.Windows.Forms.ToolStripMenuItem asdfasdfToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem removeVirtualNetworkFromTargetResourceGroupToolStripMenuItem; private System.Windows.Forms.ContextMenuStrip resourceGroupMenuStrip; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newAvailabilitySetToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newLoadBalancerToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newPublicIPToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newStorageAccountToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newVirtualNetworkToolStripMenuItem; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Newtonsoft.Json; using NodaTime; using NUnit.Framework; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Tests.Common.Util { [TestFixture] public class MarketHoursDatabaseJsonConverterTests { [Test] public void HandlesRoundTrip() { var database = MarketHoursDatabase.FromDataFolder(); var result = JsonConvert.SerializeObject(database, Formatting.Indented); var deserializedDatabase = JsonConvert.DeserializeObject<MarketHoursDatabase>(result); var originalListing = database.ExchangeHoursListing.ToDictionary(); foreach (var kvp in deserializedDatabase.ExchangeHoursListing) { var original = originalListing[kvp.Key]; Assert.AreEqual(original.DataTimeZone, kvp.Value.DataTimeZone); CollectionAssert.AreEqual(original.ExchangeHours.Holidays, kvp.Value.ExchangeHours.Holidays); foreach (var value in Enum.GetValues(typeof(DayOfWeek))) { var day = (DayOfWeek) value; var o = original.ExchangeHours.MarketHours[day]; var d = kvp.Value.ExchangeHours.MarketHours[day]; foreach (var pair in o.Segments.Zip(d.Segments, Tuple.Create)) { Assert.AreEqual(pair.Item1.State, pair.Item2.State); Assert.AreEqual(pair.Item1.Start, pair.Item2.Start); Assert.AreEqual(pair.Item1.End, pair.Item2.End); } } } } [Test, Ignore("This is provided to make it easier to convert your own market-hours-database.csv to the new format")] public void ConvertMarketHoursDatabaseCsvToJson() { var directory = Path.Combine(Constants.DataFolder, "market-hours"); var input = Path.Combine(directory, "market-hours-database.csv"); var output = Path.Combine(directory, Path.GetFileNameWithoutExtension(input) + ".json"); var allHolidays = Directory.EnumerateFiles(Path.Combine(Constants.DataFolder, "market-hours"), "holidays-*.csv").Select(x => { var dates = new HashSet<DateTime>(); var market = Path.GetFileNameWithoutExtension(x).Replace("holidays-", string.Empty); foreach (var line in File.ReadAllLines(x).Skip(1).Where(l => !l.StartsWith("#"))) { var csv = line.ToCsv(); dates.Add(new DateTime(int.Parse(csv[0]), int.Parse(csv[1]), int.Parse(csv[2]))); } return new KeyValuePair<string, IEnumerable<DateTime>>(market, dates); }).ToDictionary(); var database = FromCsvFile(input, allHolidays); File.WriteAllText(output, JsonConvert.SerializeObject(database, Formatting.Indented)); } #region These methods represent the old way of reading MarketHoursDatabase from csv and are left here to allow users to convert /// <summary> /// Creates a new instance of the <see cref="MarketHoursDatabase"/> class by reading the specified csv file /// </summary> /// <param name="file">The csv file to be read</param> /// <param name="holidaysByMarket">The holidays for each market in the file, if no holiday is present then none is used</param> /// <returns>A new instance of the <see cref="MarketHoursDatabase"/> class representing the data in the specified file</returns> public static MarketHoursDatabase FromCsvFile(string file, IReadOnlyDictionary<string, IEnumerable<DateTime>> holidaysByMarket) { var exchangeHours = new Dictionary<SecurityDatabaseKey, MarketHoursDatabase.Entry>(); if (!File.Exists(file)) { throw new FileNotFoundException("Unable to locate market hours file: " + file); } // skip the first header line, also skip #'s as these are comment lines foreach (var line in File.ReadLines(file).Where(x => !x.StartsWith("#")).Skip(1)) { SecurityDatabaseKey key; var hours = FromCsvLine(line, holidaysByMarket, out key); if (exchangeHours.ContainsKey(key)) { throw new Exception("Encountered duplicate key while processing file: " + file + ". Key: " + key); } exchangeHours[key] = hours; } return new MarketHoursDatabase(exchangeHours); } /// <summary> /// Creates a new instance of <see cref="SecurityExchangeHours"/> from the specified csv line and holiday set /// </summary> /// <param name="line">The csv line to be parsed</param> /// <param name="holidaysByMarket">The holidays this exchange isn't open for trading by market</param> /// <param name="key">The key used to uniquely identify these market hours</param> /// <returns>A new <see cref="SecurityExchangeHours"/> for the specified csv line and holidays</returns> private static MarketHoursDatabase.Entry FromCsvLine(string line, IReadOnlyDictionary<string, IEnumerable<DateTime>> holidaysByMarket, out SecurityDatabaseKey key) { var csv = line.Split(','); var marketHours = new List<LocalMarketHours>(7); // timezones can be specified using Tzdb names (America/New_York) or they can // be specified using offsets, UTC-5 var dataTimeZone = ParseTimeZone(csv[0]); var exchangeTimeZone = ParseTimeZone(csv[1]); //var market = csv[2]; //var symbol = csv[3]; //var type = csv[4]; var symbol = string.IsNullOrEmpty(csv[3]) ? null : csv[3]; key = new SecurityDatabaseKey(csv[2], symbol, (SecurityType)Enum.Parse(typeof(SecurityType), csv[4], true)); int csvLength = csv.Length; for (int i = 1; i < 8; i++) // 7 days, so < 8 { // the 4 here is because 4 times per day, ex_open,open,close,ex_close if (4*i + 4 > csvLength - 1) { break; } var hours = ReadCsvHours(csv, 4*i + 1, (DayOfWeek) (i - 1)); marketHours.Add(hours); } IEnumerable<DateTime> holidays; if (!holidaysByMarket.TryGetValue(key.Market, out holidays)) { holidays = Enumerable.Empty<DateTime>(); } var exchangeHours = new SecurityExchangeHours(exchangeTimeZone, holidays, marketHours.ToDictionary(x => x.DayOfWeek)); return new MarketHoursDatabase.Entry(dataTimeZone, exchangeHours); } private static DateTimeZone ParseTimeZone(string tz) { // handle UTC directly if (tz == "UTC") return TimeZones.Utc; // if it doesn't start with UTC then it's a name, like America/New_York if (!tz.StartsWith("UTC")) return DateTimeZoneProviders.Tzdb[tz]; // it must be a UTC offset, parse the offset as hours // define the time zone as a constant offset time zone in the form: 'UTC-3.5' or 'UTC+10' var millisecondsOffset = (int) TimeSpan.FromHours(double.Parse(tz.Replace("UTC", string.Empty))).TotalMilliseconds; return DateTimeZone.ForOffset(Offset.FromMilliseconds(millisecondsOffset)); } private static LocalMarketHours ReadCsvHours(string[] csv, int startIndex, DayOfWeek dayOfWeek) { var ex_open = csv[startIndex]; if (ex_open == "-") { return LocalMarketHours.ClosedAllDay(dayOfWeek); } if (ex_open == "+") { return LocalMarketHours.OpenAllDay(dayOfWeek); } var open = csv[startIndex + 1]; var close = csv[startIndex + 2]; var ex_close = csv[startIndex + 3]; var ex_open_time = ParseHoursToTimeSpan(ex_open); var open_time = ParseHoursToTimeSpan(open); var close_time = ParseHoursToTimeSpan(close); var ex_close_time = ParseHoursToTimeSpan(ex_close); if (ex_open_time == TimeSpan.Zero && open_time == TimeSpan.Zero && close_time == TimeSpan.Zero && ex_close_time == TimeSpan.Zero) { return LocalMarketHours.ClosedAllDay(dayOfWeek); } return new LocalMarketHours(dayOfWeek, ex_open_time, open_time, close_time, ex_close_time); } private static TimeSpan ParseHoursToTimeSpan(string ex_open) { return TimeSpan.FromHours(double.Parse(ex_open, CultureInfo.InvariantCulture)); } #endregion } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2016 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; #if FEATURE_MPCONTRACT using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // FEATURE_MPCONTRACT using System.Globalization; using System.Linq; namespace MsgPack { /// <summary> /// Implements <see cref="IDictionary{TKey,TValue}"/> for <see cref="MessagePackObject"/>. /// </summary> /// <remarks> /// This dictionary handles <see cref="MessagePackObject"/> type semantics for the key. /// Additionally, this dictionary implements 'freezing' feature. /// For details, see <see cref="IsFrozen"/>, <see cref="Freeze"/>, and <see cref="AsFrozen"/>. /// </remarks> #if !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 [Serializable] #endif // !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 [DebuggerTypeProxy( typeof( DictionaryDebuggerProxy<,> ) )] public partial class MessagePackObjectDictionary : IDictionary<MessagePackObject, MessagePackObject>, IDictionary { private const int Threashold = 10; private const int ListInitialCapacity = Threashold; private const int DictionaryInitialCapacity = Threashold * 2; private List<MessagePackObject> _keys; private List<MessagePackObject> _values; private Dictionary<MessagePackObject, MessagePackObject> _dictionary; private int _version; private bool _isFrozen; /// <summary> /// Gets a value indicating whether this instance is frozen. /// </summary> /// <value> /// <c>true</c> if this instance is frozen; otherwise, <c>false</c>. /// </value> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public bool IsFrozen { get { return this._isFrozen; } } /// <summary> /// Gets the number of elements contained in the <see cref="MessagePackObjectDictionary"/>. /// </summary> /// <returns> /// The number of elements contained in the <see cref="MessagePackObjectDictionary"/>. /// </returns> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public int Count { get { this.AssertInvariant(); return this._dictionary == null ? this._keys.Count : this._dictionary.Count; } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <value> /// The element with the specified key. /// </value> /// <param name="key">Key for geting or seting value.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>. /// </exception> /// <exception cref="T:System.Collections.Generic.KeyNotFoundException"> /// The property is retrieved and <paramref name="key"/> is not found. /// </exception> /// <exception cref="InvalidOperationException"> /// The property is set and this instance is frozen. /// </exception> /// <remarks> /// <para> /// Note that tiny integers are considered equal regardless of its CLI <see cref="Type"/>, /// and UTF-8 encoded bytes are considered equals to <see cref="String"/>. /// </para> /// <para> /// This method approaches an O(1) operation. /// </para> /// </remarks> public MessagePackObject this[ MessagePackObject key ] { get { if ( key.IsNil ) { ThrowKeyNotNilException( "key" ); } Contract.EndContractBlock(); MessagePackObject result; if ( !this.TryGetValue( key, out result ) ) { throw new KeyNotFoundException( String.Format( CultureInfo.CurrentCulture, "Key '{0}'({1} type) does not exist in this dictionary.", key, key.UnderlyingType ) ); } return result; } set { if ( key.IsNil ) { ThrowKeyNotNilException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); this.AssertInvariant(); this.AddCore( key, value, true ); } } #if !UNITY /// <summary> /// Gets an <see cref="KeySet"/> containing the keys of the <see cref="MessagePackObjectDictionary"/>. /// </summary> /// <returns> /// An <see cref="KeySet"/> containing the keys of the object. /// This value will not be <c>null</c>. /// </returns> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public KeySet Keys { get { this.AssertInvariant(); return new KeySet( this ); } } #else /// <summary> /// Gets an <see cref="KeyCollection"/> containing the keys of the <see cref="MessagePackObjectDictionary"/>. /// </summary> /// <returns> /// An <see cref="KeyCollection"/> containing the keys of the object. /// This value will not be <c>null</c>. /// </returns> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public KeyCollection Keys { get { this.AssertInvariant(); return new KeyCollection( this ); } } #endif // !UNITY /// <summary> /// Gets an <see cref="ValueCollection"/> containing the values of the <see cref="MessagePackObjectDictionary"/>. /// </summary> /// <returns> /// An <see cref="ValueCollection"/> containing the values of the object. /// This value will not be <c>null</c>. /// </returns> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public ValueCollection Values { get { this.AssertInvariant(); return new ValueCollection( this ); } } ICollection<MessagePackObject> IDictionary<MessagePackObject, MessagePackObject>.Keys { get { return this.Keys; } } ICollection<MessagePackObject> IDictionary<MessagePackObject, MessagePackObject>.Values { get { return this.Values; } } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] bool ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.IsReadOnly { get { return this.IsFrozen; } } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] bool IDictionary.IsFixedSize { get { return this.IsFrozen; } } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] bool IDictionary.IsReadOnly { get { return this.IsFrozen; } } ICollection IDictionary.Keys { get { return this._keys; } } ICollection IDictionary.Values { get { return this.Values; } } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] object IDictionary.this[ object key ] { get { if ( key == null ) { throw new ArgumentNullException( "key" ); } Contract.EndContractBlock(); var typedKey = ValidateObjectArgument( key, "key" ); if ( typedKey.IsNil ) { ThrowKeyNotNilException( "key" ); } MessagePackObject value; if ( !this.TryGetValue( typedKey, out value ) ) { return null; } return value; } set { if ( key == null ) { throw new ArgumentNullException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); var typedKey = ValidateObjectArgument( key, "key" ); if ( typedKey.IsNil ) { ThrowKeyNotNilException( "key" ); } this[ typedKey ] = ValidateObjectArgument( value, "value" ); } } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] bool ICollection.IsSynchronized { get { return false; } } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] object ICollection.SyncRoot { get { return this; } } /// <summary> /// Initializes an empty new instance of the <see cref="MessagePackObjectDictionary"/> class with default capacity. /// </summary> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public MessagePackObjectDictionary() { this._keys = new List<MessagePackObject>( ListInitialCapacity ); this._values = new List<MessagePackObject>( ListInitialCapacity ); } /// <summary> /// Initializes an empty new instance of the <see cref="MessagePackObjectDictionary"/> class with specified initial capacity. /// </summary> /// <param name="initialCapacity">The initial capacity.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="initialCapacity"/> is negative. /// </exception> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public MessagePackObjectDictionary( int initialCapacity ) { if ( initialCapacity < 0 ) { throw new ArgumentOutOfRangeException( "initialCapacity" ); } Contract.EndContractBlock(); if ( initialCapacity <= Threashold ) { this._keys = new List<MessagePackObject>( initialCapacity ); this._values = new List<MessagePackObject>( initialCapacity ); } else { this._dictionary = new Dictionary<MessagePackObject, MessagePackObject>( initialCapacity, MessagePackObjectEqualityComparer.Instance ); } } /// <summary> /// Initializes a new instance of the <see cref="MessagePackObjectDictionary"/> class. /// </summary> /// <param name="dictionary">The dictionary to be copied from.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="dictionary"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// Failed to copy from <paramref name="dictionary"/>. /// </exception> /// <remarks> /// This constructor takes <em>O(N)</em> time, <em>N</em> is <see cref="P:ICollection{T}.Count"/> of <paramref name="dictionary"/>. /// Initial capacity will be <see cref="P:ICollection{T}.Count"/> of <paramref name="dictionary"/>. /// </remarks> public MessagePackObjectDictionary( IDictionary<MessagePackObject, MessagePackObject> dictionary ) { if ( dictionary == null ) { throw new ArgumentNullException( "dictionary" ); } Contract.EndContractBlock(); if ( dictionary.Count <= Threashold ) { this._keys = new List<MessagePackObject>( dictionary.Count ); this._values = new List<MessagePackObject>( dictionary.Count ); } else { this._dictionary = new Dictionary<MessagePackObject, MessagePackObject>( dictionary.Count, MessagePackObjectEqualityComparer.Instance ); } try { foreach ( var kv in dictionary ) { this.AddCore( kv.Key, kv.Value, false ); } } catch ( ArgumentException ex ) { #if SILVERLIGHT throw new ArgumentException( "Failed to copy specified dictionary.", ex ); #else throw new ArgumentException( "Failed to copy specified dictionary.", "dictionary", ex ); #endif } } private static void ThrowKeyNotNilException( string parameterName ) { throw new ArgumentNullException( parameterName, "Key cannot be nil." ); } private static void ThrowDuplicatedKeyException( MessagePackObject key, string parameterName ) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Key '{0}'({1} type) already exists in this dictionary.", key, key.UnderlyingType ), parameterName ); } private void VerifyIsNotFrozen() { if ( this._isFrozen ) { throw new InvalidOperationException( "This dictionary is frozen." ); } } [Conditional( "DEBUG" )] private void AssertInvariant() { if ( this._dictionary == null ) { Contract.Assert( this._keys != null, "this._keys != null" ); Contract.Assert( this._values != null, "this._values != null" ); Contract.Assert( this._keys.Count == this._values.Count, "this._keys.Count == this._values.Count" ); Contract.Assert( this._keys.Distinct( MessagePackObjectEqualityComparer.Instance ).Count() == this._keys.Count, "this._keys.Distinct( MessagePackObjectEqualityComparer.Instance ).Count() == this._keys.Count" ); } else { Contract.Assert( this._keys == null, "this._keys == null" ); Contract.Assert( this._values == null, "this._values == null" ); } } private static MessagePackObject ValidateObjectArgument( object obj, string parameterName ) { var result = TryValidateObjectArgument( obj ); if ( result == null ) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Cannot convert '{1}' to {0}.", typeof( MessagePackObject ).Name, obj.GetType() ), parameterName ); } return result.Value; } private static MessagePackObject? TryValidateObjectArgument( object value ) { if ( value == null ) { return MessagePackObject.Nil; } if ( value is MessagePackObject ) { return ( MessagePackObject )value; } byte[] asBytes; if ( ( asBytes = value as byte[] ) != null ) { return asBytes; } string asString; if ( ( asString = value as string ) != null ) { return asString; } MessagePackString asMessagePackString; if ( ( asMessagePackString = value as MessagePackString ) != null ) { return new MessagePackObject( asMessagePackString ); } #if ( NETSTANDARD1_1 || NETSTANDARD1_3 ) switch ( NetStandardCompatibility.GetTypeCode( value.GetType() ) ) #else switch ( Type.GetTypeCode( value.GetType() ) ) #endif // NETSTANDARD1_1 || NETSTANDARD1_3 { case TypeCode.Boolean: { return ( bool )value; } case TypeCode.Byte: { return ( byte )value; } case TypeCode.DateTime: { return MessagePackConvert.FromDateTime( ( DateTime )value ); } case TypeCode.DBNull: case TypeCode.Empty: { return MessagePackObject.Nil; } case TypeCode.Double: { return ( double )value; } case TypeCode.Int16: { return ( short )value; } case TypeCode.Int32: { return ( int )value; } case TypeCode.Int64: { return ( long )value; } case TypeCode.SByte: { return ( sbyte )value; } case TypeCode.Single: { return ( float )value; } case TypeCode.String: { return value.ToString(); } case TypeCode.UInt16: { return ( ushort )value; } case TypeCode.UInt32: { return ( uint )value; } case TypeCode.UInt64: { return ( ulong )value; } // ReSharper disable RedundantCaseLabel case TypeCode.Char: case TypeCode.Decimal: case TypeCode.Object: // ReSharper restore RedundantCaseLabel default: { return null; } } } /// <summary> /// Determines whether the <see cref="MessagePackObjectDictionary"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="MessagePackObjectDictionary"/>.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>. /// </exception> /// <returns> /// <c>true</c> if the <see cref="MessagePackObjectDictionary"/> contains an element with the key; otherwise, <c>false</c>. /// </returns> /// <remarks> /// This method approaches an O(1) operation. /// </remarks> public bool ContainsKey( MessagePackObject key ) { if ( key.IsNil ) { ThrowKeyNotNilException( "key" ); } Contract.EndContractBlock(); this.AssertInvariant(); return this._dictionary == null ? this._keys.Contains( key, MessagePackObjectEqualityComparer.Instance ) : this._dictionary.ContainsKey( key ); } /// <summary> /// Determines whether the <see cref="MessagePackObjectDictionary"/> contains an element with the specified value. /// </summary> /// <param name="value">The value to locate in the <see cref="MessagePackObjectDictionary"/>.</param> /// <returns> /// <c>true</c> if the <see cref="MessagePackObjectDictionary"/> contains an element with the value; otherwise, <c>false</c>. /// </returns> /// <remarks> /// This method approaches an O(<em>N</em>) operation where <em>N</em> is <see cref="Count"/>. /// </remarks> public bool ContainsValue( MessagePackObject value ) { this.AssertInvariant(); return this._dictionary == null ? this._values.Contains( value, MessagePackObjectEqualityComparer.Instance ) : this._dictionary.ContainsValue( value ); } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] bool ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.Contains( KeyValuePair<MessagePackObject, MessagePackObject> item ) { MessagePackObject value; if ( !this.TryGetValue( item.Key, out value ) ) { return false; } return item.Value == value; } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] bool IDictionary.Contains( object key ) { // ReSharper disable HeuristicUnreachableCode // ReSharper disable once ConditionIsAlwaysTrueOrFalse if ( key == null ) { return false; } // ReSharper restore HeuristicUnreachableCode var typedKey = TryValidateObjectArgument( key ); if ( typedKey.GetValueOrDefault().IsNil ) { return false; } { return this.ContainsKey( typedKey.GetValueOrDefault() ); } } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key"> /// The key whose value to get. /// </param> /// <param name="value"> /// When this method returns, the value associated with the specified key, if the key is found; /// otherwise, the default value for the type of the <paramref name="value"/> parameter. /// This parameter is passed uninitialized. /// </param> /// <returns> /// <c>true</c> if this dictionary contains an element with the specified key; otherwise, <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>. /// </exception> /// <remarks> /// <para> /// Note that tiny integers are considered equal regardless of its CLI <see cref="Type"/>, /// and UTF-8 encoded bytes are considered equals to <see cref="String"/>. /// </para> /// <para> /// This method approaches an O(1) operation. /// </para> /// </remarks> public bool TryGetValue( MessagePackObject key, out MessagePackObject value ) { if ( key.IsNil ) { ThrowKeyNotNilException( "key" ); } Contract.EndContractBlock(); this.AssertInvariant(); if ( this._dictionary == null ) { int index = this._keys.FindIndex( item => item == key ); if ( index < 0 ) { value = MessagePackObject.Nil; return false; } else { value = this._values[ index ]; return true; } } else { return this._dictionary.TryGetValue( key, out value ); } } /// <summary> /// Adds the specified key and value to the dictionary. /// </summary> /// <param name="key"> /// The key of the element to add. /// </param> /// <param name="value"> /// The value of the element to add. The value can be <c>null</c> for reference types. /// </param> /// <returns> /// An element with the same key already does not exist in the dictionary and sucess to add then newly added node; /// otherwise <c>null</c>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="key"/> already exists in this dictionary. /// Note that tiny integers are considered equal regardless of its CLI <see cref="Type"/>, /// and UTF-8 encoded bytes are considered equals to <see cref="String"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>. /// </exception> /// <remarks> /// If <see cref="Count"/> is less than the capacity, this method approaches an O(1) operation. /// If the capacity must be increased to accommodate the new element, /// this method becomes an O(<em>N</em>) operation, where <em>N</em> is <see cref="Count"/>. /// </remarks> public void Add( MessagePackObject key, MessagePackObject value ) { if ( key.IsNil ) { ThrowKeyNotNilException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); this.AddCore( key, value, false ); } private void AddCore( MessagePackObject key, MessagePackObject value, bool allowOverwrite ) { Contract.Assert( !key.IsNil, "!key.IsNil" ); if ( this._dictionary == null ) { if ( this._keys.Count < Threashold ) { int index = this._keys.FindIndex( item => item == key ); if ( index < 0 ) { this._keys.Add( key ); this._values.Add( value ); } else { if ( !allowOverwrite ) { ThrowDuplicatedKeyException( key, "key" ); } this._values[ index ] = value; } unchecked { this._version++; } return; } if ( this._keys.Count == Threashold && allowOverwrite ) { int index = this._keys.FindIndex( item => item == key ); if ( 0 <= index ) { this._values[ index ] = value; unchecked { this._version++; } return; } } // Swith to hashtable base this._dictionary = new Dictionary<MessagePackObject, MessagePackObject>( DictionaryInitialCapacity, MessagePackObjectEqualityComparer.Instance ); for ( int i = 0; i < this._keys.Count; i++ ) { this._dictionary.Add( this._keys[ i ], this._values[ i ] ); } this._keys = null; this._values = null; } if ( allowOverwrite ) { this._dictionary[ key ] = value; } else { try { this._dictionary.Add( key, value ); } catch ( ArgumentException ) { ThrowDuplicatedKeyException( key, "key" ); } } unchecked { this._version++; } } void ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.Add( KeyValuePair<MessagePackObject, MessagePackObject> item ) { if ( item.Key.IsNil ) { ThrowKeyNotNilException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); this.AddCore( item.Key, item.Value, false ); } void IDictionary.Add( object key, object value ) { if ( key == null ) { throw new ArgumentNullException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); var typedKey = ValidateObjectArgument( key, "key" ); if ( typedKey.IsNil ) { ThrowKeyNotNilException( "key" ); } this.AddCore( typedKey, ValidateObjectArgument( value, "value" ), false ); } /// <summary> /// Removes the element with the specified key from the <see cref="MessagePackObjectDictionary"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// <c>true</c> if the element is successfully removed; otherwise, <c>false</c>. /// This method also returns false if <paramref name="key"/> was not found in the original <see cref="MessagePackObjectDictionary"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>. /// </exception> /// <remarks> /// This method approaches an O(1) operation. /// </remarks> public bool Remove( MessagePackObject key ) { if ( key.IsNil ) { ThrowKeyNotNilException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); return this.RemoveCore( key, default( MessagePackObject ), false ); } private bool RemoveCore( MessagePackObject key, MessagePackObject value, bool checkValue ) { Contract.Assert( !key.IsNil, "!key.IsNil" ); this.AssertInvariant(); if ( this._dictionary == null ) { int index = this._keys.FindIndex( item => item == key ); if ( index < 0 ) { return false; } if ( checkValue && this._values[ index ] != value ) { return false; } this._keys.RemoveAt( index ); this._values.RemoveAt( index ); } else { if ( checkValue ) { if ( !( this._dictionary as ICollection<KeyValuePair<MessagePackObject, MessagePackObject>> ).Remove( new KeyValuePair<MessagePackObject, MessagePackObject>( key, value ) ) ) { return false; } } else { if ( !this._dictionary.Remove( key ) ) { return false; } } } unchecked { this._version++; } return true; } bool ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.Remove( KeyValuePair<MessagePackObject, MessagePackObject> item ) { if ( item.Key.IsNil ) { ThrowKeyNotNilException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); return this.RemoveCore( item.Key, item.Value, true ); } void IDictionary.Remove( object key ) { if ( key == null ) { throw new ArgumentNullException( "key" ); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); var typedKey = ValidateObjectArgument( key, "key" ); if ( typedKey.IsNil ) { ThrowKeyNotNilException( "key" ); } this.RemoveCore( typedKey, default( MessagePackObject ), false ); } /// <summary> /// Removes all items from the <see cref="MessagePackObjectDictionary"/>. /// </summary> /// <remarks> /// This method approaches an O(<em>N</em>) operation, where <em>N</em> is <see cref="Count"/>. /// </remarks> public void Clear() { this.VerifyIsNotFrozen(); this.AssertInvariant(); if ( this._dictionary == null ) { this._keys.Clear(); this._values.Clear(); } else { this._dictionary.Clear(); } unchecked { this._version++; } } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] void ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.CopyTo( KeyValuePair<MessagePackObject, MessagePackObject>[] array, int arrayIndex ) { CollectionOperation.CopyTo( this, this.Count, 0, array, arrayIndex, this.Count ); } [SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )] void ICollection.CopyTo( Array array, int index ) { DictionaryEntry[] asDictionaryEntries; if ( ( asDictionaryEntries = array as DictionaryEntry[] ) != null ) { CollectionOperation.CopyTo( this, this.Count, 0, asDictionaryEntries, index, array.Length, kv => new DictionaryEntry( kv.Key, kv.Value ) ); return; } CollectionOperation.CopyTo( this, this.Count, array, index ); } /// <summary> /// Returns an enumerator that iterates through the <see cref="MessagePackObjectDictionary"/>. /// </summary> /// <returns> /// Returns an enumerator that iterates through the <see cref="MessagePackObjectDictionary"/>. /// </returns> /// <remarks> /// This method is an O(1) operation. /// </remarks> public Enumerator GetEnumerator() { return new Enumerator( this ); } IEnumerator<KeyValuePair<MessagePackObject, MessagePackObject>> IEnumerable<KeyValuePair<MessagePackObject, MessagePackObject>>.GetEnumerator() { return this.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } IDictionaryEnumerator IDictionary.GetEnumerator() { // Avoid tricky casting error. return new DictionaryEnumerator( this ); } /// <summary> /// Freezes this instance. /// </summary> /// <returns> /// This instance itself. /// This value will not be <c>null</c> and its <see cref="IsFrozen"/> is <c>true</c>. /// </returns> /// <remarks> /// This method freezes this instance itself. /// This operation is an O(1) operation. /// </remarks> public MessagePackObjectDictionary Freeze() { this._isFrozen = true; return this; } /// <summary> /// Gets a copy of this instance as frozen instance. /// </summary> /// <returns> /// New <see cref="MessagePackObjectDictionary"/> instance which contains same items as this instance. /// This value will not be <c>null</c> and its <see cref="IsFrozen"/> is <c>true</c>. /// </returns> /// <remarks> /// This method does not freeze this instance itself. /// This operation is an O(<em>N</em>) operation where <em>O(N)</em> <see cref="Count"/> of items. /// </remarks> public MessagePackObjectDictionary AsFrozen() { return new MessagePackObjectDictionary( this ).Freeze(); } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util.Packed; using System; using System.Diagnostics; using System.IO; namespace Lucene.Net.Codecs.Lucene41 { /* * 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> /// Encode all values in normal area with fixed bit width, /// which is determined by the max value in this block. /// </summary> internal sealed class ForUtil { /// <summary> /// Special number of bits per value used whenever all values to encode are equal. /// </summary> private static readonly int ALL_VALUES_EQUAL = 0; /// <summary> /// Upper limit of the number of bytes that might be required to stored /// <see cref="Lucene41PostingsFormat.BLOCK_SIZE"/> encoded values. /// </summary> public static readonly int MAX_ENCODED_SIZE = Lucene41PostingsFormat.BLOCK_SIZE * 4; /// <summary> /// Upper limit of the number of values that might be decoded in a single call to /// <see cref="ReadBlock(IndexInput, byte[], int[])"/>. Although values after /// <see cref="Lucene41PostingsFormat.BLOCK_SIZE"/> are garbage, it is necessary to allocate value buffers /// whose size is &gt;= MAX_DATA_SIZE to avoid <see cref="IndexOutOfRangeException"/>s. /// </summary> public static readonly int MAX_DATA_SIZE = LoadMaxDataSize(); private static int LoadMaxDataSize() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { int maxDataSize = 0; for (int version = PackedInt32s.VERSION_START; version <= PackedInt32s.VERSION_CURRENT; version++) { foreach (PackedInt32s.Format format in PackedInt32s.Format.Values/* Enum.GetValues(typeof(PackedInts.Format))*/) { for (int bpv = 1; bpv <= 32; ++bpv) { if (!format.IsSupported(bpv)) { continue; } PackedInt32s.IDecoder decoder = PackedInt32s.GetDecoder(format, version, bpv); int iterations = ComputeIterations(decoder); maxDataSize = Math.Max(maxDataSize, iterations * decoder.ByteValueCount); } } } return maxDataSize; } /// <summary> /// Compute the number of iterations required to decode <see cref="Lucene41PostingsFormat.BLOCK_SIZE"/> /// values with the provided <see cref="PackedInt32s.IDecoder"/>. /// </summary> private static int ComputeIterations(PackedInt32s.IDecoder decoder) { return (int)Math.Ceiling((float)Lucene41PostingsFormat.BLOCK_SIZE / decoder.ByteValueCount); } /// <summary> /// Compute the number of bytes required to encode a block of values that require /// <paramref name="bitsPerValue"/> bits per value with format <paramref name="format"/>. /// </summary> private static int EncodedSize(PackedInt32s.Format format, int packedIntsVersion, int bitsPerValue) { long byteCount = format.ByteCount(packedIntsVersion, Lucene41PostingsFormat.BLOCK_SIZE, bitsPerValue); if (Debugging.AssertsEnabled) Debugging.Assert(byteCount >= 0 && byteCount <= int.MaxValue, byteCount.ToString); return (int)byteCount; } private readonly int[] encodedSizes; private readonly PackedInt32s.IEncoder[] encoders; private readonly PackedInt32s.IDecoder[] decoders; private readonly int[] iterations; /// <summary> /// Create a new <see cref="ForUtil"/> instance and save state into <paramref name="out"/>. /// </summary> internal ForUtil(float acceptableOverheadRatio, DataOutput @out) { @out.WriteVInt32(PackedInt32s.VERSION_CURRENT); encodedSizes = new int[33]; encoders = new PackedInt32s.IEncoder[33]; decoders = new PackedInt32s.IDecoder[33]; iterations = new int[33]; for (int bpv = 1; bpv <= 32; ++bpv) { PackedInt32s.FormatAndBits formatAndBits = PackedInt32s.FastestFormatAndBits(Lucene41PostingsFormat.BLOCK_SIZE, bpv, acceptableOverheadRatio); if (Debugging.AssertsEnabled) { Debugging.Assert(formatAndBits.Format.IsSupported(formatAndBits.BitsPerValue)); Debugging.Assert(formatAndBits.BitsPerValue <= 32); } encodedSizes[bpv] = EncodedSize(formatAndBits.Format, PackedInt32s.VERSION_CURRENT, formatAndBits.BitsPerValue); encoders[bpv] = PackedInt32s.GetEncoder(formatAndBits.Format, PackedInt32s.VERSION_CURRENT, formatAndBits.BitsPerValue); decoders[bpv] = PackedInt32s.GetDecoder(formatAndBits.Format, PackedInt32s.VERSION_CURRENT, formatAndBits.BitsPerValue); iterations[bpv] = ComputeIterations(decoders[bpv]); @out.WriteVInt32(formatAndBits.Format.Id << 5 | (formatAndBits.BitsPerValue - 1)); } } /// <summary> /// Restore a <see cref="ForUtil"/> from a <see cref="DataInput"/>. /// </summary> internal ForUtil(DataInput @in) { int packedIntsVersion = @in.ReadVInt32(); PackedInt32s.CheckVersion(packedIntsVersion); encodedSizes = new int[33]; encoders = new PackedInt32s.IEncoder[33]; decoders = new PackedInt32s.IDecoder[33]; iterations = new int[33]; for (int bpv = 1; bpv <= 32; ++bpv) { var code = @in.ReadVInt32(); var formatId = (int)((uint)code >> 5); var bitsPerValue = (code & 31) + 1; PackedInt32s.Format format = PackedInt32s.Format.ById(formatId); if (Debugging.AssertsEnabled) Debugging.Assert(format.IsSupported(bitsPerValue)); encodedSizes[bpv] = EncodedSize(format, packedIntsVersion, bitsPerValue); encoders[bpv] = PackedInt32s.GetEncoder(format, packedIntsVersion, bitsPerValue); decoders[bpv] = PackedInt32s.GetDecoder(format, packedIntsVersion, bitsPerValue); iterations[bpv] = ComputeIterations(decoders[bpv]); } } /// <summary> /// Write a block of data (<c>For</c> format). /// </summary> /// <param name="data"> The data to write. </param> /// <param name="encoded"> A buffer to use to encode data. </param> /// <param name="out"> The destination output. </param> /// <exception cref="IOException"> If there is a low-level I/O error. </exception> internal void WriteBlock(int[] data, byte[] encoded, IndexOutput @out) { if (IsAllEqual(data)) { @out.WriteByte((byte)(sbyte)ALL_VALUES_EQUAL); @out.WriteVInt32(data[0]); return; } int numBits = BitsRequired(data); if (Debugging.AssertsEnabled) Debugging.Assert(numBits > 0 && numBits <= 32, numBits.ToString); PackedInt32s.IEncoder encoder = encoders[numBits]; int iters = iterations[numBits]; if (Debugging.AssertsEnabled) Debugging.Assert(iters * encoder.ByteValueCount >= Lucene41PostingsFormat.BLOCK_SIZE); int encodedSize = encodedSizes[numBits]; if (Debugging.AssertsEnabled) Debugging.Assert(iters * encoder.ByteBlockCount >= encodedSize); @out.WriteByte((byte)numBits); encoder.Encode(data, 0, encoded, 0, iters); @out.WriteBytes(encoded, encodedSize); } /// <summary> /// Read the next block of data (<c>For</c> format). /// </summary> /// <param name="in"> The input to use to read data. </param> /// <param name="encoded"> A buffer that can be used to store encoded data. </param> /// <param name="decoded"> Where to write decoded data. </param> /// <exception cref="IOException"> If there is a low-level I/O error. </exception> internal void ReadBlock(IndexInput @in, byte[] encoded, int[] decoded) { int numBits = @in.ReadByte(); if (Debugging.AssertsEnabled) Debugging.Assert(numBits <= 32, numBits.ToString); if (numBits == ALL_VALUES_EQUAL) { int value = @in.ReadVInt32(); Arrays.Fill(decoded, 0, Lucene41PostingsFormat.BLOCK_SIZE, value); return; } int encodedSize = encodedSizes[numBits]; @in.ReadBytes(encoded, 0, encodedSize); PackedInt32s.IDecoder decoder = decoders[numBits]; int iters = iterations[numBits]; if (Debugging.AssertsEnabled) Debugging.Assert(iters * decoder.ByteValueCount >= Lucene41PostingsFormat.BLOCK_SIZE); decoder.Decode(encoded, 0, decoded, 0, iters); } /// <summary> /// Skip the next block of data. /// </summary> /// <param name="in"> The input where to read data. </param> /// <exception cref="IOException"> If there is a low-level I/O error. </exception> internal void SkipBlock(IndexInput @in) { int numBits = @in.ReadByte(); if (numBits == ALL_VALUES_EQUAL) { @in.ReadVInt32(); return; } if (Debugging.AssertsEnabled) Debugging.Assert(numBits > 0 && numBits <= 32, numBits.ToString); int encodedSize = encodedSizes[numBits]; @in.Seek(@in.GetFilePointer() + encodedSize); } private static bool IsAllEqual(int[] data) { int v = data[0]; for (int i = 1; i < Lucene41PostingsFormat.BLOCK_SIZE; ++i) { if (data[i] != v) { return false; } } return true; } /// <summary> /// Compute the number of bits required to serialize any of the longs in /// <paramref name="data"/>. /// </summary> private static int BitsRequired(int[] data) { long or = 0; for (int i = 0; i < Lucene41PostingsFormat.BLOCK_SIZE; ++i) { if (Debugging.AssertsEnabled) Debugging.Assert(data[i] >= 0); or |= (uint)data[i]; } return PackedInt32s.BitsRequired(or); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Runtime; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using System.Collections.Concurrent; using Internal.Runtime.Augments; using Internal.Reflection.Core.NonPortable; namespace System { public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { public unsafe int CompareTo(Object target) { if (target == null) return 1; if (target == this) return 0; if (this.EETypePtr != target.EETypePtr) { throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, target.GetType().ToString(), this.GetType().ToString())); } fixed (IntPtr* pThisObj = &this.m_pEEType, pTargetObj = &target.m_pEEType) { IntPtr pThisValue = Object.GetAddrOfPinnedObjectFromEETypeField(pThisObj); IntPtr pTargetValue = Object.GetAddrOfPinnedObjectFromEETypeField(pTargetObj); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return (*(sbyte*)pThisValue == *(sbyte*)pTargetValue) ? 0 : (*(sbyte*)pThisValue < *(sbyte*)pTargetValue) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return (*(byte*)pThisValue == *(byte*)pTargetValue) ? 0 : (*(byte*)pThisValue < *(byte*)pTargetValue) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return (*(short*)pThisValue == *(short*)pTargetValue) ? 0 : (*(short*)pThisValue < *(short*)pTargetValue) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return (*(ushort*)pThisValue == *(ushort*)pTargetValue) ? 0 : (*(ushort*)pThisValue < *(ushort*)pTargetValue) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return (*(int*)pThisValue == *(int*)pTargetValue) ? 0 : (*(int*)pThisValue < *(int*)pTargetValue) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return (*(uint*)pThisValue == *(uint*)pTargetValue) ? 0 : (*(uint*)pThisValue < *(uint*)pTargetValue) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return (*(long*)pThisValue == *(long*)pTargetValue) ? 0 : (*(long*)pThisValue < *(long*)pTargetValue) ? -1 : 1; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return (*(ulong*)pThisValue == *(ulong*)pTargetValue) ? 0 : (*(ulong*)pThisValue < *(ulong*)pTargetValue) ? -1 : 1; default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } } public override bool Equals(Object obj) { if (obj == null) return false; EETypePtr eeType = this.EETypePtr; if (!eeType.FastEquals(obj.EETypePtr)) return false; unsafe { fixed (IntPtr* pThisObj = &this.m_pEEType, pOtherObj = &obj.m_pEEType) { IntPtr pThisValue = Object.GetAddrOfPinnedObjectFromEETypeField(pThisObj); IntPtr pOtherValue = Object.GetAddrOfPinnedObjectFromEETypeField(pOtherObj); RuntimeImports.RhCorElementTypeInfo corElementTypeInfo = eeType.CorElementTypeInfo; switch (corElementTypeInfo.Log2OfSize) { case 0: return (*(byte*)pThisValue) == (*(byte*)pOtherValue); case 1: return (*(ushort*)pThisValue) == (*(ushort*)pOtherValue); case 2: return (*(uint*)pThisValue) == (*(uint*)pOtherValue); case 3: return (*(ulong*)pThisValue) == (*(ulong*)pOtherValue); default: Environment.FailFast("Unexpected enum underlying type"); return false; } } } } public override int GetHashCode() { unsafe { fixed (IntPtr* pObj = &this.m_pEEType) { IntPtr pValue = Object.GetAddrOfPinnedObjectFromEETypeField(pObj); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return (*(bool*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return (*(char*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return (*(sbyte*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return (*(byte*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return (*(short*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return (*(ushort*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return (*(int*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return (*(uint*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return (*(long*)pValue).GetHashCode(); case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return (*(ulong*)pValue).GetHashCode(); default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } } } public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException("enumType"); EnumInfo enumInfo = GetEnumInfo(enumType); if (value == null) throw new ArgumentNullException("value"); if (format == null) throw new ArgumentNullException("format"); Contract.EndContractBlock(); if (value.EETypePtr.IsEnum) { EETypePtr enumTypeEEType; if ((!enumType.TryGetEEType(out enumTypeEEType)) || enumTypeEEType != value.EETypePtr) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType().ToString(), enumType.ToString())); } else { if (value.EETypePtr != enumInfo.UnderlyingType.TypeHandle.ToEETypePtr()) throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, value.GetType().ToString(), enumInfo.UnderlyingType.ToString())); } return Format(enumInfo, value, format); } private static String Format(EnumInfo enumInfo, Object value, String format) { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) { Debug.Assert(false, "Caller was expected to do enough validation to avoid reaching this."); throw new ArgumentException(); } if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { return DoFormatD(rawValue, value.EETypePtr.CorElementType); } if (formatCh == 'X' || formatCh == 'x') { return DoFormatX(rawValue, value.EETypePtr.CorElementType); } if (formatCh == 'G' || formatCh == 'g') { return DoFormatG(enumInfo, rawValue); } if (formatCh == 'F' || formatCh == 'f') { return DoFormatF(enumInfo, rawValue); } throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } // // Helper for Enum.Format(,,"d") // private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { SByte result = (SByte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte result = (Byte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed bool b = (rawValue != 0); return b.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { Int16 result = (Int16)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 result = (UInt16)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { Char result = (Char)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 result = (UInt32)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { Int32 result = (Int32)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 result = (UInt64)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { Int64 result = (Int64)rawValue; return result.ToString(); } default: Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } // // Helper for Enum.Format(,,"x") // private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { Byte result = (byte)(sbyte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed Byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { UInt16 result = (UInt16)(Int16)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 result = (UInt16)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { UInt16 result = (UInt16)(Char)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 result = (UInt32)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { UInt32 result = (UInt32)(int)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 result = (UInt64)rawValue; return result.ToString("X16", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { UInt64 result = (UInt64)(Int64)rawValue; return result.ToString("X16", null); } default: Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } // // Helper for Enum.Format(,,"g") // private static String DoFormatG(EnumInfo enumInfo, ulong rawValue) { Contract.Requires(enumInfo != null); if (!enumInfo.HasFlagsAttribute) // Not marked with Flags attribute { // Try to see if its one of the enum values, then we return a String back else the value String name = GetNameIfAny(enumInfo, rawValue); if (name == null) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); else return name; } else // These are flags OR'ed together (We treat everything as unsigned types) { return DoFormatF(enumInfo, rawValue); } } // // Helper for Enum.Format(,,"f") // private static String DoFormatF(EnumInfo enumInfo, ulong rawValue) { Contract.Requires(enumInfo != null); // These values are sorted by value. Don't change this KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues; int index = namesAndValues.Length - 1; StringBuilder retval = new StringBuilder(); bool firstTime = true; ulong result = rawValue; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (namesAndValues[index].Value == 0)) break; if ((result & namesAndValues[index].Value) == namesAndValues[index].Value) { result -= namesAndValues[index].Value; if (!firstTime) retval.Insert(0, ", "); retval.Insert(0, namesAndValues[index].Key); firstTime = false; } index--; } // We were unable to represent this number as a bitwise or of valid flags if (result != 0) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); // For the case when we have zero if (rawValue == 0) { if (namesAndValues.Length > 0 && namesAndValues[0].Value == 0) return namesAndValues[0].Key; // Zero was one of the enum values. else return "0"; } else return retval.ToString(); // Built a list of matching names. Return it. } internal unsafe Object GetValue() { fixed (IntPtr* pObj = &this.m_pEEType) { IntPtr pValue = Object.GetAddrOfPinnedObjectFromEETypeField(pObj); switch (this.EETypePtr.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return *(bool*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return *(char*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return *(sbyte*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return *(byte*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return *(short*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return *(ushort*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return *(int*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return *(uint*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return *(long*)pValue; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return *(ulong*)pValue; default: Environment.FailFast("Unexpected enum underlying type"); return 0; } } } public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (value == null) throw new ArgumentNullException("value"); ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, "value"); // For desktop compatibility, do not bounce an incoming integer that's the wrong size. // Do a value-preserving cast of both it and the enum values and do a 64-bit compare. EnumInfo enumInfo = GetEnumInfo(enumType); String nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull; } public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); KeyValuePair<String, ulong>[] namesAndValues = GetEnumInfo(enumType).NamesAndValues; String[] names = new String[namesAndValues.Length]; for (int i = 0; i < namesAndValues.Length; i++) names[i] = namesAndValues[i].Key; return names; } public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); RuntimeTypeHandle runtimeTypeHandle = enumType.TypeHandle; EETypePtr eeType = runtimeTypeHandle.ToEETypePtr(); if (!eeType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); switch (eeType.CorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: return CommonRuntimeTypes.Boolean; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: return CommonRuntimeTypes.Char; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: return CommonRuntimeTypes.SByte; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: return CommonRuntimeTypes.Byte; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: return CommonRuntimeTypes.Int16; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: return CommonRuntimeTypes.UInt16; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: return CommonRuntimeTypes.Int32; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: return CommonRuntimeTypes.UInt32; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: return CommonRuntimeTypes.Int64; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: return CommonRuntimeTypes.UInt64; default: throw new ArgumentException(); } } public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Array values = GetEnumInfo(enumType).Values; int count = values.Length; EETypePtr enumArrayType = enumType.MakeArrayType().TypeHandle.ToEETypePtr(); Array result = RuntimeImports.RhNewArray(enumArrayType, count); Array.CopyImplValueTypeArrayNoInnerGcRefs(values, 0, result, 0, count); return result; } public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException("flag"); Contract.EndContractBlock(); if (!(this.EETypePtr == flag.EETypePtr)) throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType())); unsafe { fixed (IntPtr* pThisObj = &this.m_pEEType, pFlagObj = &flag.m_pEEType) { IntPtr pThisValue = Object.GetAddrOfPinnedObjectFromEETypeField(pThisObj); IntPtr pFlagValue = Object.GetAddrOfPinnedObjectFromEETypeField(pFlagObj); switch (this.EETypePtr.CorElementTypeInfo.Log2OfSize) { case 0: return ((*(byte*)pThisValue) & (*(byte*)pFlagValue)) == *(byte*)pFlagValue; case 1: return ((*(ushort*)pThisValue) & (*(ushort*)pFlagValue)) == *(ushort*)pFlagValue; case 2: return ((*(uint*)pThisValue) & (*(uint*)pFlagValue)) == *(uint*)pFlagValue; case 3: return ((*(ulong*)pThisValue) & (*(ulong*)pFlagValue)) == *(ulong*)pFlagValue; default: Environment.FailFast("Unexpected enum underlying type"); return false; } } } } public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (value == null) throw new ArgumentNullException("value"); if (value.EETypePtr == EETypePtr.EETypePtrOf<string>()) { EnumInfo enumInfo = GetEnumInfo(enumType); foreach (KeyValuePair<String, ulong> kv in enumInfo.NamesAndValues) { if (value.Equals(kv.Key)) return true; } return false; } else { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) { if (IsIntegerType(value.GetType())) throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), Enum.GetUnderlyingType(enumType))); else throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } EnumInfo enumInfo = null; if (value.EETypePtr.IsEnum) { if (!ValueTypeMatchesEnumType(enumType, value)) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType(), enumType)); } else { enumInfo = GetEnumInfo(enumType); if (!(enumInfo.UnderlyingType.TypeHandle.ToEETypePtr() == value.EETypePtr)) throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), enumInfo.UnderlyingType)); } if (enumInfo == null) enumInfo = GetEnumInfo(enumType); String nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull != null; } } public static Object Parse(Type enumType, String value) { return Parse(enumType, value, ignoreCase: false); } public static Object Parse(Type enumType, String value, bool ignoreCase) { Object result; Exception exception; if (!TryParseEnum(enumType, value, ignoreCase, out result, out exception)) throw exception; return result; } public static unsafe Object ToObject(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.TypeHandle.ToEETypePtr().IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); if (value == null) throw new ArgumentNullException("value"); ulong rawValue; bool success = TryGetUnboxedValueOfEnumOrInteger(value, out rawValue); if (!success) throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum); if (value.EETypePtr.IsEnum && !ValueTypeMatchesEnumType(enumType, value)) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType(), enumType)); EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr(); return RuntimeImports.RhBox(enumEEType, &rawValue); //@todo: Not big-endian compatible. } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { Exception exception; Object tempResult; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out tempResult, out exception)) { result = default(TEnum); return false; } result = (TEnum)tempResult; return true; } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse<TEnum>(value, false, out result); } public override String ToString() { try { return this.ToString("G"); } catch (Exception) { return this.LastResortToString; } } public String ToString(String format) { if (format == null || format.Length == 0) format = "G"; EnumInfo enumInfo = GetEnumInfoIfAvailable(this.GetType()); // Project N port note: If Reflection info isn't available, fallback to ToString() which will substitute a numeric value for the "correct" output. // This scenario has been hit frequently when throwing exceptions formatted with error strings containing enum substitations. // To avoid replacing the masking the actual exception with an uninteresting MissingMetadataException, we choose instead // to return a base-effort string. if (enumInfo == null) return this.LastResortToString; return Format(enumInfo, this, format); } String IFormattable.ToString(String format, IFormatProvider provider) { return ToString(format); } [Obsolete("The provider argument is not used. Please use ToString().")] String IConvertible.ToString(IFormatProvider provider) { return ToString(); } // // Note: this helper also checks if the enumType is in fact an Enum and throws an user-visible ArgumentException if it's not. // private static EnumInfo GetEnumInfo(Type enumType) { EnumInfo enumInfo = GetEnumInfoIfAvailable(enumType); if (enumInfo == null) throw RuntimeAugments.Callbacks.CreateMissingMetadataException(enumType); return enumInfo; } // // Note: this helper also checks if the enumType is in fact an Enum and throws an user-visible ArgumentException if it's not. // private static EnumInfo GetEnumInfoIfAvailable(Type enumType) { RuntimeTypeHandle runtimeTypeHandle = enumType.TypeHandle; if (!runtimeTypeHandle.ToEETypePtr().IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); // We know this cast will succeed as we already checked for the existence of a RuntimeTypeHandle. RuntimeType runtimeEnumType = (RuntimeType)enumType; return s_enumInfoCache.GetOrAdd(runtimeEnumType); } // // Checks if value.GetType() matches enumType exactly. // private static bool ValueTypeMatchesEnumType(Type enumType, Object value) { EETypePtr enumEEType; if (!enumType.TryGetEEType(out enumEEType)) return false; if (!(enumEEType == value.EETypePtr)) return false; return true; } // // Note: This works on both Enum's and underlying integer values. // // // This returns the underlying enum values as "ulong" regardless of the actual underlying type. Signed integral // types get sign-extended into the 64-bit value, unsigned types get zero-extended. // // The return value is "bool" if "value" is not an enum or an "integer type" as defined by the BCL Enum apis. // private static bool TryGetUnboxedValueOfEnumOrInteger(Object value, out ulong result) { EETypePtr eeType = value.EETypePtr; // For now, this check is required to flush out pointers. RuntimeImports.RhEETypeClassification classification = RuntimeImports.RhGetEETypeClassification(eeType); if (classification != RuntimeImports.RhEETypeClassification.Regular) { result = 0; return false; } RuntimeImports.RhCorElementType corElementType = eeType.CorElementType; unsafe { fixed (IntPtr* pEEType = &value.m_pEEType) { IntPtr pValue = Object.GetAddrOfPinnedObjectFromEETypeField(pEEType); switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: result = (*(bool*)pValue) ? 1UL : 0UL; return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: result = (ulong)(long)(*(char*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: result = (ulong)(long)(*(sbyte*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: result = (ulong)(long)(*(byte*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: result = (ulong)(long)(*(short*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: result = (ulong)(long)(*(ushort*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: result = (ulong)(long)(*(int*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: result = (ulong)(long)(*(uint*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: result = (ulong)(long)(*(long*)pValue); return true; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: result = (ulong)(long)(*(ulong*)pValue); return true; default: result = 0; return false; } } } } // // Look up a name for rawValue if a matching one exists. Returns null if no matching name exists. // private static String GetNameIfAny(EnumInfo enumInfo, ulong rawValue) { KeyValuePair<String, ulong>[] namesAndValues = enumInfo.NamesAndValues; KeyValuePair<String, ulong> searchKey = new KeyValuePair<String, ulong>(null, rawValue); int index = Array.BinarySearch<KeyValuePair<String, ulong>>(namesAndValues, searchKey, s_nameAndValueComparer); if (index < 0) return null; return namesAndValues[index].Key; } // // Common funnel for Enum.Parse methods. // private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, out Object result, out Exception exception) { exception = null; result = null; if (enumType == null) throw new ArgumentNullException("enumType"); RuntimeType runtimeEnumType = enumType as RuntimeType; if (runtimeEnumType == null) throw new ArgumentException(SR.Arg_MustBeType, "enumType"); if (value == null) { exception = new ArgumentNullException("null"); return false; } int firstNonWhitespaceIndex = -1; for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { firstNonWhitespaceIndex = i; break; } } if (firstNonWhitespaceIndex == -1) { exception = new ArgumentException(SR.Arg_MustContainEnumInfo); return false; } EETypePtr enumEEType = runtimeEnumType.TypeHandle.ToEETypePtr(); if (!enumEEType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); if (TryParseAsInteger(enumEEType, value, firstNonWhitespaceIndex, out result)) return true; // Parse as string. Now (and only now) do we look for metadata information. EnumInfo enumInfo = RuntimeAugments.Callbacks.GetEnumInfoIfAvailable(runtimeEnumType); if (enumInfo == null) throw RuntimeAugments.Callbacks.CreateMissingMetadataException(runtimeEnumType); ulong v = 0; // Port note: The docs are silent on how multiple matches are resolved when doing case-insensitive parses. // The desktop's ad-hoc behavior is to pick the one with the smallest value after doing a value-preserving cast // to a ulong, so we'll follow that here. StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; KeyValuePair<String, ulong>[] actualNamesAndValues = enumInfo.NamesAndValues; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { // Find the next separator, if there is one, otherwise the end of the string. int endIndex = value.IndexOf(',', valueIndex); if (endIndex == -1) { endIndex = value.Length; } // Shift the starting and ending indices to eliminate whitespace int endIndexNoWhitespace = endIndex; while (valueIndex < endIndex && char.IsWhiteSpace(value[valueIndex])) valueIndex++; while (endIndexNoWhitespace > valueIndex && char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--; int valueSubstringLength = endIndexNoWhitespace - valueIndex; // Try to match this substring against each enum name bool foundMatch = false; foreach (KeyValuePair<String, ulong> kv in actualNamesAndValues) { String actualName = kv.Key; if (actualName.Length == valueSubstringLength && String.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0) { v |= kv.Value; foundMatch = true; break; } } if (!foundMatch) { exception = new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, value)); return false; } // Move our pointer to the ending index to go again. valueIndex = endIndex + 1; } unsafe { result = RuntimeImports.RhBox(enumEEType, &v); //@todo: Not compatible with big-endian platforms. } return true; } private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int valueOffset, out Object result) { Debug.Assert(value != null, "Expected non-null value"); Debug.Assert(value.Length > 0, "Expected non-empty value"); Debug.Assert(valueOffset >= 0 && valueOffset < value.Length, "Expected valueOffset to be within value"); result = null; char firstNonWhitespaceChar = value[valueOffset]; if (!(Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-')) return false; RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType; value = value.Trim(); unsafe { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { Boolean v; if (!Boolean.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { Char v; if (!Char.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { SByte v; if (!SByte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { Byte v; if (!Byte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { Int16 v; if (!Int16.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { UInt16 v; if (!UInt16.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { Int32 v; if (!Int32.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { UInt32 v; if (!UInt32.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { Int64 v; if (!Int64.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { UInt64 v; if (!UInt64.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; } default: throw new NotSupportedException(); } } } // // Sort comparer for NamesAndValues // private class NamesAndValueComparer : IComparer<KeyValuePair<String, ulong>> { public int Compare(KeyValuePair<String, ulong> kv1, KeyValuePair<String, ulong> kv2) { ulong x = kv1.Value; ulong y = kv2.Value; if (x < y) return -1; else if (x > y) return 1; else return 0; } } private static bool IsIntegerType(Type t) { return (t == typeof(int) || t == typeof(short) || t == typeof(ushort) || t == typeof(byte) || t == typeof(sbyte) || t == typeof(uint) || t == typeof(long) || t == typeof(ulong) || t == typeof(char) || t == typeof(bool)); } private static NamesAndValueComparer s_nameAndValueComparer = new NamesAndValueComparer(); private String LastResortToString { get { return String.Format("{0}", GetValue()); } } private sealed class EnumInfoUnifier : ConcurrentUnifierW<RuntimeType, EnumInfo> { protected override EnumInfo Factory(RuntimeType key) { return RuntimeAugments.Callbacks.GetEnumInfoIfAvailable(key); } } private static EnumInfoUnifier s_enumInfoCache = new EnumInfoUnifier(); #region IConvertible TypeCode IConvertible.GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType(enumType); if (underlyingType == typeof(Int32)) { return TypeCode.Int32; } if (underlyingType == typeof(sbyte)) { return TypeCode.SByte; } if (underlyingType == typeof(Int16)) { return TypeCode.Int16; } if (underlyingType == typeof(Int64)) { return TypeCode.Int64; } if (underlyingType == typeof(UInt32)) { return TypeCode.UInt32; } if (underlyingType == typeof(byte)) { return TypeCode.Byte; } if (underlyingType == typeof(UInt16)) { return TypeCode.UInt16; } if (underlyingType == typeof(UInt64)) { return TypeCode.UInt64; } if (underlyingType == typeof(Boolean)) { return TypeCode.Boolean; } if (underlyingType == typeof(Char)) { return TypeCode.Char; } Contract.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion } }
using System; using System.IO; using System.Runtime.Serialization; using System.ServiceModel.Channels; using System.Text; using System.Xml; using NUnit.Framework; using NServiceKit.Messaging; using NServiceKit.ServiceModel.Serialization; using Message = System.ServiceModel.Channels.Message; using DataContractSerializer = NServiceKit.ServiceModel.Serialization.DataContractSerializer; namespace NServiceKit.WebHost.Endpoints.Tests { [DataContract(Namespace = "http://schemas.NServiceKit.net/types")] public class Reverse { /// <summary>Gets or sets the value.</summary> /// /// <value>The value.</value> /// <summary>Gets or sets the value.</summary> /// /// <value>The value.</value> [DataMember] public string Value { get; set; } } /// <summary>A message serialization tests.</summary> [TestFixture] public class MessageSerializationTests { static string xml = "<Reverse xmlns=\"http://schemas.NServiceKit.net/types\"><Value>test</Value></Reverse>"; Reverse request = new Reverse { Value = "test" }; string msgXml = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"><s:Body>" + xml + "</s:Body></s:Envelope>"; /// <summary>Can deserialize message from get body.</summary> [Test] public void Can_Deserialize_Message_from_GetBody() { var msg = Message.CreateMessage(MessageVersion.Default, "Reverse", request); //Console.WriteLine("BODY: " + msg.GetReaderAtBodyContents().ReadOuterXml()); var fromRequest = msg.GetBody<Reverse>(new System.Runtime.Serialization.DataContractSerializer(typeof(Reverse))); Assert.That(fromRequest.Value, Is.EqualTo(request.Value)); } /// <summary>Can deserialize message from get reader at body contents.</summary> [Test] public void Can_Deserialize_Message_from_GetReaderAtBodyContents() { var msg = Message.CreateMessage(MessageVersion.Default, "Reverse", request); using (var reader = msg.GetReaderAtBodyContents()) { var requestXml = reader.ReadOuterXml(); var fromRequest = (Reverse)DataContractDeserializer.Instance.Parse(requestXml, typeof(Reverse)); Assert.That(fromRequest.Value, Is.EqualTo(request.Value)); } } internal class SimpleBodyWriter : BodyWriter { private readonly string message; /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.MessageSerializationTests.SimpleBodyWriter class.</summary> /// /// <param name="message">The message.</param> public SimpleBodyWriter(string message) : base(false) { this.message = message; } /// <summary>When implemented, provides an extensibility point when the body contents are written.</summary> /// /// <param name="writer">The <see cref="T:System.Xml.XmlDictionaryWriter" /> used to write out the message body.</param> protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteRaw(message); } } /// <summary>Can create entire message from XML.</summary> [Test] public void Can_create_entire_message_from_xml() { //var msg = Message.CreateMessage(MessageVersion.Default, // "Reverse", new SimpleBodyWriter(msgXml)); var doc = new XmlDocument(); doc.LoadXml(msgXml); using (var xnr = new XmlNodeReader(doc)) { var msg = Message.CreateMessage(xnr, msgXml.Length, MessageVersion.Soap12WSAddressingAugust2004); var xml = msg.GetReaderAtBodyContents().ReadOuterXml(); Console.WriteLine("BODY: " + DataContractSerializer.Instance.Parse(request)); Console.WriteLine("EXPECTED BODY: " + xml); var fromRequest = (Reverse)DataContractDeserializer.Instance.Parse(xml, typeof(Reverse)); Assert.That(fromRequest.Value, Is.EqualTo(request.Value)); } //var fromRequest = msg.GetBody<Request>(new DataContractSerializer(typeof(Request))); } /// <summary>What do the different SOAP payloads look like.</summary> [Test] public void What_do_the_different_soap_payloads_look_like() { var doc = new XmlDocument(); doc.LoadXml(msgXml); //var action = "Request"; string action = null; var soap12 = Message.CreateMessage(MessageVersion.Soap12, action, request); var soap12WSAddressing10 = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, action, request); var soap12WSAddressingAugust2004 = Message.CreateMessage(MessageVersion.Soap12WSAddressingAugust2004, action, request); Console.WriteLine("Soap12: " + GetMessageEnvelope(soap12)); Console.WriteLine("Soap12WSAddressing10: " + GetMessageEnvelope(soap12WSAddressing10)); Console.WriteLine("Soap12WSAddressingAugust2004: " + GetMessageEnvelope(soap12WSAddressingAugust2004)); } /// <summary>Gets message envelope.</summary> /// /// <param name="msg">The message.</param> /// /// <returns>The message envelope.</returns> public string GetMessageEnvelope(Message msg) { var sb = new StringBuilder(); using (var sw = XmlWriter.Create(new StringWriter(sb))) { msg.WriteMessage(sw); sw.Flush(); return sb.ToString(); } } /// <summary>Gets request message.</summary> /// /// <param name="requestXml">The request XML.</param> /// /// <returns>The request message.</returns> protected static Message GetRequestMessage(string requestXml) { var doc = new XmlDocument(); doc.LoadXml(requestXml); var msg = Message.CreateMessage(new XmlNodeReader(doc), int.MaxValue, MessageVersion.Soap11WSAddressingAugust2004); //var msg = Message.CreateMessage(MessageVersion.Soap12WSAddressingAugust2004, // "*", new XmlBodyWriter(requestXml)); return msg; } /// <summary>Can create message from XML.</summary> [Test] public void Can_create_message_from_xml() { var requestXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>" + "<Reverse xmlns=\"http://schemas.NServiceKit.net/types\"><Value>Testing</Value></Reverse>" + "</soap:Body></soap:Envelope>"; var requestMsg = GetRequestMessage(requestXml); using (var reader = requestMsg.GetReaderAtBodyContents()) { requestXml = reader.ReadOuterXml(); } var requestType = typeof (Reverse); var request = (Reverse)DataContractDeserializer.Instance.Parse(requestXml, requestType); Assert.That(request.Value, Is.EqualTo("Testing")); } /// <summary>A dto body writer.</summary> public class DtoBodyWriter : BodyWriter { private readonly object dto; /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.MessageSerializationTests.DtoBodyWriter class.</summary> /// /// <param name="dto">The dto.</param> public DtoBodyWriter(object dto) : base(true) { this.dto = dto; } /// <summary>When implemented, provides an extensibility point when the body contents are written.</summary> /// /// <param name="writer">The <see cref="T:System.Xml.XmlDictionaryWriter" /> used to write out the message body.</param> protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { var xml = DataContractSerializer.Instance.Parse(dto); writer.WriteString(xml); } } /// <summary>An XML body writer.</summary> public class XmlBodyWriter : BodyWriter { private readonly string xml; /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.Tests.MessageSerializationTests.XmlBodyWriter class.</summary> /// /// <param name="xml">The XML.</param> public XmlBodyWriter(string xml) : base(true) { this.xml = xml; } /// <summary>When implemented, provides an extensibility point when the body contents are written.</summary> /// /// <param name="writer">The <see cref="T:System.Xml.XmlDictionaryWriter" /> used to write out the message body.</param> protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteString(xml); } } } }
#region PDFsharp Charting - A .NET charting library based on PDFsharp // // Authors: // Niklas Schneider // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using PdfSharp.Drawing; namespace PdfSharp.Charting.Renderers { /// <summary> /// Represents an axis renderer used for charts of type Bar2D. /// </summary> internal class VerticalXAxisRenderer : XAxisRenderer { /// <summary> /// Initializes a new instance of the VerticalXAxisRenderer class with the specified renderer parameters. /// </summary> internal VerticalXAxisRenderer(RendererParameters parms) : base(parms) { } /// <summary> /// Returns an initialized rendererInfo based on the X axis. /// </summary> internal override RendererInfo Init() { Chart chart = (Chart)_rendererParms.DrawingItem; AxisRendererInfo xari = new AxisRendererInfo(); xari._axis = chart._xAxis; if (xari._axis != null) { ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo; CalculateXAxisValues(xari); InitXValues(xari); InitAxisTitle(xari, cri.DefaultFont); InitTickLabels(xari, cri.DefaultFont); InitAxisLineFormat(xari); InitGridlines(xari); } return xari; } /// <summary> /// Calculates the space used for the X axis. /// </summary> internal override void Format() { AxisRendererInfo xari = ((ChartRendererInfo)_rendererParms.RendererInfo).xAxisRendererInfo; if (xari._axis != null) { AxisTitleRendererInfo atri = xari._axisTitleRendererInfo; // Calculate space used for axis title. XSize titleSize = new XSize(0, 0); if (atri != null && atri.AxisTitleText != null && atri.AxisTitleText.Length > 0) titleSize = _rendererParms.Graphics.MeasureString(atri.AxisTitleText, atri.AxisTitleFont); // Calculate space used for tick labels. XSize size = new XSize(0, 0); foreach (XSeries xs in xari.XValues) { foreach (XValue xv in xs) { XSize valueSize = _rendererParms.Graphics.MeasureString(xv._value, xari.TickLabelsFont); size.Height += valueSize.Height; size.Width = Math.Max(valueSize.Width, size.Width); } } // Remember space for later drawing. if (atri != null) atri.AxisTitleSize = titleSize; xari.TickLabelsHeight = size.Height; xari.Height = size.Height; xari.Width = titleSize.Width + size.Width + xari.MajorTickMarkWidth; } } /// <summary> /// Draws the horizontal X axis. /// </summary> internal override void Draw() { XGraphics gfx = _rendererParms.Graphics; ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo; AxisRendererInfo xari = cri.xAxisRendererInfo; double xMin = xari.MinimumScale; double xMax = xari.MaximumScale; double xMajorTick = xari.MajorTick; double xMinorTick = xari.MinorTick; double xMaxExtension = xari.MajorTick; // Draw tick labels. Each tick label will be aligned centered. int countTickLabels = (int)xMax; double tickLabelStep = xari.Height / countTickLabels; XPoint startPos = new XPoint(xari.X + xari.Width - xari.MajorTickMarkWidth, xari.Y + tickLabelStep / 2); foreach (XSeries xs in xari.XValues) { for (int idx = countTickLabels - 1; idx >= 0; --idx) { XValue xv = xs[idx]; string tickLabel = xv._value; XSize size = gfx.MeasureString(tickLabel, xari.TickLabelsFont); gfx.DrawString(tickLabel, xari.TickLabelsFont, xari.TickLabelsBrush, startPos.X - size.Width, startPos.Y + size.Height / 2); startPos.Y += tickLabelStep; } } // Draw axis. // First draw tick marks, second draw axis. double majorTickMarkStart = 0, majorTickMarkEnd = 0, minorTickMarkStart = 0, minorTickMarkEnd = 0; GetTickMarkPos(xari, ref majorTickMarkStart, ref majorTickMarkEnd, ref minorTickMarkStart, ref minorTickMarkEnd); LineFormatRenderer lineFormatRenderer = new LineFormatRenderer(gfx, xari.LineFormat); XPoint[] points = new XPoint[2]; // Minor ticks. if (xari.MinorTickMark != TickMarkType.None) { int countMinorTickMarks = (int)(xMax / xMinorTick); double minorTickMarkStep = xari.Height / countMinorTickMarks; startPos.Y = xari.Y; for (int x = 0; x <= countMinorTickMarks; x++) { points[0].X = minorTickMarkStart; points[0].Y = startPos.Y + minorTickMarkStep * x; points[1].X = minorTickMarkEnd; points[1].Y = points[0].Y; lineFormatRenderer.DrawLine(points[0], points[1]); } } // Major ticks. if (xari.MajorTickMark != TickMarkType.None) { int countMajorTickMarks = (int)(xMax / xMajorTick); double majorTickMarkStep = xari.Height / countMajorTickMarks; startPos.Y = xari.Y; for (int x = 0; x <= countMajorTickMarks; x++) { points[0].X = majorTickMarkStart; points[0].Y = startPos.Y + majorTickMarkStep * x; points[1].X = majorTickMarkEnd; points[1].Y = points[0].Y; lineFormatRenderer.DrawLine(points[0], points[1]); } } // Axis. if (xari.LineFormat != null) { points[0].X = xari.X + xari.Width; points[0].Y = xari.Y; points[1].X = xari.X + xari.Width; points[1].Y = xari.Y + xari.Height; if (xari.MajorTickMark != TickMarkType.None) { points[0].Y -= xari.LineFormat.Width / 2; points[1].Y += xari.LineFormat.Width / 2; } lineFormatRenderer.DrawLine(points[0], points[1]); } // Draw axis title. AxisTitleRendererInfo atri = xari._axisTitleRendererInfo; if (atri != null && atri.AxisTitleText != null && atri.AxisTitleText.Length > 0) { XRect rect = new XRect(xari.X, xari.Y + xari.Height / 2, atri.AxisTitleSize.Width, 0); gfx.DrawString(atri.AxisTitleText, atri.AxisTitleFont, atri.AxisTitleBrush, rect); } } /// <summary> /// Calculates the X axis describing values like minimum/maximum scale, major/minor tick and /// major/minor tick mark width. /// </summary> private void CalculateXAxisValues(AxisRendererInfo rendererInfo) { // Calculates the maximum number of data points over all series. SeriesCollection seriesCollection = ((Chart)rendererInfo._axis._parent)._seriesCollection; int count = 0; foreach (Series series in seriesCollection) count = Math.Max(count, series.Count); rendererInfo.MinimumScale = 0; rendererInfo.MaximumScale = count; // At least 0 rendererInfo.MajorTick = 1; rendererInfo.MinorTick = 0.5; rendererInfo.MajorTickMarkWidth = DefaultMajorTickMarkWidth; rendererInfo.MinorTickMarkWidth = DefaultMinorTickMarkWidth; } /// <summary> /// Initializes the rendererInfo's xvalues. If not set by the user xvalues will be simply numbers /// from minimum scale + 1 to maximum scale. /// </summary> private void InitXValues(AxisRendererInfo rendererInfo) { rendererInfo.XValues = ((Chart)rendererInfo._axis._parent)._xValues; if (rendererInfo.XValues == null) { rendererInfo.XValues = new XValues(); XSeries xs = rendererInfo.XValues.AddXSeries(); for (double i = rendererInfo.MinimumScale + 1; i <= rendererInfo.MaximumScale; ++i) xs.Add(i.ToString()); } } /// <summary> /// Calculates the starting and ending y position for the minor and major tick marks. /// </summary> private void GetTickMarkPos(AxisRendererInfo rendererInfo, ref double majorTickMarkStart, ref double majorTickMarkEnd, ref double minorTickMarkStart, ref double minorTickMarkEnd) { double majorTickMarkWidth = rendererInfo.MajorTickMarkWidth; double minorTickMarkWidth = rendererInfo.MinorTickMarkWidth; double x = rendererInfo.Rect.X + rendererInfo.Rect.Width; switch (rendererInfo.MajorTickMark) { case TickMarkType.Inside: majorTickMarkStart = x; majorTickMarkEnd = x + majorTickMarkWidth; break; case TickMarkType.Outside: majorTickMarkStart = x - majorTickMarkWidth; majorTickMarkEnd = x; break; case TickMarkType.Cross: majorTickMarkStart = x - majorTickMarkWidth; majorTickMarkEnd = x + majorTickMarkWidth; break; case TickMarkType.None: majorTickMarkStart = 0; majorTickMarkEnd = 0; break; } switch (rendererInfo.MinorTickMark) { case TickMarkType.Inside: minorTickMarkStart = x; minorTickMarkEnd = x + minorTickMarkWidth; break; case TickMarkType.Outside: minorTickMarkStart = x - minorTickMarkWidth; minorTickMarkEnd = x; break; case TickMarkType.Cross: minorTickMarkStart = x - minorTickMarkWidth; minorTickMarkEnd = x + minorTickMarkWidth; break; case TickMarkType.None: minorTickMarkStart = 0; minorTickMarkEnd = 0; break; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Capture execution context for a thread ** ** ===========================================================*/ namespace System.Threading { using System; using System.Security; using System.Runtime.Remoting; #if FEATURE_IMPERSONATION using System.Security.Principal; #endif using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.ExceptionServices; using System.Runtime.Serialization; using System.Security.Permissions; #if FEATURE_REMOTING using System.Runtime.Remoting.Messaging; #endif // FEATURE_REMOTING using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [System.Runtime.InteropServices.ComVisible(true)] public delegate void ContextCallback(Object state); #if FEATURE_CORECLR [SecurityCritical] internal struct ExecutionContextSwitcher { internal ExecutionContext m_ec; internal SynchronizationContext m_sc; internal void Undo(Thread currentThread) { Contract.Assert(currentThread == Thread.CurrentThread); // The common case is that these have not changed, so avoid the cost of a write if not needed. if (currentThread.SynchronizationContext != m_sc) { currentThread.SynchronizationContext = m_sc; } if (currentThread.ExecutionContext != m_ec) { ExecutionContext.Restore(currentThread, m_ec); } } } public sealed class ExecutionContext : IDisposable { private static readonly ExecutionContext Default = new ExecutionContext(); private readonly Dictionary<IAsyncLocal, object> m_localValues; private readonly IAsyncLocal[] m_localChangeNotifications; private ExecutionContext() { m_localValues = new Dictionary<IAsyncLocal, object>(); m_localChangeNotifications = Array.Empty<IAsyncLocal>(); } private ExecutionContext(Dictionary<IAsyncLocal, object> localValues, IAsyncLocal[] localChangeNotifications) { m_localValues = localValues; m_localChangeNotifications = localChangeNotifications; } [SecuritySafeCritical] public static ExecutionContext Capture() { return Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default; } [SecurityCritical] [HandleProcessCorruptedStateExceptions] public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state) { if (executionContext == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext")); Thread currentThread = Thread.CurrentThread; ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher); try { EstablishCopyOnWriteScope(currentThread, ref ecsw); ExecutionContext.Restore(currentThread, executionContext); callback(state); } catch { // Note: we have a "catch" rather than a "finally" because we want // to stop the first pass of EH here. That way we can restore the previous // context before any of our callers' EH filters run. That means we need to // end the scope separately in the non-exceptional case below. ecsw.Undo(currentThread); throw; } ecsw.Undo(currentThread); } [SecurityCritical] internal static void Restore(Thread currentThread, ExecutionContext executionContext) { Contract.Assert(currentThread == Thread.CurrentThread); ExecutionContext previous = currentThread.ExecutionContext ?? Default; currentThread.ExecutionContext = executionContext; // New EC could be null if that's what ECS.Undo saved off. // For the purposes of dealing with context change, treat this as the default EC executionContext = executionContext ?? Default; if (previous != executionContext) { OnContextChanged(previous, executionContext); } } [SecurityCritical] static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw) { Contract.Assert(currentThread == Thread.CurrentThread); ecsw.m_ec = currentThread.ExecutionContext; ecsw.m_sc = currentThread.SynchronizationContext; } [SecurityCritical] [HandleProcessCorruptedStateExceptions] private static void OnContextChanged(ExecutionContext previous, ExecutionContext current) { Contract.Assert(previous != null); Contract.Assert(current != null); Contract.Assert(previous != current); foreach (IAsyncLocal local in previous.m_localChangeNotifications) { object previousValue; object currentValue; previous.m_localValues.TryGetValue(local, out previousValue); current.m_localValues.TryGetValue(local, out currentValue); if (previousValue != currentValue) local.OnValueChanged(previousValue, currentValue, true); } if (current.m_localChangeNotifications != previous.m_localChangeNotifications) { try { foreach (IAsyncLocal local in current.m_localChangeNotifications) { // If the local has a value in the previous context, we already fired the event for that local // in the code above. object previousValue; if (!previous.m_localValues.TryGetValue(local, out previousValue)) { object currentValue; current.m_localValues.TryGetValue(local, out currentValue); if (previousValue != currentValue) local.OnValueChanged(previousValue, currentValue, true); } } } catch (Exception ex) { Environment.FailFast( Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"), ex); } } } [SecurityCritical] internal static object GetLocalValue(IAsyncLocal local) { ExecutionContext current = Thread.CurrentThread.ExecutionContext; if (current == null) return null; object value; current.m_localValues.TryGetValue(local, out value); return value; } [SecurityCritical] internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications) { ExecutionContext current = Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default; object previousValue; bool hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue); if (previousValue == newValue) return; // // Allocate a new Dictionary containing a copy of the old values, plus the new value. We have to do this manually to // minimize allocations of IEnumerators, etc. // Dictionary<IAsyncLocal, object> newValues = new Dictionary<IAsyncLocal, object>(current.m_localValues.Count + (hadPreviousValue ? 0 : 1)); foreach (KeyValuePair<IAsyncLocal, object> pair in current.m_localValues) newValues.Add(pair.Key, pair.Value); newValues[local] = newValue; // // Either copy the change notification array, or create a new one, depending on whether we need to add a new item. // IAsyncLocal[] newChangeNotifications = current.m_localChangeNotifications; if (needChangeNotifications) { if (hadPreviousValue) { Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0); } else { int newNotificationIndex = newChangeNotifications.Length; Array.Resize(ref newChangeNotifications, newNotificationIndex + 1); newChangeNotifications[newNotificationIndex] = local; } } Thread.CurrentThread.ExecutionContext = new ExecutionContext(newValues, newChangeNotifications); if (needChangeNotifications) { local.OnValueChanged(previousValue, newValue, false); } } #region Wrappers for CLR compat, to avoid ifdefs all over the BCL [Flags] internal enum CaptureOptions { None = 0x00, IgnoreSyncCtx = 0x01, OptimizeDefaultCase = 0x02, } [SecurityCritical] internal static ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions captureOptions) { return Capture(); } [SecuritySafeCritical] [FriendAccessAllowed] internal static ExecutionContext FastCapture() { return Capture(); } [SecurityCritical] [FriendAccessAllowed] internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx) { Run(executionContext, callback, state); } [SecurityCritical] internal bool IsDefaultFTContext(bool ignoreSyncCtx) { return this == Default; } [SecuritySafeCritical] public ExecutionContext CreateCopy() { return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies. } public void Dispose() { // For CLR compat only } public static bool IsFlowSuppressed() { return false; } internal static ExecutionContext PreAllocatedDefault { [SecuritySafeCritical] get { return ExecutionContext.Default; } } internal bool IsPreAllocatedDefault { get { return this == ExecutionContext.Default; } } #endregion } #else // FEATURE_CORECLR // Legacy desktop ExecutionContext implementation internal struct ExecutionContextSwitcher { internal ExecutionContext.Reader outerEC; // previous EC we need to restore on Undo internal bool outerECBelongsToScope; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK internal SecurityContextSwitcher scsw; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK internal Object hecsw; #if FEATURE_IMPERSONATION internal WindowsIdentity wi; internal bool cachedAlwaysFlowImpersonationPolicy; internal bool wiIsValid; #endif internal Thread thread; [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] #endif // FEATURE_CORRUPTING_EXCEPTIONS internal bool UndoNoThrow(Thread currentThread) { try { Undo(currentThread); } catch { return false; } return true; } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal void Undo(Thread currentThread) { // // Don't use an uninitialized switcher, or one that's already been used. // if (thread == null) return; // Don't do anything Contract.Assert(Thread.CurrentThread == this.thread); // // Restore the HostExecutionContext before restoring the ExecutionContext. // #if FEATURE_CAS_POLICY if (hecsw != null) HostExecutionContextSwitcher.Undo(hecsw); #endif // FEATURE_CAS_POLICY // // restore the saved Execution Context. Note that this will also restore the // SynchronizationContext, Logical/IllogicalCallContext, etc. // ExecutionContext.Reader innerEC = currentThread.GetExecutionContextReader(); currentThread.SetExecutionContext(outerEC, outerECBelongsToScope); #if DEBUG try { currentThread.ForbidExecutionContextMutation = true; #endif // // Tell the SecurityContext to do the side-effects of restoration. // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (scsw.currSC != null) { // Any critical failure inside scsw will cause FailFast scsw.Undo(); } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_IMPERSONATION if (wiIsValid) SecurityContext.RestoreCurrentWI(outerEC, innerEC, wi, cachedAlwaysFlowImpersonationPolicy); #endif thread = null; // this will prevent the switcher object being used again #if DEBUG } finally { currentThread.ForbidExecutionContextMutation = false; } #endif ExecutionContext.OnAsyncLocalContextChanged(innerEC.DangerousGetRawExecutionContext(), outerEC.DangerousGetRawExecutionContext()); } } public struct AsyncFlowControl: IDisposable { private bool useEC; private ExecutionContext _ec; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK private SecurityContext _sc; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK private Thread _thread; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK [SecurityCritical] internal void Setup(SecurityContextDisableFlow flags) { useEC = false; Thread currentThread = Thread.CurrentThread; _sc = currentThread.GetMutableExecutionContext().SecurityContext; _sc._disableFlow = flags; _thread = currentThread; } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK [SecurityCritical] internal void Setup() { useEC = true; Thread currentThread = Thread.CurrentThread; _ec = currentThread.GetMutableExecutionContext(); _ec.isFlowSuppressed = true; _thread = currentThread; } public void Dispose() { Undo(); } [SecuritySafeCritical] public void Undo() { if (_thread == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCMultiple")); } if (_thread != Thread.CurrentThread) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread")); } if (useEC) { if (Thread.CurrentThread.GetMutableExecutionContext() != _ec) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch")); } ExecutionContext.RestoreFlow(); } #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK else { if (!Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(_sc)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch")); } SecurityContext.RestoreFlow(); } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK _thread = null; } public override int GetHashCode() { return _thread == null ? ToString().GetHashCode() : _thread.GetHashCode(); } public override bool Equals(Object obj) { if (obj is AsyncFlowControl) return Equals((AsyncFlowControl)obj); else return false; } public bool Equals(AsyncFlowControl obj) { return obj.useEC == useEC && obj._ec == _ec && #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK obj._sc == _sc && #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK obj._thread == _thread; } public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b) { return a.Equals(b); } public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b) { return !(a == b); } } #if FEATURE_SERIALIZATION [Serializable] #endif public sealed class ExecutionContext : IDisposable, ISerializable { /*========================================================================= ** Data accessed from managed code that needs to be defined in ** ExecutionContextObject to maintain alignment between the two classes. ** DON'T CHANGE THESE UNLESS YOU MODIFY ExecutionContextObject in vm\object.h =========================================================================*/ #if FEATURE_CAS_POLICY private HostExecutionContext _hostExecutionContext; #endif // FEATURE_CAS_POLICY private SynchronizationContext _syncContext; private SynchronizationContext _syncContextNoFlow; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK private SecurityContext _securityContext; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_REMOTING [System.Security.SecurityCritical] // auto-generated private LogicalCallContext _logicalCallContext; private IllogicalCallContext _illogicalCallContext; // this call context follows the physical thread #endif // #if FEATURE_REMOTING enum Flags { None = 0x0, IsNewCapture = 0x1, IsFlowSuppressed = 0x2, IsPreAllocatedDefault = 0x4 } private Flags _flags; private Dictionary<IAsyncLocal, object> _localValues; private List<IAsyncLocal> _localChangeNotifications; internal bool isNewCapture { get { return (_flags & (Flags.IsNewCapture | Flags.IsPreAllocatedDefault)) != Flags.None; } set { Contract.Assert(!IsPreAllocatedDefault); if (value) _flags |= Flags.IsNewCapture; else _flags &= ~Flags.IsNewCapture; } } internal bool isFlowSuppressed { get { return (_flags & Flags.IsFlowSuppressed) != Flags.None; } set { Contract.Assert(!IsPreAllocatedDefault); if (value) _flags |= Flags.IsFlowSuppressed; else _flags &= ~Flags.IsFlowSuppressed; } } private static readonly ExecutionContext s_dummyDefaultEC = new ExecutionContext(isPreAllocatedDefault: true); static internal ExecutionContext PreAllocatedDefault { [SecuritySafeCritical] get { return s_dummyDefaultEC; } } internal bool IsPreAllocatedDefault { get { // we use _flags instead of a direct comparison w/ s_dummyDefaultEC to avoid the static access on // hot code paths. if ((_flags & Flags.IsPreAllocatedDefault) != Flags.None) { Contract.Assert(this == s_dummyDefaultEC); return true; } else { return false; } } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal ExecutionContext() { } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal ExecutionContext(bool isPreAllocatedDefault) { if (isPreAllocatedDefault) _flags = Flags.IsPreAllocatedDefault; } // Read-only wrapper around ExecutionContext. This enables safe reading of an ExecutionContext without accidentally modifying it. internal struct Reader { ExecutionContext m_ec; public Reader(ExecutionContext ec) { m_ec = ec; } public ExecutionContext DangerousGetRawExecutionContext() { return m_ec; } public bool IsNull { get { return m_ec == null; } } [SecurityCritical] public bool IsDefaultFTContext(bool ignoreSyncCtx) { return m_ec.IsDefaultFTContext(ignoreSyncCtx); } public bool IsFlowSuppressed { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return IsNull ? false : m_ec.isFlowSuppressed; } } //public Thread Thread { get { return m_ec._thread; } } public bool IsSame(ExecutionContext.Reader other) { return m_ec == other.m_ec; } public SynchronizationContext SynchronizationContext { get { return IsNull ? null : m_ec.SynchronizationContext; } } public SynchronizationContext SynchronizationContextNoFlow { get { return IsNull ? null : m_ec.SynchronizationContextNoFlow; } } #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK public SecurityContext.Reader SecurityContext { [SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new SecurityContext.Reader(IsNull ? null : m_ec.SecurityContext); } } #endif #if FEATURE_REMOTING public LogicalCallContext.Reader LogicalCallContext { [SecurityCritical] get { return new LogicalCallContext.Reader(IsNull ? null : m_ec.LogicalCallContext); } } public IllogicalCallContext.Reader IllogicalCallContext { [SecurityCritical] get { return new IllogicalCallContext.Reader(IsNull ? null : m_ec.IllogicalCallContext); } } #endif [SecurityCritical] public object GetLocalValue(IAsyncLocal local) { if (IsNull) return null; if (m_ec._localValues == null) return null; object value; m_ec._localValues.TryGetValue(local, out value); return value; } [SecurityCritical] public bool HasSameLocalValues(ExecutionContext other) { var thisLocalValues = IsNull ? null : m_ec._localValues; var otherLocalValues = other == null ? null : other._localValues; return thisLocalValues == otherLocalValues; } [SecurityCritical] public bool HasLocalValues() { return !this.IsNull && m_ec._localValues != null; } } [SecurityCritical] internal static object GetLocalValue(IAsyncLocal local) { return Thread.CurrentThread.GetExecutionContextReader().GetLocalValue(local); } [SecurityCritical] internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications) { ExecutionContext current = Thread.CurrentThread.GetMutableExecutionContext(); object previousValue = null; bool hadPreviousValue = current._localValues != null && current._localValues.TryGetValue(local, out previousValue); if (previousValue == newValue) return; if (current._localValues == null) current._localValues = new Dictionary<IAsyncLocal, object>(); else current._localValues = new Dictionary<IAsyncLocal, object>(current._localValues); current._localValues[local] = newValue; if (needChangeNotifications) { if (hadPreviousValue) { Contract.Assert(current._localChangeNotifications != null); Contract.Assert(current._localChangeNotifications.Contains(local)); } else { if (current._localChangeNotifications == null) current._localChangeNotifications = new List<IAsyncLocal>(); else current._localChangeNotifications = new List<IAsyncLocal>(current._localChangeNotifications); current._localChangeNotifications.Add(local); } local.OnValueChanged(previousValue, newValue, false); } } [SecurityCritical] [HandleProcessCorruptedStateExceptions] internal static void OnAsyncLocalContextChanged(ExecutionContext previous, ExecutionContext current) { List<IAsyncLocal> previousLocalChangeNotifications = (previous == null) ? null : previous._localChangeNotifications; if (previousLocalChangeNotifications != null) { foreach (IAsyncLocal local in previousLocalChangeNotifications) { object previousValue = null; if (previous != null && previous._localValues != null) previous._localValues.TryGetValue(local, out previousValue); object currentValue = null; if (current != null && current._localValues != null) current._localValues.TryGetValue(local, out currentValue); if (previousValue != currentValue) local.OnValueChanged(previousValue, currentValue, true); } } List<IAsyncLocal> currentLocalChangeNotifications = (current == null) ? null : current._localChangeNotifications; if (currentLocalChangeNotifications != null && currentLocalChangeNotifications != previousLocalChangeNotifications) { try { foreach (IAsyncLocal local in currentLocalChangeNotifications) { // If the local has a value in the previous context, we already fired the event for that local // in the code above. object previousValue = null; if (previous == null || previous._localValues == null || !previous._localValues.TryGetValue(local, out previousValue)) { object currentValue = null; if (current != null && current._localValues != null) current._localValues.TryGetValue(local, out currentValue); if (previousValue != currentValue) local.OnValueChanged(previousValue, currentValue, true); } } } catch (Exception ex) { Environment.FailFast( Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"), ex); } } } #if FEATURE_REMOTING internal LogicalCallContext LogicalCallContext { [System.Security.SecurityCritical] // auto-generated get { if (_logicalCallContext == null) { _logicalCallContext = new LogicalCallContext(); } return _logicalCallContext; } [System.Security.SecurityCritical] // auto-generated set { Contract.Assert(this != s_dummyDefaultEC); _logicalCallContext = value; } } internal IllogicalCallContext IllogicalCallContext { get { if (_illogicalCallContext == null) { _illogicalCallContext = new IllogicalCallContext(); } return _illogicalCallContext; } set { Contract.Assert(this != s_dummyDefaultEC); _illogicalCallContext = value; } } #endif // #if FEATURE_REMOTING internal SynchronizationContext SynchronizationContext { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return _syncContext; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { Contract.Assert(this != s_dummyDefaultEC); _syncContext = value; } } internal SynchronizationContext SynchronizationContextNoFlow { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return _syncContextNoFlow; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { Contract.Assert(this != s_dummyDefaultEC); _syncContextNoFlow = value; } } #if FEATURE_CAS_POLICY internal HostExecutionContext HostExecutionContext { get { return _hostExecutionContext; } set { Contract.Assert(this != s_dummyDefaultEC); _hostExecutionContext = value; } } #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK internal SecurityContext SecurityContext { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return _securityContext; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { Contract.Assert(this != s_dummyDefaultEC); // store the new security context _securityContext = value; // perform the reverse link too if (value != null) _securityContext.ExecutionContext = this; } } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK public void Dispose() { if(this.IsPreAllocatedDefault) return; //Do nothing if this is the default context #if FEATURE_CAS_POLICY if (_hostExecutionContext != null) _hostExecutionContext.Dispose(); #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null) _securityContext.Dispose(); #endif //FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK } [DynamicSecurityMethod] [System.Security.SecurityCritical] // auto-generated_required public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state) { if (executionContext == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext")); if (!executionContext.isNewCapture) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext")); Run(executionContext, callback, state, false); } // This method is special from a security perspective - the VM will not allow a stack walk to // continue past the call to ExecutionContext.Run. If you change the signature to this method, make // sure to update SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new signature. [DynamicSecurityMethod] [SecurityCritical] [FriendAccessAllowed] internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx) { RunInternal(executionContext, callback, state, preserveSyncCtx); } // Actual implementation of Run is here, in a non-DynamicSecurityMethod, because the JIT seems to refuse to inline callees into // a DynamicSecurityMethod. [SecurityCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] [HandleProcessCorruptedStateExceptions] internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx) { Contract.Assert(executionContext != null); if (executionContext.IsPreAllocatedDefault) { Contract.Assert(executionContext.IsDefaultFTContext(preserveSyncCtx)); } else { Contract.Assert(executionContext.isNewCapture); executionContext.isNewCapture = false; } Thread currentThread = Thread.CurrentThread; ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher); RuntimeHelpers.PrepareConstrainedRegions(); try { ExecutionContext.Reader ec = currentThread.GetExecutionContextReader(); if ( (ec.IsNull || ec.IsDefaultFTContext(preserveSyncCtx)) && #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) && #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK executionContext.IsDefaultFTContext(preserveSyncCtx) && ec.HasSameLocalValues(executionContext) ) { // Neither context is interesting, so we don't need to set the context. // We do need to reset any changes made by the user's callback, // so here we establish a "copy-on-write scope". Any changes will // result in a copy of the context being made, preserving the original // context. EstablishCopyOnWriteScope(currentThread, true, ref ecsw); } else { if (executionContext.IsPreAllocatedDefault) executionContext = new ExecutionContext(); ecsw = SetExecutionContext(executionContext, preserveSyncCtx); } // // Call the user's callback // callback(state); } finally { ecsw.Undo(currentThread); } } [SecurityCritical] static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw) { EstablishCopyOnWriteScope(currentThread, false, ref ecsw); } [SecurityCritical] static private void EstablishCopyOnWriteScope(Thread currentThread, bool knownNullWindowsIdentity, ref ExecutionContextSwitcher ecsw) { Contract.Assert(currentThread == Thread.CurrentThread); ecsw.outerEC = currentThread.GetExecutionContextReader(); ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope; #if FEATURE_IMPERSONATION ecsw.cachedAlwaysFlowImpersonationPolicy = SecurityContext.AlwaysFlowImpersonationPolicy; if (knownNullWindowsIdentity) Contract.Assert(SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy) == null); else ecsw.wi = SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy); ecsw.wiIsValid = true; #endif currentThread.ExecutionContextBelongsToCurrentScope = false; ecsw.thread = currentThread; } // Sets the given execution context object on the thread. // Returns the previous one. [System.Security.SecurityCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] #endif // FEATURE_CORRUPTING_EXCEPTIONS internal static ExecutionContextSwitcher SetExecutionContext(ExecutionContext executionContext, bool preserveSyncCtx) { #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK Contract.Assert(executionContext != null); Contract.Assert(executionContext != s_dummyDefaultEC); // Set up the switcher object to return; ExecutionContextSwitcher ecsw = new ExecutionContextSwitcher(); Thread currentThread = Thread.CurrentThread; ExecutionContext.Reader outerEC = currentThread.GetExecutionContextReader(); ecsw.thread = currentThread; ecsw.outerEC = outerEC; ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope; if (preserveSyncCtx) executionContext.SynchronizationContext = outerEC.SynchronizationContext; executionContext.SynchronizationContextNoFlow = outerEC.SynchronizationContextNoFlow; currentThread.SetExecutionContext(executionContext, belongsToCurrentScope: true); RuntimeHelpers.PrepareConstrainedRegions(); try { OnAsyncLocalContextChanged(outerEC.DangerousGetRawExecutionContext(), executionContext); #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK //set the security context SecurityContext sc = executionContext.SecurityContext; if (sc != null) { // non-null SC: needs to be set SecurityContext.Reader prevSeC = outerEC.SecurityContext; ecsw.scsw = SecurityContext.SetSecurityContext(sc, prevSeC, false, ref stackMark); } else if (!SecurityContext.CurrentlyInDefaultFTSecurityContext(ecsw.outerEC)) { // null incoming SC, but we're currently not in FT: use static FTSC to set SecurityContext.Reader prevSeC = outerEC.SecurityContext; ecsw.scsw = SecurityContext.SetSecurityContext(SecurityContext.FullTrustSecurityContext, prevSeC, false, ref stackMark); } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_CAS_POLICY // set the Host Context HostExecutionContext hostContext = executionContext.HostExecutionContext; if (hostContext != null) { ecsw.hecsw = HostExecutionContextManager.SetHostExecutionContextInternal(hostContext); } #endif // FEATURE_CAS_POLICY } catch { ecsw.UndoNoThrow(currentThread); throw; } return ecsw; } // // Public CreateCopy. Used to copy captured ExecutionContexts so they can be reused multiple times. // This should only copy the portion of the context that we actually capture. // [SecuritySafeCritical] public ExecutionContext CreateCopy() { if (!isNewCapture) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotCopyUsedContext")); } ExecutionContext ec = new ExecutionContext(); ec.isNewCapture = true; ec._syncContext = _syncContext == null ? null : _syncContext.CreateCopy(); ec._localValues = _localValues; ec._localChangeNotifications = _localChangeNotifications; #if FEATURE_CAS_POLICY // capture the host execution context ec._hostExecutionContext = _hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy(); #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null) { ec._securityContext = _securityContext.CreateCopy(); ec._securityContext.ExecutionContext = ec; } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_REMOTING if (this._logicalCallContext != null) ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone(); Contract.Assert(this._illogicalCallContext == null); #endif // #if FEATURE_REMOTING return ec; } // // Creates a complete copy, used for copy-on-write. // [SecuritySafeCritical] internal ExecutionContext CreateMutableCopy() { Contract.Assert(!this.isNewCapture); ExecutionContext ec = new ExecutionContext(); // We don't deep-copy the SyncCtx, since we're still in the same context after copy-on-write. ec._syncContext = this._syncContext; ec._syncContextNoFlow = this._syncContextNoFlow; #if FEATURE_CAS_POLICY // capture the host execution context ec._hostExecutionContext = this._hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy(); #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null) { ec._securityContext = this._securityContext.CreateMutableCopy(); ec._securityContext.ExecutionContext = ec; } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_REMOTING if (this._logicalCallContext != null) ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone(); if (this._illogicalCallContext != null) ec.IllogicalCallContext = (IllogicalCallContext)this.IllogicalCallContext.CreateCopy(); #endif // #if FEATURE_REMOTING ec._localValues = this._localValues; ec._localChangeNotifications = this._localChangeNotifications; ec.isFlowSuppressed = this.isFlowSuppressed; return ec; } [System.Security.SecurityCritical] // auto-generated_required public static AsyncFlowControl SuppressFlow() { if (IsFlowSuppressed()) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes")); } Contract.EndContractBlock(); AsyncFlowControl afc = new AsyncFlowControl(); afc.Setup(); return afc; } [SecuritySafeCritical] public static void RestoreFlow() { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); if (!ec.isFlowSuppressed) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow")); } ec.isFlowSuppressed = false; } [Pure] public static bool IsFlowSuppressed() { return Thread.CurrentThread.GetExecutionContextReader().IsFlowSuppressed; } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static ExecutionContext Capture() { // set up a stack mark for finding the caller StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return ExecutionContext.Capture(ref stackMark, CaptureOptions.None); } // // Captures an ExecutionContext with optimization for the "default" case, and captures a "null" synchronization context. // When calling ExecutionContext.Run on the returned context, specify ignoreSyncCtx = true // [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [FriendAccessAllowed] internal static ExecutionContext FastCapture() { // set up a stack mark for finding the caller StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return ExecutionContext.Capture(ref stackMark, CaptureOptions.IgnoreSyncCtx | CaptureOptions.OptimizeDefaultCase); } [Flags] internal enum CaptureOptions { None = 0x00, IgnoreSyncCtx = 0x01, //Don't flow SynchronizationContext OptimizeDefaultCase = 0x02, //Faster in the typical case, but can't show the result to users // because they could modify the shared default EC. // Use this only if you won't be exposing the captured EC to users. } // internal helper to capture the current execution context using a passed in stack mark [System.Security.SecurityCritical] // auto-generated static internal ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions options) { ExecutionContext.Reader ecCurrent = Thread.CurrentThread.GetExecutionContextReader(); // check to see if Flow is suppressed if (ecCurrent.IsFlowSuppressed) return null; // // Attempt to capture context. There may be nothing to capture... // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK // capture the security context SecurityContext secCtxNew = SecurityContext.Capture(ecCurrent, ref stackMark); #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_CAS_POLICY // capture the host execution context HostExecutionContext hostCtxNew = HostExecutionContextManager.CaptureHostExecutionContext(); #endif // FEATURE_CAS_POLICY SynchronizationContext syncCtxNew = null; #if FEATURE_REMOTING LogicalCallContext logCtxNew = null; #endif if (!ecCurrent.IsNull) { // capture the sync context if (0 == (options & CaptureOptions.IgnoreSyncCtx)) syncCtxNew = (ecCurrent.SynchronizationContext == null) ? null : ecCurrent.SynchronizationContext.CreateCopy(); #if FEATURE_REMOTING // copy over the Logical Call Context if (ecCurrent.LogicalCallContext.HasInfo) logCtxNew = ecCurrent.LogicalCallContext.Clone(); #endif // #if FEATURE_REMOTING } Dictionary<IAsyncLocal, object> localValues = null; List<IAsyncLocal> localChangeNotifications = null; if (!ecCurrent.IsNull) { localValues = ecCurrent.DangerousGetRawExecutionContext()._localValues; localChangeNotifications = ecCurrent.DangerousGetRawExecutionContext()._localChangeNotifications; } // // If we didn't get anything but defaults, and we're allowed to return the // dummy default EC, don't bother allocating a new context. // if (0 != (options & CaptureOptions.OptimizeDefaultCase) && #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK secCtxNew == null && #endif #if FEATURE_CAS_POLICY hostCtxNew == null && #endif // FEATURE_CAS_POLICY syncCtxNew == null && #if FEATURE_REMOTING (logCtxNew == null || !logCtxNew.HasInfo) && #endif // #if FEATURE_REMOTING localValues == null && localChangeNotifications == null ) { return s_dummyDefaultEC; } // // Allocate the new context, and fill it in. // ExecutionContext ecNew = new ExecutionContext(); #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK ecNew.SecurityContext = secCtxNew; if (ecNew.SecurityContext != null) ecNew.SecurityContext.ExecutionContext = ecNew; #endif #if FEATURE_CAS_POLICY ecNew._hostExecutionContext = hostCtxNew; #endif // FEATURE_CAS_POLICY ecNew._syncContext = syncCtxNew; #if FEATURE_REMOTING ecNew.LogicalCallContext = logCtxNew; #endif // #if FEATURE_REMOTING ecNew._localValues = localValues; ecNew._localChangeNotifications = localChangeNotifications; ecNew.isNewCapture = true; return ecNew; } // // Implementation of ISerializable // [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); #if FEATURE_REMOTING if (_logicalCallContext != null) { info.AddValue("LogicalCallContext", _logicalCallContext, typeof(LogicalCallContext)); } #endif // #if FEATURE_REMOTING } [System.Security.SecurityCritical] // auto-generated private ExecutionContext(SerializationInfo info, StreamingContext context) { SerializationInfoEnumerator e = info.GetEnumerator(); while (e.MoveNext()) { #if FEATURE_REMOTING if (e.Name.Equals("LogicalCallContext")) { _logicalCallContext = (LogicalCallContext) e.Value; } #endif // #if FEATURE_REMOTING } } // ObjRef .ctor [System.Security.SecurityCritical] // auto-generated internal bool IsDefaultFTContext(bool ignoreSyncCtx) { #if FEATURE_CAS_POLICY if (_hostExecutionContext != null) return false; #endif // FEATURE_CAS_POLICY if (!ignoreSyncCtx && _syncContext != null) return false; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext()) return false; #endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_REMOTING if (_logicalCallContext != null && _logicalCallContext.HasInfo) return false; if (_illogicalCallContext != null && _illogicalCallContext.HasUserData) return false; #endif //#if FEATURE_REMOTING return true; } } // class ExecutionContext #endif //FEATURE_CORECLR }
#region Header // -------------------------------------------------------------------------- // Tethys.Silverlight // ========================================================================== // // This library contains common code for WPF, Silverlight, Windows Phone and // Windows 8 projects. // // =========================================================================== // // <copyright file="MD5.cs" company="Tethys"> // Copyright 2010-2015 by Thomas Graf // All rights reserved. // Licensed under the Apache License, Version 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. // </copyright> // // System ... Microsoft .Net Framework 4.5 // Tools .... Microsoft Visual Studio 2013 // // --------------------------------------------------------------------------- /* Copyright (C) 1991, RSA Data Security, Inc. All rights reserved. License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. These notices must be retained in any copies of any part of this documentation and/or software. */ #endregion // In the Windows Phone 7 Framework is no support for cryptography // and thus no class HasAlgorithm. This implementation supports // both: the .Net Framework and the .Net Compact Framework. namespace Tethys.Silverlight.Cryptography { using System; using System.Security.Cryptography; /// <summary> /// The class MD5 implements the <c>RSA Data Security, Inc.</c> /// MD5 Message Digest Algorithm. /// </summary> public sealed class MD5 : HashAlgorithm { // =================================================================== // CHECKSUM RESULTS // =================================================================== // TEST1 is the three character sequence "ABC". // TEST2 is the three character sequence "CBA". // TEST3 is the eight character sequence of "12345678" // TEST4 is the 1024 character sequence of "12345678" // repeated 128 times. // // Value // --------- // MD5(TEST1) = 90 2F BD D2 B1 DF 0C 4F 70 B4 A5 D2 35 25 E9 32 // MD5(TEST2) = A6 1A 40 94 3E 07 25 7E 08 4E A3 F6 2D FD B1 C8 // MD5(TEST3) = 25 D5 5A D2 83 AA 40 0A F4 64 C7 6D 71 3C 07 AD // MD5(TEST4) = 89 F8 B6 EB 65 9B 80 F8 1B 22 A0 4F 27 E3 A8 63 // MD5("") = d41d8cd98f00b204e9800998ecf8427e // MD5("a") = 0cc175b9c0f1b6a831c399e269772661 // MD5("abc") = 900150983cd24fb0d6963f7d28e17f72 // MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0 // MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b // =================================================================== // ---- Constants for MD5Transform routine. --- /// <summary> /// The S11 value. /// </summary> private const int S11 = 7; /// <summary> /// The S12 value. /// </summary> private const int S12 = 12; /// <summary> /// The S13 value. /// </summary> private const int S13 = 17; /// <summary> /// The S14 value. /// </summary> private const int S14 = 22; /// <summary> /// The S21 value. /// </summary> private const int S21 = 5; /// <summary> /// The S22 value. /// </summary> private const int S22 = 9; /// <summary> /// The S23 value. /// </summary> private const int S23 = 14; /// <summary> /// The S24 value. /// </summary> private const int S24 = 20; /// <summary> /// The S31 value. /// </summary> private const int S31 = 4; /// <summary> /// The S32 value. /// </summary> private const int S32 = 11; /// <summary> /// The S33 value. /// </summary> private const int S33 = 16; /// <summary> /// The S34 value. /// </summary> private const int S34 = 23; /// <summary> /// The S41 value. /// </summary> private const int S41 = 6; /// <summary> /// The S42 value. /// </summary> private const int S42 = 10; /// <summary> /// The S43 value. /// </summary> private const int S43 = 15; /// <summary> /// The S44 value. /// </summary> private const int S44 = 21; /// <summary> /// Padding buffer. /// </summary> private static readonly byte[] Padding = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /// <summary> /// Hash size in bits. /// </summary> private const int HashSizeBits = 128; /// <summary> /// Hash size in bytes. /// </summary> private const int HashSizeBytes = 16; /// <summary> /// MD5 context: state (ABCD). /// </summary> private readonly UInt32[] ctxState; /// <summary> /// MD5 context: number of bits, modulo 2^64 (lsb first). /// </summary> private readonly UInt32[] ctxCount; /// <summary> /// MD5 context: input buffer. /// </summary> private readonly byte[] ctxBuffer; #region PUBLIC HASH ALGORITHM METHODS /// <summary> /// Initializes a new instance of the <see cref="MD5"/> class. /// </summary> public MD5() { this.HashSizeValue = HashSizeBits; this.HashValue = new byte[HashSizeBytes]; this.ctxState = new UInt32[4]; this.ctxCount = new UInt32[2]; this.ctxBuffer = new byte[64]; this.Initialize(); } // MD5() /// <summary> /// MD5 initialization. Begins an MD5 operation, writing a new context.<br/> /// </summary> public override void Initialize() { this.ctxCount[0] = 0; this.ctxCount[1] = 0; // Load magic initialization constants. this.ctxState[0] = 0x67452301; this.ctxState[1] = 0xefcdab89; this.ctxState[2] = 0x98badcfe; this.ctxState[3] = 0x10325476; for (int i = 0; i < 64; i++) { this.ctxBuffer[i] = 0; } // for } // Initialize() #endregion // PUBLIC HASH ALGORITHM METHODS #region PROTECTED HASH ALGORITHM METHODS #region BASIC MD5 FUNCTIONS // ----------------------------------- // F, G, H and I are basic MD5 functions. // ----------------------------------- /// <summary> /// Basic MD5 function F(). /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> /// <returns>F() return value.</returns> private static UInt32 F(UInt32 x, UInt32 y, UInt32 z) { return (((x) & (y)) | ((~x) & (z))); } // F() /// <summary> /// Basic MD5 function G(). /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> /// <returns>G() return value.</returns> private static UInt32 G(UInt32 x, UInt32 y, UInt32 z) { return (((x) & (z)) | ((y) & (~z))); } // G() /// <summary> /// Basic MD5 function H(). /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> /// <returns>H() return value.</returns> private static UInt32 H(UInt32 x, UInt32 y, UInt32 z) { return ((x) ^ (y) ^ (z)); } // H() /// <summary> /// Basic MD5 function I(). /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> /// <returns> /// I() return value. /// </returns> private static UInt32 I(UInt32 x, UInt32 y, UInt32 z) { return ((y) ^ ((x) | (~z))); } // H() #endregion // BASIC MD5 FUNCTIONS #region MD5 TRANSFORMATIONS // FF, GG and HH are transformations for rounds 1, 2, 3 and 4. // Rotation is separate from addition to prevent recomputation /// <summary> /// MD5 transformation FF(). /// </summary> /// <param name="a">The a value.</param> /// <param name="b">The b value.</param> /// <param name="c">The c value.</param> /// <param name="d">The d value.</param> /// <param name="x">The x value.</param> /// <param name="s">The s value.</param> /// <param name="ac">The ac value.</param> private static void FF(ref UInt32 a, UInt32 b, UInt32 c, UInt32 d, UInt32 x, byte s, UInt32 ac) { a += F(b, c, d) + x + ac; a = HashSupport.RotateLeft(a, s); a += b; } // FF() /// <summary> /// MD5 transformation GG(). /// </summary> /// <param name="a">The a value.</param> /// <param name="b">The b value.</param> /// <param name="c">The c value.</param> /// <param name="d">The d value.</param> /// <param name="x">The x value.</param> /// <param name="s">The s value.</param> /// <param name="ac">The ac value.</param> private static void GG(ref UInt32 a, UInt32 b, UInt32 c, UInt32 d, UInt32 x, byte s, UInt32 ac) { a += G(b, c, d) + x + ac; a = HashSupport.RotateLeft(a, s); a += b; } // GG() /// <summary> /// MD5 transformation HH(). /// </summary> /// <param name="a">The a value.</param> /// <param name="b">The b value.</param> /// <param name="c">The c value.</param> /// <param name="d">The d value.</param> /// <param name="x">The x value.</param> /// <param name="s">The s value.</param> /// <param name="ac">The ac value.</param> private static void HH(ref UInt32 a, UInt32 b, UInt32 c, UInt32 d, UInt32 x, byte s, UInt32 ac) { a += H(b, c, d) + x + ac; a = HashSupport.RotateLeft(a, s); a += b; } // HH() /// <summary> /// MD5 transformation II(). /// </summary> /// <param name="a">The a value.</param> /// <param name="b">The b value.</param> /// <param name="c">The c value.</param> /// <param name="d">The d value.</param> /// <param name="x">The x value.</param> /// <param name="s">The s value.</param> /// <param name="ac">The ac value.</param> private static void II(ref UInt32 a, UInt32 b, UInt32 c, UInt32 d, UInt32 x, byte s, UInt32 ac) { a += I(b, c, d) + x + ac; a = HashSupport.RotateLeft(a, s); a += b; } // HH() #endregion // MD5 TRANSFORMATIONS /// <summary> /// MD5 block update operation. Continues an MD5 message-digest operation, /// processing another message block, and updating the context. /// </summary> /// <param name="input">The input for which to compute the hash code. </param> /// <param name="offset">The offset into the byte array from which to begin using data. </param> /// <param name="inputLen">The number of bytes in the byte array to use as data.</param> protected override void HashCore(byte[] input, int offset, int inputLen) { int i; // Compute number of bytes mod 64 var index = (int)((this.ctxCount[0] >> 3) & 0x3F); // Update number of bits this.ctxCount[0] += (UInt32)(inputLen << 3); if (this.ctxCount[0] < ((UInt32)inputLen << 3)) { this.ctxCount[1]++; } // if this.ctxCount[1] += ((UInt32)inputLen >> 29); var partLen = 64 - index; // Transform as many times as possible. if (inputLen >= partLen) { HashSupport.MemCpy(this.ctxBuffer, index, input, 0, partLen); MD5Transform(this.ctxState, this.ctxBuffer); for (i = partLen; i + 63 < inputLen; i += 64) { MD5Transform(this.ctxState, input); } // for index = 0; } else { i = 0; } // if // Buffer remaining input HashSupport.MemCpy(this.ctxBuffer, index, input, i, inputLen - i); } // HashCore() /// <summary> /// MD5 basic transformation. Transforms state and updates checksum /// based on block. /// </summary> /// <param name="state">The state.</param> /// <param name="block">The block.</param> private static void MD5Transform(UInt32[] state, byte[] block) { UInt32 a = state[0]; UInt32 b = state[1]; UInt32 c = state[2]; UInt32 d = state[3]; UInt32[] x = new UInt32[16]; HashSupport.Decode(x, block, 64); // Round 1 FF(ref a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ FF(ref d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ FF(ref c, d, a, b, x[2], S13, 0x242070db); /* 3 */ FF(ref b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ FF(ref a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ FF(ref d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ FF(ref c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ FF(ref b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ FF(ref a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ FF(ref d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ FF(ref c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF(ref b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF(ref a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF(ref d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF(ref c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF(ref b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ // Round 2 GG(ref a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ GG(ref d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ GG(ref c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG(ref b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ GG(ref a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ GG(ref d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG(ref c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG(ref b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ GG(ref a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ GG(ref d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG(ref c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ GG(ref b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ GG(ref a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG(ref d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ GG(ref c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ GG(ref b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ // Round 3 HH(ref a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ HH(ref d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ HH(ref c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH(ref b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH(ref a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ HH(ref d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ HH(ref c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ HH(ref b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH(ref a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH(ref d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ HH(ref c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ HH(ref b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ HH(ref a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ HH(ref d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH(ref c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH(ref b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ // Round II(ref a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ II(ref d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ II(ref c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II(ref b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ II(ref a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II(ref d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ II(ref c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II(ref b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ II(ref a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ II(ref d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II(ref c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ II(ref b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II(ref a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ II(ref d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II(ref c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ II(ref b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; // Zeroize sensitive information. HashSupport.ZeroMemory(x, x.Length); } // MD5Transform() /// <summary> /// MD5 finalization. Ends an MD5 message-digest operation, writing the /// message digest and setting the context to zero. /// </summary> /// <returns>The computed hash code.</returns> protected override byte[] HashFinal() { var bits = new byte[8]; // Save number of bits HashSupport.Encode(bits, this.ctxCount, 8); // Pad out to 56 mod 64. var index = (int)((this.ctxCount[0] >> 3) & 0x3f); var padLen = (index < 56) ? (56 - index) : (120 - index); this.HashCore(Padding, 0, padLen); // Append length (before padding) this.HashCore(bits, 0, 8); // Store state in digest HashSupport.Encode(this.HashValue, this.ctxState, 16); // Zeroize sensitive information. HashSupport.ZeroMemory(this.ctxState, this.ctxState.Length); HashSupport.ZeroMemory(this.ctxCount, this.ctxCount.Length); HashSupport.MemSet(this.ctxBuffer, 0, this.ctxBuffer.Length); return this.HashValue; } // HashFinal() #endregion // PROTECTED HASH ALGORITHM METHODS } // MD5 } // Tethys.Silverlight.Cryptography
using System; using System.Runtime; namespace System.Management { public class RelatedObjectQuery : WqlObjectQuery { private readonly static string tokenAssociators; private readonly static string tokenOf; private readonly static string tokenWhere; private readonly static string tokenResultClass; private readonly static string tokenAssocClass; private readonly static string tokenResultRole; private readonly static string tokenRole; private readonly static string tokenRequiredQualifier; private readonly static string tokenRequiredAssocQualifier; private readonly static string tokenClassDefsOnly; private readonly static string tokenSchemaOnly; private bool isSchemaQuery; private string sourceObject; private string relatedClass; private string relationshipClass; private string relatedQualifier; private string relationshipQualifier; private string relatedRole; private string thisRole; private bool classDefinitionsOnly; public bool ClassDefinitionsOnly { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.classDefinitionsOnly; } set { this.classDefinitionsOnly = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public bool IsSchemaQuery { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.isSchemaQuery; } set { this.isSchemaQuery = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string RelatedClass { get { if (this.relatedClass != null) { return this.relatedClass; } else { return string.Empty; } } set { this.relatedClass = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string RelatedQualifier { get { if (this.relatedQualifier != null) { return this.relatedQualifier; } else { return string.Empty; } } set { this.relatedQualifier = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string RelatedRole { get { if (this.relatedRole != null) { return this.relatedRole; } else { return string.Empty; } } set { this.relatedRole = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string RelationshipClass { get { if (this.relationshipClass != null) { return this.relationshipClass; } else { return string.Empty; } } set { this.relationshipClass = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string RelationshipQualifier { get { if (this.relationshipQualifier != null) { return this.relationshipQualifier; } else { return string.Empty; } } set { this.relationshipQualifier = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string SourceObject { get { if (this.sourceObject != null) { return this.sourceObject; } else { return string.Empty; } } set { this.sourceObject = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string ThisRole { get { if (this.thisRole != null) { return this.thisRole; } else { return string.Empty; } } set { this.thisRole = value; this.BuildQuery(); base.FireIdentifierChanged(); } } static RelatedObjectQuery() { RelatedObjectQuery.tokenAssociators = "associators"; RelatedObjectQuery.tokenOf = "of"; RelatedObjectQuery.tokenWhere = "where"; RelatedObjectQuery.tokenResultClass = "resultclass"; RelatedObjectQuery.tokenAssocClass = "assocclass"; RelatedObjectQuery.tokenResultRole = "resultrole"; RelatedObjectQuery.tokenRole = "role"; RelatedObjectQuery.tokenRequiredQualifier = "requiredqualifier"; RelatedObjectQuery.tokenRequiredAssocQualifier = "requiredassocqualifier"; RelatedObjectQuery.tokenClassDefsOnly = "classdefsonly"; RelatedObjectQuery.tokenSchemaOnly = "schemaonly"; } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public RelatedObjectQuery() : this(null) { } public RelatedObjectQuery(string queryOrSourceObject) { if (queryOrSourceObject == null) { return; } else { if (!queryOrSourceObject.TrimStart(new char[0]).StartsWith(RelatedObjectQuery.tokenAssociators, StringComparison.OrdinalIgnoreCase)) { ManagementPath managementPath = new ManagementPath(queryOrSourceObject); if ((managementPath.IsClass || managementPath.IsInstance) && managementPath.NamespacePath.Length == 0) { this.SourceObject = queryOrSourceObject; this.isSchemaQuery = false; return; } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "queryOrSourceObject"); } } else { this.QueryString = queryOrSourceObject; return; } } } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public RelatedObjectQuery(string sourceObject, string relatedClass) : this(sourceObject, relatedClass, null, null, null, null, null, false) { } public RelatedObjectQuery(string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly) { this.isSchemaQuery = false; this.sourceObject = sourceObject; this.relatedClass = relatedClass; this.relationshipClass = relationshipClass; this.relatedQualifier = relatedQualifier; this.relationshipQualifier = relationshipQualifier; this.relatedRole = relatedRole; this.thisRole = thisRole; this.classDefinitionsOnly = classDefinitionsOnly; this.BuildQuery(); } public RelatedObjectQuery(bool isSchemaQuery, string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole) { if (isSchemaQuery) { this.isSchemaQuery = true; this.sourceObject = sourceObject; this.relatedClass = relatedClass; this.relationshipClass = relationshipClass; this.relatedQualifier = relatedQualifier; this.relationshipQualifier = relationshipQualifier; this.relatedRole = relatedRole; this.thisRole = thisRole; this.classDefinitionsOnly = false; this.BuildQuery(); return; } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "isSchemaQuery"); } } protected internal void BuildQuery() { if (this.sourceObject == null) { base.SetQueryString(string.Empty); } if (this.sourceObject == null || this.sourceObject.Length == 0) { return; } else { string[] strArrays = new string[6]; strArrays[0] = RelatedObjectQuery.tokenAssociators; strArrays[1] = " "; strArrays[2] = RelatedObjectQuery.tokenOf; strArrays[3] = " {"; strArrays[4] = this.sourceObject; strArrays[5] = "}"; string str = string.Concat(strArrays); if (this.RelatedClass.Length != 0 || this.RelationshipClass.Length != 0 || this.RelatedQualifier.Length != 0 || this.RelationshipQualifier.Length != 0 || this.RelatedRole.Length != 0 || this.ThisRole.Length != 0 || this.classDefinitionsOnly || this.isSchemaQuery) { str = string.Concat(str, " ", RelatedObjectQuery.tokenWhere); if (this.RelatedClass.Length != 0) { string[] strArrays1 = new string[5]; strArrays1[0] = str; strArrays1[1] = " "; strArrays1[2] = RelatedObjectQuery.tokenResultClass; strArrays1[3] = " = "; strArrays1[4] = this.relatedClass; str = string.Concat(strArrays1); } if (this.RelationshipClass.Length != 0) { string[] strArrays2 = new string[5]; strArrays2[0] = str; strArrays2[1] = " "; strArrays2[2] = RelatedObjectQuery.tokenAssocClass; strArrays2[3] = " = "; strArrays2[4] = this.relationshipClass; str = string.Concat(strArrays2); } if (this.RelatedRole.Length != 0) { string[] strArrays3 = new string[5]; strArrays3[0] = str; strArrays3[1] = " "; strArrays3[2] = RelatedObjectQuery.tokenResultRole; strArrays3[3] = " = "; strArrays3[4] = this.relatedRole; str = string.Concat(strArrays3); } if (this.ThisRole.Length != 0) { string[] strArrays4 = new string[5]; strArrays4[0] = str; strArrays4[1] = " "; strArrays4[2] = RelatedObjectQuery.tokenRole; strArrays4[3] = " = "; strArrays4[4] = this.thisRole; str = string.Concat(strArrays4); } if (this.RelatedQualifier.Length != 0) { string[] strArrays5 = new string[5]; strArrays5[0] = str; strArrays5[1] = " "; strArrays5[2] = RelatedObjectQuery.tokenRequiredQualifier; strArrays5[3] = " = "; strArrays5[4] = this.relatedQualifier; str = string.Concat(strArrays5); } if (this.RelationshipQualifier.Length != 0) { string[] strArrays6 = new string[5]; strArrays6[0] = str; strArrays6[1] = " "; strArrays6[2] = RelatedObjectQuery.tokenRequiredAssocQualifier; strArrays6[3] = " = "; strArrays6[4] = this.relationshipQualifier; str = string.Concat(strArrays6); } if (this.isSchemaQuery) { str = string.Concat(str, " ", RelatedObjectQuery.tokenSchemaOnly); } else { if (this.classDefinitionsOnly) { str = string.Concat(str, " ", RelatedObjectQuery.tokenClassDefsOnly); } } } base.SetQueryString(str); return; } } public override object Clone() { if (this.isSchemaQuery) { return new RelatedObjectQuery(true, this.sourceObject, this.relatedClass, this.relationshipClass, this.relatedQualifier, this.relationshipQualifier, this.relatedRole, this.thisRole); } else { return new RelatedObjectQuery(this.sourceObject, this.relatedClass, this.relationshipClass, this.relatedQualifier, this.relationshipQualifier, this.relatedRole, this.thisRole, this.classDefinitionsOnly); } } protected internal override void ParseQuery(string query) { string str = null; string str1 = null; string str2 = null; string str3 = null; string str4 = null; string str5 = null; bool flag = false; bool flag1 = false; string str6 = query.Trim(); if (string.Compare(str6, 0, RelatedObjectQuery.tokenAssociators, 0, RelatedObjectQuery.tokenAssociators.Length, StringComparison.OrdinalIgnoreCase) == 0) { str6 = str6.Remove(0, RelatedObjectQuery.tokenAssociators.Length); if (str6.Length == 0 || !char.IsWhiteSpace(str6[0])) { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } else { str6 = str6.TrimStart(null); if (string.Compare(str6, 0, RelatedObjectQuery.tokenOf, 0, RelatedObjectQuery.tokenOf.Length, StringComparison.OrdinalIgnoreCase) == 0) { str6 = str6.Remove(0, RelatedObjectQuery.tokenOf.Length).TrimStart(null); if (str6.IndexOf('{') == 0) { str6 = str6.Remove(0, 1).TrimStart(null); int num = str6.IndexOf('}'); int num1 = num; if (-1 != num) { string str7 = str6.Substring(0, num1).TrimEnd(null); str6 = str6.Remove(0, num1 + 1).TrimStart(null); if (0 < str6.Length) { if (string.Compare(str6, 0, RelatedObjectQuery.tokenWhere, 0, RelatedObjectQuery.tokenWhere.Length, StringComparison.OrdinalIgnoreCase) == 0) { str6 = str6.Remove(0, RelatedObjectQuery.tokenWhere.Length); if (str6.Length == 0 || !char.IsWhiteSpace(str6[0])) { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } else { str6 = str6.TrimStart(null); bool flag2 = false; bool flag3 = false; bool flag4 = false; bool flag5 = false; bool flag6 = false; bool flag7 = false; bool flag8 = false; bool flag9 = false; while (true) { if (str6.Length < RelatedObjectQuery.tokenResultClass.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenResultClass, 0, RelatedObjectQuery.tokenResultClass.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str6.Length < RelatedObjectQuery.tokenAssocClass.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenAssocClass, 0, RelatedObjectQuery.tokenAssocClass.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str6.Length < RelatedObjectQuery.tokenResultRole.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenResultRole, 0, RelatedObjectQuery.tokenResultRole.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str6.Length < RelatedObjectQuery.tokenRole.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenRole, 0, RelatedObjectQuery.tokenRole.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str6.Length < RelatedObjectQuery.tokenRequiredQualifier.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenRequiredQualifier, 0, RelatedObjectQuery.tokenRequiredQualifier.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str6.Length < RelatedObjectQuery.tokenRequiredAssocQualifier.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenRequiredAssocQualifier, 0, RelatedObjectQuery.tokenRequiredAssocQualifier.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str6.Length < RelatedObjectQuery.tokenSchemaOnly.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenSchemaOnly, 0, RelatedObjectQuery.tokenSchemaOnly.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str6.Length < RelatedObjectQuery.tokenClassDefsOnly.Length || string.Compare(str6, 0, RelatedObjectQuery.tokenClassDefsOnly, 0, RelatedObjectQuery.tokenClassDefsOnly.Length, StringComparison.OrdinalIgnoreCase) != 0) { break; } ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenClassDefsOnly, ref flag8); flag = true; } else { ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenSchemaOnly, ref flag9); flag1 = true; } } else { ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenRequiredAssocQualifier, "=", ref flag7, ref str5); } } else { ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenRequiredQualifier, "=", ref flag6, ref str4); } } else { ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenRole, "=", ref flag5, ref str3); } } else { ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenResultRole, "=", ref flag4, ref str2); } } else { ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenAssocClass, "=", ref flag3, ref str1); } } else { ManagementQuery.ParseToken(ref str6, RelatedObjectQuery.tokenResultClass, "=", ref flag2, ref str); } } if (str6.Length == 0) { if (flag9 && flag8) { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "where"); } } this.sourceObject = str7; this.relatedClass = str; this.relationshipClass = str1; this.relatedRole = str2; this.thisRole = str3; this.relatedQualifier = str4; this.relationshipQualifier = str5; this.classDefinitionsOnly = flag; this.isSchemaQuery = flag1; return; } else { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "of"); } } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "associators"); } } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public class JTokenReader : JsonReader, IJsonLineInfo { private readonly JToken _root; private JToken _parent; private JToken _current; /// <summary> /// Initializes a new instance of the <see cref="JTokenReader"/> class. /// </summary> /// <param name="token">The token to read from.</param> public JTokenReader(JToken token) { ValidationUtils.ArgumentNotNull(token, "token"); _root = token; _current = token; } /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns> /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array. /// </returns> public override byte[] ReadAsBytes() { return ReadAsBytesInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public override decimal? ReadAsDecimal() { return ReadAsDecimalInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public override int? ReadAsInt32() { return ReadAsInt32Internal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override string ReadAsString() { return ReadAsStringInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTime? ReadAsDateTime() { return ReadAsDateTimeInternal(); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { return ReadAsDateTimeOffsetInternal(); } internal override bool ReadInternal() { if (CurrentState != State.Start) { JContainer container = _current as JContainer; if (container != null && _parent != container) return ReadInto(container); else return ReadOver(_current); } SetToken(_current); return true; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> public override bool Read() { _readType = ReadType.Read; return ReadInternal(); } private bool ReadOver(JToken t) { if (t == _root) return ReadToEnd(); JToken next = t.Next; if ((next == null || next == t) || t == t.Parent.Last) { if (t.Parent == null) return ReadToEnd(); return SetEnd(t.Parent); } else { _current = next; SetToken(_current); return true; } } private bool ReadToEnd() { SetToken(JsonToken.None); return false; } private bool IsEndElement { get { return (_current == _parent); } } private JsonToken? GetEndToken(JContainer c) { switch (c.Type) { case JTokenType.Object: return JsonToken.EndObject; case JTokenType.Array: return JsonToken.EndArray; case JTokenType.Constructor: return JsonToken.EndConstructor; case JTokenType.Property: return null; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", c.Type, "Unexpected JContainer type."); } } private bool ReadInto(JContainer c) { JToken firstChild = c.First; if (firstChild == null) { return SetEnd(c); } else { SetToken(firstChild); _current = firstChild; _parent = c; return true; } } private bool SetEnd(JContainer c) { JsonToken? endToken = GetEndToken(c); if (endToken != null) { SetToken(endToken.Value); _current = c; _parent = c; return true; } else { return ReadOver(c); } } private void SetToken(JToken token) { switch (token.Type) { case JTokenType.Object: SetToken(JsonToken.StartObject); break; case JTokenType.Array: SetToken(JsonToken.StartArray); break; case JTokenType.Constructor: SetToken(JsonToken.StartConstructor); break; case JTokenType.Property: SetToken(JsonToken.PropertyName, ((JProperty)token).Name); break; case JTokenType.Comment: SetToken(JsonToken.Comment, ((JValue)token).Value); break; case JTokenType.Integer: SetToken(JsonToken.Integer, ((JValue)token).Value); break; case JTokenType.Float: SetToken(JsonToken.Float, ((JValue)token).Value); break; case JTokenType.String: SetToken(JsonToken.String, ((JValue)token).Value); break; case JTokenType.Boolean: SetToken(JsonToken.Boolean, ((JValue)token).Value); break; case JTokenType.Null: SetToken(JsonToken.Null, ((JValue)token).Value); break; case JTokenType.Undefined: SetToken(JsonToken.Undefined, ((JValue)token).Value); break; case JTokenType.Date: SetToken(JsonToken.Date, ((JValue)token).Value); break; case JTokenType.Raw: SetToken(JsonToken.Raw, ((JValue)token).Value); break; case JTokenType.Bytes: SetToken(JsonToken.Bytes, ((JValue)token).Value); break; case JTokenType.Guid: SetToken(JsonToken.String, SafeToString(((JValue)token).Value)); break; case JTokenType.Uri: SetToken(JsonToken.String, SafeToString(((JValue)token).Value)); break; case JTokenType.TimeSpan: SetToken(JsonToken.String, SafeToString(((JValue)token).Value)); break; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", token.Type, "Unexpected JTokenType."); } } private string SafeToString(object value) { return (value != null) ? value.ToString() : null; } bool IJsonLineInfo.HasLineInfo() { if (CurrentState == State.Start) return false; IJsonLineInfo info = IsEndElement ? null : _current; return (info != null && info.HasLineInfo()); } int IJsonLineInfo.LineNumber { get { if (CurrentState == State.Start) return 0; IJsonLineInfo info = IsEndElement ? null : _current; if (info != null) return info.LineNumber; return 0; } } int IJsonLineInfo.LinePosition { get { if (CurrentState == State.Start) return 0; IJsonLineInfo info = IsEndElement ? null : _current; if (info != null) return info.LinePosition; return 0; } } } } #endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class Expenum3Tests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "Expenum3_"; int testNumber = 0; result |= Assert.CheckFailed( Expenum_sbyte_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_sbyte_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_short_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_uint_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ulong_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_ulong_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_ushort_enum_to_ushort_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_byte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_int_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_long_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_sbyte_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_short_enum_rtime_s_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( Expenum_byte_enum_to_uint_enum_rtime_s_Test( ), testName, ++testNumber ); return result; } //Expenum Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Expenum //byte_to_byte_enum_rtime_s,byte_to_int_enum_rtime_s,byte_to_long_enum_rtime_s,byte_to_sbyte_enum_rtime_s, //byte_to_short_enum_rtime_s,byte_to_uint_enum_rtime_s,byte_to_ulong_enum_rtime_s,byte_to_ushort_enum_rtime_s, //double_to_byte_enum_rtime_s,double_to_int_enum_rtime_s,double_to_long_enum_rtime_s,double_to_sbyte_enum_rtime_s, //double_to_short_enum_rtime_s,double_to_uint_enum_rtime_s,double_to_ulong_enum_rtime_s, //double_to_ushort_enum_rtime_s,float_to_byte_enum_rtime_s,float_to_int_enum_rtime_s,float_to_long_enum_rtime_s, //float_to_sbyte_enum_rtime_s,float_to_short_enum_rtime_s,float_to_uint_enum_rtime_s,float_to_ulong_enum_rtime_s, //float_to_ushort_enum_rtime_s,short_enum_to_float_rtime_s,short_enum_to_int_rtime_s,int_to_byte_enum_rtime_s, //int_to_int_enum_rtime_s,int_to_long_enum_rtime_s,int_to_sbyte_enum_rtime_s,int_to_short_enum_rtime_s, //int_to_uint_enum_rtime_s,int_to_ulong_enum_rtime_s,int_to_ushort_enum_rtime_s,long_to_byte_enum_rtime_s, //long_to_int_enum_rtime_s,long_to_long_enum_rtime_s,long_to_sbyte_enum_rtime_s,long_to_short_enum_rtime_s, //long_to_uint_enum_rtime_s,long_to_ulong_enum_rtime_s,long_to_ushort_enum_rtime_s,sbyte_to_byte_enum_rtime_s, //sbyte_to_int_enum_rtime_s,sbyte_to_long_enum_rtime_s,sbyte_to_sbyte_enum_rtime_s,sbyte_to_short_enum_rtime_s, //sbyte_to_uint_enum_rtime_s,sbyte_to_ulong_enum_rtime_s,sbyte_to_ushort_enum_rtime_s,short_to_byte_enum_rtime_s, //short_to_int_enum_rtime_s,short_to_long_enum_rtime_s,short_to_sbyte_enum_rtime_s,short_to_short_enum_rtime_s, //short_to_uint_enum_rtime_s,short_to_ulong_enum_rtime_s,short_to_ushort_enum_rtime_s,uint_to_byte_enum_rtime_s, //uint_to_int_enum_rtime_s,uint_to_long_enum_rtime_s,uint_to_sbyte_enum_rtime_s,uint_to_short_enum_rtime_s, //uint_to_uint_enum_rtime_s,uint_to_ulong_enum_rtime_s,uint_to_ushort_enum_rtime_s,ulong_to_byte_enum_rtime_s, //ulong_to_int_enum_rtime_s,ulong_to_long_enum_rtime_s,ulong_to_sbyte_enum_rtime_s,ulong_to_short_enum_rtime_s, //ulong_to_uint_enum_rtime_s,ulong_to_ulong_enum_rtime_s,ulong_to_ushort_enum_rtime_s,ushort_to_byte_enum_rtime_s, //ushort_to_int_enum_rtime_s,ushort_to_long_enum_rtime_s,ushort_to_sbyte_enum_rtime_s,ushort_to_short_enum_rtime_s, //ushort_to_uint_enum_rtime_s,ushort_to_ulong_enum_rtime_s,ushort_to_ushort_enum_rtime_s,int_enum_to_ushort_rtime_s, //long_enum_to_byte_rtime_s,long_enum_to_double_rtime_s,long_enum_to_float_rtime_s,long_enum_to_int_rtime_s, //long_enum_to_long_rtime_s,long_enum_to_sbyte_rtime_s,long_enum_to_short_rtime_s,long_enum_to_uint_rtime_s, //long_enum_to_ulong_rtime_s,long_enum_to_ushort_rtime_s,sbyte_enum_to_byte_rtime_s,sbyte_enum_to_double_rtime_s, //sbyte_enum_to_float_rtime_s,sbyte_enum_to_int_rtime_s,sbyte_enum_to_long_rtime_s,sbyte_enum_to_sbyte_rtime_s, //sbyte_enum_to_short_rtime_s,sbyte_enum_to_uint_rtime_s,sbyte_enum_to_ulong_rtime_s,sbyte_enum_to_ushort_rtime_s, //short_enum_to_byte_rtime_s,short_enum_to_double_rtime_s,short_enum_to_long_rtime_s,short_enum_to_sbyte_rtime_s, //short_enum_to_short_rtime_s,short_enum_to_uint_rtime_s,short_enum_to_ulong_rtime_s,short_enum_to_ushort_rtime_s, //uint_enum_to_byte_rtime_s,uint_enum_to_double_rtime_s,uint_enum_to_float_rtime_s,uint_enum_to_int_rtime_s, //uint_enum_to_long_rtime_s,uint_enum_to_sbyte_rtime_s,uint_enum_to_short_rtime_s,uint_enum_to_uint_rtime_s, //uint_enum_to_ulong_rtime_s,uint_enum_to_ushort_rtime_s,ulong_enum_to_byte_rtime_s,ulong_enum_to_double_rtime_s, //ulong_enum_to_float_rtime_s,ulong_enum_to_int_rtime_s,ulong_enum_to_long_rtime_s,ulong_enum_to_sbyte_rtime_s, //ulong_enum_to_short_rtime_s,ulong_enum_to_uint_rtime_s,ulong_enum_to_ulong_rtime_s,ulong_enum_to_ushort_rtime_s, //ushort_enum_to_byte_rtime_s,ushort_enum_to_double_rtime_s,ushort_enum_to_float_rtime_s,ushort_enum_to_int_rtime_s, //ushort_enum_to_long_rtime_s,ushort_enum_to_sbyte_rtime_s,ushort_enum_to_short_rtime_s,ushort_enum_to_uint_rtime_s, //ushort_enum_to_ulong_rtime_s,ushort_enum_to_ushort_rtime_s,byte_enum_to_byte_rtime_s,byte_enum_to_double_rtime_s, //byte_enum_to_float_rtime_s,byte_enum_to_int_rtime_s,byte_enum_to_long_rtime_s,byte_enum_to_sbyte_rtime_s, //byte_enum_to_short_rtime_s,byte_enum_to_uint_rtime_s,byte_enum_to_ulong_rtime_s,byte_enum_to_ushort_rtime_s, //int_enum_to_byte_rtime_s,int_enum_to_double_rtime_s,int_enum_to_float_rtime_s,int_enum_to_int_rtime_s, //int_enum_to_long_rtime_s,int_enum_to_sbyte_rtime_s,int_enum_to_short_rtime_s,int_enum_to_uint_rtime_s, //int_enum_to_ulong_rtime_s,int_enum_to_ulong_enum_rtime_s,int_enum_to_ushort_enum_rtime_s,long_enum_to_byte_enum_rtime_s, //long_enum_to_int_enum_rtime_s,long_enum_to_long_enum_rtime_s,long_enum_to_sbyte_enum_rtime_s,long_enum_to_short_enum_rtime_s, //long_enum_to_uint_enum_rtime_s,long_enum_to_ulong_enum_rtime_s,long_enum_to_ushort_enum_rtime_s, //sbyte_enum_to_byte_enum_rtime_s,sbyte_enum_to_int_enum_rtime_s,sbyte_enum_to_long_enum_rtime_s,sbyte_enum_to_sbyte_enum_rtime_s, //sbyte_enum_to_short_enum_rtime_s,sbyte_enum_to_uint_enum_rtime_s,sbyte_enum_to_ulong_enum_rtime_s,sbyte_enum_to_ushort_enum_rtime_s, //short_enum_to_byte_enum_rtime_s,short_enum_to_int_enum_rtime_s,short_enum_to_long_enum_rtime_s,short_enum_to_sbyte_enum_rtime_s, //short_enum_to_short_enum_rtime_s,short_enum_to_uint_enum_rtime_s,short_enum_to_ulong_enum_rtime_s,short_enum_to_ushort_enum_rtime_s, //uint_enum_to_byte_enum_rtime_s,uint_enum_to_int_enum_rtime_s,uint_enum_to_long_enum_rtime_s,uint_enum_to_sbyte_enum_rtime_s, //uint_enum_to_short_enum_rtime_s,uint_enum_to_uint_enum_rtime_s,uint_enum_to_ulong_enum_rtime_s,uint_enum_to_ushort_enum_rtime_s, //ulong_enum_to_byte_enum_rtime_s,ulong_enum_to_int_enum_rtime_s,ulong_enum_to_long_enum_rtime_s,ulong_enum_to_sbyte_enum_rtime_s, //ulong_enum_to_short_enum_rtime_s,ulong_enum_to_uint_enum_rtime_s,ulong_enum_to_ulong_enum_rtime_s,ulong_enum_to_ushort_enum_rtime_s, //ushort_enum_to_byte_enum_rtime_s,ushort_enum_to_int_enum_rtime_s,ushort_enum_to_long_enum_rtime_s,ushort_enum_to_sbyte_enum_rtime_s, //ushort_enum_to_short_enum_rtime_s,ushort_enum_to_uint_enum_rtime_s,ushort_enum_to_ulong_enum_rtime_s,ushort_enum_to_ushort_enum_rtime_s, //byte_enum_to_byte_enum_rtime_s,byte_enum_to_int_enum_rtime_s,byte_enum_to_long_enum_rtime_s,byte_enum_to_sbyte_enum_rtime_s, //byte_enum_to_short_enum_rtime_s,byte_enum_to_uint_enum_rtime_s,byte_enum_to_ulong_enum_rtime_s,byte_enum_to_ushort_enum_rtime_s, //int_enum_to_byte_enum_rtime_s,int_enum_to_int_enum_rtime_s,int_enum_to_long_enum_rtime_s,int_enum_to_sbyte_enum_rtime_s //int_enum_to_short_enum_rtime_s,int_enum_to_uint_enum_rtime_s //Test Case Calls [TestMethod] public TestResult Expenum_sbyte_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_sbyte_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_short_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_short_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_uint_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ulong_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_ulong_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_ushort_enum_to_ushort_enum_rtime_s_Test() { if (ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_byte_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_byte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_int_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_int_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_long_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_long_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_sbyte_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_short_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_short_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Expenum_byte_enum_to_uint_enum_rtime_s_Test() { if (ExpenumTestClass_byte_enum_to_uint_enum_rtime_s.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } enum ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_SrcEnumType : sbyte { ValOne = 1 } public class ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_sbyte_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_short_enum_to_byte_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_short_enum_to_int_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_short_enum_to_long_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_short_enum_to_short_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_short_enum_to_uint_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_SrcEnumType : short { ValOne = 1 } public class ExpenumTestClass_short_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_short_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_int_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_long_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_short_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_SrcEnumType : uint { ValOne = 1 } public class ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_uint_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_SrcEnumType : ulong { ValOne = 1 } public class ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ulong_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType : ulong { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_ulong_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType : ushort { ValOne = 1 } enum ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_SrcEnumType : ushort { ValOne = 1 } public class ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_ushort_enum_to_ushort_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType : byte { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_byte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_byte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType : int { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_int_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_int_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_int_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_int_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_int_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType : long { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_long_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_long_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_long_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_long_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_long_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType : sbyte { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_sbyte_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType : short { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_short_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_short_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_short_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_short_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_short_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } enum ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType : uint { ValOne = 1 } enum ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_SrcEnumType : byte { ValOne = 1 } public class ExpenumTestClass_byte_enum_to_uint_enum_rtime_s { public static bool testMethod() { ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType Destination; ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_SrcEnumType Source = ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_SrcEnumType.ValOne; Destination = (ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType)Source; if (Destination == ExpenumTestClass_byte_enum_to_uint_enum_rtime_s_DestEnumType.ValOne) return true; else return false; } } } }
/* ** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** ** 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 including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ 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 SILICON GRAPHICS, INC. ** 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. ** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. */ /* ** Original Author: Eric Veach, July 1994. ** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/. ** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet */ using System; using System.Collections.Generic; using System.Diagnostics; namespace UnityEngine.Experimental.Rendering.LWRP { #if DOUBLE namespace LibTessDotNet.Double #else namespace LibTessDotNet #endif { internal class PriorityQueue<TValue> where TValue : class { private PriorityHeap<TValue>.LessOrEqual _leq; private PriorityHeap<TValue> _heap; private TValue[] _keys; private int[] _order; private int _size, _max; private bool _initialized; public bool Empty { get { return _size == 0 && _heap.Empty; } } public PriorityQueue(int initialSize, PriorityHeap<TValue>.LessOrEqual leq) { _leq = leq; _heap = new PriorityHeap<TValue>(initialSize, leq); _keys = new TValue[initialSize]; _size = 0; _max = initialSize; _initialized = false; } class StackItem { internal int p, r; }; static void Swap(ref int a, ref int b) { int tmp = a; a = b; b = tmp; } public void Init() { var stack = new Stack<StackItem>(); int p, r, i, j, piv; uint seed = 2016473283; p = 0; r = _size - 1; _order = new int[_size + 1]; for (piv = 0, i = p; i <= r; ++piv, ++i) { _order[i] = piv; } stack.Push(new StackItem { p = p, r = r }); while (stack.Count > 0) { var top = stack.Pop(); p = top.p; r = top.r; while (r > p + 10) { seed = seed * 1539415821 + 1; i = p + (int)(seed % (r - p + 1)); piv = _order[i]; _order[i] = _order[p]; _order[p] = piv; i = p - 1; j = r + 1; do { do { ++i; } while (!_leq(_keys[_order[i]], _keys[piv])); do { --j; } while (!_leq(_keys[piv], _keys[_order[j]])); Swap(ref _order[i], ref _order[j]); } while (i < j); Swap(ref _order[i], ref _order[j]); if (i - p < r - j) { stack.Push(new StackItem { p = j + 1, r = r }); r = i - 1; } else { stack.Push(new StackItem { p = p, r = i - 1 }); p = j + 1; } } for (i = p + 1; i <= r; ++i) { piv = _order[i]; for (j = i; j > p && !_leq(_keys[piv], _keys[_order[j - 1]]); --j) { _order[j] = _order[j - 1]; } _order[j] = piv; } } #if DEBUG p = 0; r = _size - 1; for (i = p; i < r; ++i) { Debug.Assert(_leq(_keys[_order[i + 1]], _keys[_order[i]]), "Wrong sort"); } #endif _max = _size; _initialized = true; _heap.Init(); } public PQHandle Insert(TValue value) { if (_initialized) { return _heap.Insert(value); } int curr = _size; if (++_size >= _max) { _max <<= 1; Array.Resize(ref _keys, _max); } _keys[curr] = value; return new PQHandle { _handle = -(curr + 1) }; } public TValue ExtractMin() { Debug.Assert(_initialized); if (_size == 0) { return _heap.ExtractMin(); } TValue sortMin = _keys[_order[_size - 1]]; if (!_heap.Empty) { TValue heapMin = _heap.Minimum(); if (_leq(heapMin, sortMin)) return _heap.ExtractMin(); } do { --_size; } while (_size > 0 && _keys[_order[_size - 1]] == null); return sortMin; } public TValue Minimum() { Debug.Assert(_initialized); if (_size == 0) { return _heap.Minimum(); } TValue sortMin = _keys[_order[_size - 1]]; if (!_heap.Empty) { TValue heapMin = _heap.Minimum(); if (_leq(heapMin, sortMin)) return heapMin; } return sortMin; } public void Remove(PQHandle handle) { Debug.Assert(_initialized); int curr = handle._handle; if (curr >= 0) { _heap.Remove(handle); return; } curr = -(curr + 1); Debug.Assert(curr < _max && _keys[curr] != null); _keys[curr] = null; while (_size > 0 && _keys[_order[_size - 1]] == null) { --_size; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// VirtualMachineExtensionImagesOperations operations. /// </summary> internal partial class VirtualMachineExtensionImagesOperations : Microsoft.Rest.IServiceOperations<ComputeManagementClient>, IVirtualMachineExtensionImagesOperations { /// <summary> /// Initializes a new instance of the VirtualMachineExtensionImagesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal VirtualMachineExtensionImagesOperations(ComputeManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ComputeManagementClient /// </summary> public ComputeManagementClient Client { get; private set; } /// <summary> /// Gets a virtual machine extension image. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='type'> /// </param> /// <param name='version'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<VirtualMachineExtensionImage>> GetWithHttpMessagesAsync(string location, string publisherName, string type, string version, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (location == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "publisherName"); } if (type == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "type"); } if (version == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "version"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("type", type); tracingParameters.Add("version", version); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions/{version}").ToString(); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName)); _url = _url.Replace("{type}", System.Uri.EscapeDataString(type)); _url = _url.Replace("{version}", System.Uri.EscapeDataString(version)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<VirtualMachineExtensionImage>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualMachineExtensionImage>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of virtual machine extension image types. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<VirtualMachineExtensionImage>>> ListTypesWithHttpMessagesAsync(string location, string publisherName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (location == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "publisherName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListTypes", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types").ToString(); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<VirtualMachineExtensionImage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<VirtualMachineExtensionImage>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of virtual machine extension image versions. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='type'> /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<VirtualMachineExtensionImage>>> ListVersionsWithHttpMessagesAsync(string location, string publisherName, string type, Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineExtensionImage> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineExtensionImage>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (location == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "publisherName"); } if (type == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "type"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("type", type); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListVersions", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmextension/types/{type}/versions").ToString(); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", System.Uri.EscapeDataString(publisherName)); _url = _url.Replace("{type}", System.Uri.EscapeDataString(type)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IList<VirtualMachineExtensionImage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<VirtualMachineExtensionImage>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.CodeGeneration; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Serialization.Invocation; namespace Orleans { internal class InvokableObjectManager : IDisposable { private readonly CancellationTokenSource disposed = new CancellationTokenSource(); private readonly ConcurrentDictionary<ObserverGrainId, LocalObjectData> localObjects = new ConcurrentDictionary<ObserverGrainId, LocalObjectData>(); private readonly IGrainContext rootGrainContext; private readonly IRuntimeClient runtimeClient; private readonly ILogger logger; private readonly DeepCopier deepCopier; private readonly MessagingTrace messagingTrace; public InvokableObjectManager( IGrainContext rootGrainContext, IRuntimeClient runtimeClient, DeepCopier deepCopier, MessagingTrace messagingTrace, ILogger logger) { this.rootGrainContext = rootGrainContext; this.runtimeClient = runtimeClient; this.deepCopier = deepCopier; this.messagingTrace = messagingTrace; this.logger = logger; } public bool TryRegister(IAddressable obj, ObserverGrainId objectId) { return this.localObjects.TryAdd(objectId, new LocalObjectData(obj, objectId, this)); } public bool TryDeregister(ObserverGrainId objectId) { return this.localObjects.TryRemove(objectId, out _); } public void Dispatch(Message message) { if (!ObserverGrainId.TryParse(message.TargetGrain, out var observerId)) { this.logger.LogError( (int)ErrorCode.ProxyClient_OGC_TargetNotFound_2, "Message is not addressed to an observer. {Message}", message); return; } if (this.localObjects.TryGetValue(observerId, out var objectData)) { objectData.ReceiveMessage(message); } else { this.logger.LogError( (int)ErrorCode.ProxyClient_OGC_TargetNotFound, "Unexpected target grain in request: {TargetGrain}. Message: {Message}", message.TargetGrain, message); } } public void Dispose() { var tokenSource = this.disposed; Utils.SafeExecute(() => tokenSource?.Cancel(false)); Utils.SafeExecute(() => tokenSource?.Dispose()); } public class LocalObjectData : IGrainContext { private static readonly Func<object, Task> HandleFunc = self => ((LocalObjectData)self).LocalObjectMessagePumpAsync(); private readonly InvokableObjectManager _manager; internal LocalObjectData(IAddressable obj, ObserverGrainId observerId, InvokableObjectManager manager) { this.LocalObject = new WeakReference(obj); this.ObserverId = observerId; this.Messages = new Queue<Message>(); this.Running = false; _manager = manager; } internal WeakReference LocalObject { get; } internal ObserverGrainId ObserverId { get; } internal Queue<Message> Messages { get; } internal bool Running { get; set; } GrainId IGrainContext.GrainId => this.ObserverId.GrainId; GrainReference IGrainContext.GrainReference => _manager.runtimeClient.InternalGrainFactory.GetGrain(ObserverId.GrainId).AsReference(); object IGrainContext.GrainInstance => this.LocalObject.Target; ActivationId IGrainContext.ActivationId => throw new NotImplementedException(); GrainAddress IGrainContext.Address => throw new NotImplementedException(); IServiceProvider IGrainContext.ActivationServices => throw new NotSupportedException(); IGrainLifecycle IGrainContext.ObservableLifecycle => throw new NotImplementedException(); public IWorkItemScheduler Scheduler => throw new NotImplementedException(); void IGrainContext.SetComponent<TComponent>(TComponent value) { if (this.LocalObject.Target is TComponent) { throw new ArgumentException("Cannot override a component which is implemented by this grain"); } _manager.rootGrainContext.SetComponent(value); } public TComponent GetComponent<TComponent>() { if (this.LocalObject.Target is TComponent component) { return component; } return _manager.rootGrainContext.GetComponent<TComponent>(); } public TTarget GetTarget<TTarget>() => (TTarget)(object)this.LocalObject.Target; bool IEquatable<IGrainContext>.Equals(IGrainContext other) => ReferenceEquals(this, other); public void ReceiveMessage(object msg) { var message = (Message)msg; var obj = (IAddressable)this.LocalObject.Target; if (obj == null) { //// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore. _manager.logger.LogWarning( (int)ErrorCode.Runtime_Error_100162, "Object associated with Observer ID {ObserverId} has been garbage collected. Deleting object reference and unregistering it. Message = {message}", this.ObserverId, message); // Try to remove. If it's not there, we don't care. _manager.TryDeregister(this.ObserverId); return; } bool start; lock (this.Messages) { this.Messages.Enqueue(message); start = !this.Running; this.Running = true; } if (_manager.logger.IsEnabled(LogLevel.Trace)) _manager.logger.Trace($"InvokeLocalObjectAsync {message} start {start}"); if (start) { // we want to ensure that the message pump operates asynchronously // with respect to the current thread. see // http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74 // at position 54:45. // // according to the information posted at: // http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr // this idiom is dependent upon the a TaskScheduler not implementing the // override QueueTask as task inlining (as opposed to queueing). this seems // implausible to the author, since none of the .NET schedulers do this and // it is considered bad form (the OrleansTaskScheduler does not do this). // // if, for some reason this doesn't hold true, we can guarantee what we // want by passing a placeholder continuation token into Task.StartNew() // instead. i.e.: // // return Task.StartNew(() => ..., new CancellationToken()); // We pass these options to Task.Factory.StartNew as they make the call identical // to Task.Run. See: https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/ Task.Factory.StartNew( HandleFunc, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Ignore(); } } private async Task LocalObjectMessagePumpAsync() { while (true) { try { Message message; lock (this.Messages) { if (this.Messages.Count == 0) { this.Running = false; break; } message = this.Messages.Dequeue(); } if (message.IsExpired) { _manager.messagingTrace.OnDropExpiredMessage(message, MessagingStatisticsGroup.Phase.Invoke); continue; } RequestContextExtensions.Import(message.RequestContextData); IInvokable request = null; try { request = (IInvokable)message.BodyObject; } catch (Exception deserializationException) { if (_manager.logger.IsEnabled(LogLevel.Warning)) { _manager.logger.LogWarning( deserializationException, "Exception during message body deserialization in " + nameof(LocalObjectMessagePumpAsync) + " for message: {Message}", message); } _manager.runtimeClient.SendResponse(message, Response.FromException(deserializationException)); continue; } try { request.SetTarget(this); var response = await request.Invoke(); if (message.Direction != Message.Directions.OneWay) { this.SendResponseAsync(message, response); } } catch (Exception exc) { this.ReportException(message, exc); } } catch (Exception outerException) { // ignore, keep looping. _manager.logger.LogWarning( outerException, "Exception in " + nameof(LocalObjectMessagePumpAsync)); } finally { RequestContext.Clear(); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void SendResponseAsync(Message message, Response resultObject) { if (message.IsExpired) { _manager.messagingTrace.OnDropExpiredMessage(message, MessagingStatisticsGroup.Phase.Respond); return; } Response deepCopy; try { // we're expected to notify the caller if the deep copy failed. deepCopy = _manager.deepCopier.Copy(resultObject); } catch (Exception exc2) { _manager.runtimeClient.SendResponse(message, Response.FromException(exc2)); _manager.logger.LogWarning((int)ErrorCode.ProxyClient_OGC_SendResponseFailed, exc2, "Exception trying to send a response."); return; } // the deep-copy succeeded. _manager.runtimeClient.SendResponse(message, deepCopy); return; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ReportException(Message message, Exception exception) { var request = (IInvokable)message.BodyObject; switch (message.Direction) { case Message.Directions.OneWay: { _manager.logger.LogError( (int)ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke, exception, "Exception during invocation of notification {Request}, interface {Interface}. Ignoring exception because this is a one way request.", request.ToString(), message.InterfaceType); break; } case Message.Directions.Request: { Exception deepCopy; try { // we're expected to notify the caller if the deep copy failed. deepCopy = (Exception)_manager.deepCopier.Copy(exception); } catch (Exception ex2) { _manager.runtimeClient.SendResponse(message, Response.FromException(ex2)); _manager.logger.LogWarning( (int)ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed, ex2, "Exception trying to send an exception response"); return; } // the deep-copy succeeded. var response = Response.FromException(deepCopy); _manager.runtimeClient.SendResponse(message, response); break; } default: throw new InvalidOperationException($"Unrecognized direction for message {message}, request {request}, which resulted in exception: {exception}"); } } public void Activate(Dictionary<string, object> requestContext, CancellationToken? cancellationToken = null) { } public void Deactivate(DeactivationReason deactivationReason, CancellationToken? cancellationToken = null) { } public Task Deactivated => Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { //////////////////////////////////////////////////////////////// // TestFiles // //////////////////////////////////////////////////////////////// public class NameTable_TestFiles { //Data private static string s_allNodeTypeDTD = "AllNodeTypes.dtd"; private static string s_allNodeTypeENT = "AllNodeTypes.ent"; private static string s_genericXml = "Generic.xml"; private static string s_bigFileXml = "Big.xml"; public static void RemoveDataReader(EREADER_TYPE eReaderType) { switch (eReaderType) { case EREADER_TYPE.GENERIC: DeleteTestFile(s_allNodeTypeDTD); DeleteTestFile(s_allNodeTypeENT); DeleteTestFile(s_genericXml); break; case EREADER_TYPE.BIG_ELEMENT_SIZE: DeleteTestFile(s_bigFileXml); break; default: throw new Exception(); } } private static Dictionary<EREADER_TYPE, string> s_fileNameMap = null; public static string GetTestFileName(EREADER_TYPE eReaderType) { if (s_fileNameMap == null) InitFileNameMap(); return s_fileNameMap[eReaderType]; } private static void InitFileNameMap() { if (s_fileNameMap == null) { s_fileNameMap = new Dictionary<EREADER_TYPE, string>(); } s_fileNameMap.Add(EREADER_TYPE.GENERIC, s_genericXml); s_fileNameMap.Add(EREADER_TYPE.BIG_ELEMENT_SIZE, s_bigFileXml); } public static void CreateTestFile(ref string strFileName, EREADER_TYPE eReaderType) { strFileName = GetTestFileName(eReaderType); switch (eReaderType) { case EREADER_TYPE.GENERIC: CreateGenericTestFile(strFileName); break; case EREADER_TYPE.BIG_ELEMENT_SIZE: CreateBigElementTestFile(strFileName); break; default: throw new Exception(); } } protected static void DeleteTestFile(string strFileName) { } public static void CreateGenericTestFile(string strFileName) { MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); tw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"); tw.WriteLine("<!-- comment1 -->"); tw.WriteLine("<?PI1_First processing instruction?>"); tw.WriteLine("<?PI1a?>"); tw.WriteLine("<?PI1b?>"); tw.WriteLine("<?PI1c?>"); tw.WriteLine("<!DOCTYPE root SYSTEM \"AllNodeTypes.dtd\" ["); tw.WriteLine("<!NOTATION gif SYSTEM \"foo.exe\">"); tw.WriteLine("<!ELEMENT root ANY>"); tw.WriteLine("<!ELEMENT elem1 ANY>"); tw.WriteLine("<!ELEMENT ISDEFAULT ANY>"); tw.WriteLine("<!ENTITY % e SYSTEM \"AllNodeTypes.ent\">"); tw.WriteLine("%e;"); tw.WriteLine("<!ENTITY e1 \"e1foo\">"); tw.WriteLine("<!ENTITY e2 \"&ext3; e2bar\">"); tw.WriteLine("<!ENTITY e3 \"&e1; e3bzee \">"); tw.WriteLine("<!ENTITY e4 \"&e3; e4gee\">"); tw.WriteLine("<!ATTLIST elem1 child1 CDATA #IMPLIED child2 CDATA \"&e2;\" child3 CDATA #REQUIRED>"); tw.WriteLine("<!ATTLIST root xmlns:something CDATA #FIXED \"something\" xmlns:my CDATA #FIXED \"my\" xmlns:dt CDATA #FIXED \"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">"); tw.WriteLine("<!ATTLIST ISDEFAULT d1 CDATA #FIXED \"d1value\">"); tw.WriteLine("<!ATTLIST MULTISPACES att IDREFS #IMPLIED>"); tw.WriteLine("<!ELEMENT CATMIXED (#PCDATA)>"); tw.WriteLine("]>"); tw.WriteLine("<PLAY>"); tw.WriteLine("<root xmlns:something=\"something\" xmlns:my=\"my\" xmlns:dt=\"urn:uuid:C2F41010-65B3-11d1-A29F-00AA00C14882/\">"); tw.WriteLine("<elem1 child1=\"\" child2=\"e1foo e3bzee e2bar\" child3=\"something\">"); tw.WriteLine("text node two e1foo text node three"); tw.WriteLine("</elem1>"); tw.WriteLine("e1foo e3bzee e2bar"); tw.WriteLine("<![CDATA[ This section contains characters that should not be interpreted as markup. For example, characters ', \","); tw.WriteLine("<, >, and & are all fine here.]]>"); tw.WriteLine("<elem2 att1=\"id1\" att2=\"up\" att3=\"attribute3\"> "); tw.WriteLine("<a />"); tw.WriteLine("</elem2>"); tw.WriteLine("<elem2> "); tw.WriteLine("elem2-text1"); tw.WriteLine("<a refs=\"id2\"> "); tw.WriteLine("this-is-a "); tw.WriteLine("</a> "); tw.WriteLine("elem2-text2"); tw.WriteLine("e1foo e3bzee "); tw.WriteLine("e1foo e3bzee e4gee"); tw.WriteLine("<!-- elem2-comment1-->"); tw.WriteLine("elem2-text3"); tw.WriteLine("<b> "); tw.WriteLine("this-is-b"); tw.WriteLine("</b>"); tw.WriteLine("elem2-text4"); tw.WriteLine("<?elem2_PI elem2-PI?>"); tw.WriteLine("elem2-text5"); tw.WriteLine("</elem2>"); tw.WriteLine("<elem2 att1=\"id2\"></elem2>"); tw.WriteLine("</root>"); tw.Write("<ENTITY1 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY1>"); tw.WriteLine("<ENTITY2 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY2>"); tw.WriteLine("<ENTITY3 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY3>"); tw.WriteLine("<ENTITY4 att1='xxx&lt;xxx&#65;xxx&#x43;xxxe1fooxxx'>xxx&gt;xxx&#66;xxx&#x44;xxxe1fooxxx</ENTITY4>"); tw.WriteLine("<ENTITY5>e1foo e3bzee </ENTITY5>"); tw.WriteLine("<ATTRIBUTE1 />"); tw.WriteLine("<ATTRIBUTE2 a1='a1value' />"); tw.WriteLine("<ATTRIBUTE3 a1='a1value' a2='a2value' a3='a3value' />"); tw.WriteLine("<ATTRIBUTE4 a1='' />"); tw.WriteLine(string.Format("<ATTRIBUTE5 CRLF='x{0}x' CR='x{0}x' LF='x\nx' MS='x x' TAB='x\tx' />", Environment.NewLine)); tw.WriteLine(string.Format("<ENDOFLINE1>x{0}x</ENDOFLINE1>", Environment.NewLine)); tw.WriteLine(string.Format("<ENDOFLINE2>x{0}x</ENDOFLINE2>", Environment.NewLine)); tw.WriteLine("<ENDOFLINE3>x\nx</ENDOFLINE3>"); tw.WriteLine(string.Format("<WHITESPACE1>{0}<ELEM />{0}</WHITESPACE1>", Environment.NewLine)); tw.WriteLine("<WHITESPACE2> <ELEM /> </WHITESPACE2>"); tw.WriteLine("<WHITESPACE3>\t<ELEM />\t</WHITESPACE3>"); tw.WriteLine("<SKIP1 /><AFTERSKIP1 />"); tw.WriteLine("<SKIP2></SKIP2><AFTERSKIP2 />"); tw.WriteLine("<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3><AFTERSKIP3></AFTERSKIP3>"); tw.WriteLine("<SKIP4><ELEM1 /><ELEM2>xxx<ELEM3 /></ELEM2></SKIP4>"); tw.WriteLine("<CHARS1>0123456789</CHARS1>"); tw.WriteLine("<CHARS2>xxx<MARKUP />yyy</CHARS2>"); tw.WriteLine("<CHARS_ELEM1>xxx<MARKUP />yyy</CHARS_ELEM1>"); tw.WriteLine("<CHARS_ELEM2><MARKUP />yyy</CHARS_ELEM2>"); tw.WriteLine("<CHARS_ELEM3>xxx<MARKUP /></CHARS_ELEM3>"); tw.WriteLine("<CHARS_CDATA1>xxx<![CDATA[yyy]]>zzz</CHARS_CDATA1>"); tw.WriteLine("<CHARS_CDATA2><![CDATA[yyy]]>zzz</CHARS_CDATA2>"); tw.WriteLine("<CHARS_CDATA3>xxx<![CDATA[yyy]]></CHARS_CDATA3>"); tw.WriteLine("<CHARS_PI1>xxx<?PI_CHAR1 yyy?>zzz</CHARS_PI1>"); tw.WriteLine("<CHARS_PI2><?PI_CHAR2?>zzz</CHARS_PI2>"); tw.WriteLine("<CHARS_PI3>xxx<?PI_CHAR3 yyy?></CHARS_PI3>"); tw.WriteLine("<CHARS_COMMENT1>xxx<!-- comment1-->zzz</CHARS_COMMENT1>"); tw.WriteLine("<CHARS_COMMENT2><!-- comment1-->zzz</CHARS_COMMENT2>"); tw.WriteLine("<CHARS_COMMENT3>xxx<!-- comment1--></CHARS_COMMENT3>"); tw.Flush(); tw.WriteLine("<ISDEFAULT />"); tw.WriteLine("<ISDEFAULT a1='a1value' />"); tw.WriteLine("<BOOLEAN1>true</BOOLEAN1>"); tw.WriteLine("<BOOLEAN2>false</BOOLEAN2>"); tw.WriteLine("<BOOLEAN3>1</BOOLEAN3>"); tw.WriteLine("<BOOLEAN4>tRue</BOOLEAN4>"); tw.WriteLine("<DATETIME>1999-02-22T11:11:11</DATETIME>"); tw.WriteLine("<DATE>1999-02-22</DATE>"); tw.WriteLine("<TIME>11:11:11</TIME>"); tw.WriteLine("<INTEGER>9999</INTEGER>"); tw.WriteLine("<FLOAT>99.99</FLOAT>"); tw.WriteLine("<DECIMAL>.09</DECIMAL>"); tw.WriteLine("<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>"); tw.WriteLine("<TITLE><!-- this is a comment--></TITLE>"); tw.WriteLine("<PGROUP>"); tw.WriteLine("<ACT0 xmlns:foo=\"http://www.foo.com\" foo:Attr0=\"0\" foo:Attr1=\"1111111101\" foo:Attr2=\"222222202\" foo:Attr3=\"333333303\" foo:Attr4=\"444444404\" foo:Attr5=\"555555505\" foo:Attr6=\"666666606\" foo:Attr7=\"777777707\" foo:Attr8=\"888888808\" foo:Attr9=\"999999909\" />"); tw.WriteLine("<ACT1 Attr0=\'0\' Attr1=\'1111111101\' Attr2=\'222222202\' Attr3=\'333333303\' Attr4=\'444444404\' Attr5=\'555555505\' Attr6=\'666666606\' Attr7=\'777777707\' Attr8=\'888888808\' Attr9=\'999999909\' />"); tw.WriteLine("<QUOTE1 Attr0=\"0\" Attr1=\'1111111101\' Attr2=\"222222202\" Attr3=\'333333303\' />"); tw.WriteLine("<PERSONA>DROMIO OF EPHESUS</PERSONA>"); tw.WriteLine("<QUOTE2 Attr0=\"0\" Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\'333333303\' />"); tw.WriteLine("<QUOTE3 Attr0=\'0\' Attr1=\"1111111101\" Attr2=\'222222202\' Attr3=\"333333303\" />"); tw.WriteLine("<EMPTY1 />"); tw.WriteLine("<EMPTY2 val=\"abc\" />"); tw.WriteLine("<EMPTY3></EMPTY3>"); tw.WriteLine("<NONEMPTY0></NONEMPTY0>"); tw.WriteLine("<NONEMPTY1>ABCDE</NONEMPTY1>"); tw.WriteLine("<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>"); tw.WriteLine("<ACT2 Attr0=\"10\" Attr1=\"1111111011\" Attr2=\"222222012\" Attr3=\"333333013\" Attr4=\"444444014\" Attr5=\"555555015\" Attr6=\"666666016\" Attr7=\"777777017\" Attr8=\"888888018\" Attr9=\"999999019\" />"); tw.WriteLine("<GRPDESCR>twin brothers, and sons to Aegeon and Aemilia.</GRPDESCR>"); tw.WriteLine("</PGROUP>"); tw.WriteLine("<PGROUP>"); tw.Flush(); tw.WriteLine("<XMLLANG0 xml:lang=\"en-US\">What color e1foo is it?</XMLLANG0>"); tw.Write("<XMLLANG1 xml:lang=\"en-GB\">What color is it?<a><b><c>Language Test</c><PERSONA>DROMIO OF EPHESUS</PERSONA></b></a></XMLLANG1>"); tw.WriteLine("<NOXMLLANG />"); tw.WriteLine("<EMPTY_XMLLANG Attr0=\"0\" xml:lang=\"en-US\" />"); tw.WriteLine("<XMLLANG2 xml:lang=\"en-US\">What color is it?<TITLE><!-- this is a comment--></TITLE><XMLLANG1 xml:lang=\"en-GB\">Testing language<XMLLANG0 xml:lang=\"en-US\">What color is it?</XMLLANG0>haha </XMLLANG1>hihihi</XMLLANG2>"); tw.WriteLine("<DONEXMLLANG />"); tw.WriteLine("<XMLSPACE1 xml:space=\'default\'>&lt; &gt;</XMLSPACE1>"); tw.Write("<XMLSPACE2 xml:space=\'preserve\'>&lt; &gt;<a><!-- comment--><b><?PI1a?><c>Space Test</c><PERSONA>DROMIO OF SYRACUSE</PERSONA></b></a></XMLSPACE2>"); tw.WriteLine("<NOSPACE />"); tw.WriteLine("<EMPTY_XMLSPACE Attr0=\"0\" xml:space=\'default\' />"); tw.WriteLine("<XMLSPACE2A xml:space=\'default\'>&lt; <XMLSPACE3 xml:space=\'preserve\'> &lt; &gt; <XMLSPACE4 xml:space=\'default\'> &lt; &gt; </XMLSPACE4> test </XMLSPACE3> &gt;</XMLSPACE2A>"); tw.WriteLine("<GRPDESCR>twin brothers, and attendants on the two Antipholuses.</GRPDESCR>"); tw.WriteLine("<DOCNAMESPACE>"); tw.WriteLine("<NAMESPACE0 xmlns:bar=\"1\"><bar:check>Namespace=1</bar:check></NAMESPACE0>"); tw.WriteLine("<NAMESPACE1 xmlns:bar=\"1\"><a><b><c><d><bar:check>Namespace=1</bar:check><bar:check2></bar:check2></d></c></b></a></NAMESPACE1>"); tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>"); tw.WriteLine("<EMPTY_NAMESPACE bar:Attr0=\"0\" xmlns:bar=\"1\" />"); tw.WriteLine("<EMPTY_NAMESPACE1 Attr0=\"0\" xmlns=\"14\" />"); tw.WriteLine("<EMPTY_NAMESPACE2 Attr0=\"0\" xmlns=\"14\"></EMPTY_NAMESPACE2>"); tw.WriteLine("<NAMESPACE2 xmlns:bar=\"1\"><a><b><c xmlns:bar=\"2\"><d><bar:check>Namespace=2</bar:check></d></c></b></a></NAMESPACE2>"); tw.WriteLine("<NAMESPACE3 xmlns=\"1\"><a xmlns:a=\"2\" xmlns:b=\"3\" xmlns:c=\"4\"><b xmlns:d=\"5\" xmlns:e=\"6\" xmlns:f='7'><c xmlns:d=\"8\" xmlns:e=\"9\" xmlns:f=\"10\">"); tw.WriteLine("<d xmlns:g=\"11\" xmlns:h=\"12\"><check>Namespace=1</check><testns xmlns=\"100\"><empty100 /><check100>Namespace=100</check100></testns><check1>Namespace=1</check1><d:check8>Namespace=8</d:check8></d></c><d:check5>Namespace=5</d:check5></b></a>"); tw.WriteLine("<a13 a:check=\"Namespace=13\" xmlns:a=\"13\" /><check14 xmlns=\"14\">Namespace=14</check14></NAMESPACE3>"); tw.WriteLine("<NONAMESPACE>Namespace=\"\"</NONAMESPACE>"); tw.WriteLine("<NONAMESPACE1 Attr1=\"one\" xmlns=\"1000\">Namespace=\"\"</NONAMESPACE1>"); tw.WriteLine("</DOCNAMESPACE>"); tw.WriteLine("</PGROUP>"); tw.WriteLine("<GOTOCONTENT>some text<![CDATA[cdata info]]></GOTOCONTENT>"); tw.WriteLine("<SKIPCONTENT att1=\"\"> <!-- comment1--> \n <?PI_SkipContent instruction?></SKIPCONTENT>"); tw.WriteLine("<MIXCONTENT> <!-- comment1-->some text<?PI_SkipContent instruction?><![CDATA[cdata info]]></MIXCONTENT>"); tw.WriteLine("<A att=\"123\">1<B>2<C>3<D>4<E>5<F>6<G>7<H>8<I>9<J>10"); tw.WriteLine("<A1 att=\"456\">11<B1>12<C1>13<D1>14<E1>15<F1>16<G1>17<H1>18<I1>19<J1>20"); tw.WriteLine("<A2 att=\"789\">21<B2>22<C2>23<D2>24<E2>25<F2>26<G2>27<H2>28<I2>29<J2>30"); tw.WriteLine("<A3 att=\"123\">31<B3>32<C3>33<D3>34<E3>35<F3>36<G3>37<H3>38<I3>39<J3>40"); tw.WriteLine("<A4 att=\"456\">41<B4>42<C4>43<D4>44<E4>45<F4>46<G4>47<H4>48<I4>49<J4>50"); tw.WriteLine("<A5 att=\"789\">51<B5>52<C5>53<D5>54<E5>55<F5>56<G5>57<H5>58<I5>59<J5>60"); tw.WriteLine("<A6 att=\"123\">61<B6>62<C6>63<D6>64<E6>65<F6>66<G6>67<H6>68<I6>69<J6>70"); tw.WriteLine("<A7 att=\"456\">71<B7>72<C7>73<D7>74<E7>75<F7>76<G7>77<H7>78<I7>79<J7>80"); tw.WriteLine("<A8 att=\"789\">81<B8>82<C8>83<D8>84<E8>85<F8>86<G8>87<H8>88<I8>89<J8>90"); tw.WriteLine("<A9 att=\"123\">91<B9>92<C9>93<D9>94<E9>95<F9>96<G9>97<H9>98<I9>99<J9>100"); tw.WriteLine("<A10 att=\"123\">101<B10>102<C10>103<D10>104<E10>105<F10>106<G10>107<H10>108<I10>109<J10>110"); tw.WriteLine("</J10>109</I10>108</H10>107</G10>106</F10>105</E10>104</D10>103</C10>102</B10>101</A10>"); tw.WriteLine("</J9>99</I9>98</H9>97</G9>96</F9>95</E9>94</D9>93</C9>92</B9>91</A9>"); tw.WriteLine("</J8>89</I8>88</H8>87</G8>86</F8>85</E8>84</D8>83</C8>82</B8>81</A8>"); tw.WriteLine("</J7>79</I7>78</H7>77</G7>76</F7>75</E7>74</D7>73</C7>72</B7>71</A7>"); tw.WriteLine("</J6>69</I6>68</H6>67</G6>66</F6>65</E6>64</D6>63</C6>62</B6>61</A6>"); tw.WriteLine("</J5>59</I5>58</H5>57</G5>56</F5>55</E5>54</D5>53</C5>52</B5>51</A5>"); tw.WriteLine("</J4>49</I4>48</H4>47</G4>46</F4>45</E4>44</D4>43</C4>42</B4>41</A4>"); tw.WriteLine("</J3>39</I3>38</H3>37</G3>36</F3>35</E3>34</D3>33</C3>32</B3>31</A3>"); tw.WriteLine("</J2>29</I2>28</H2>27</G2>26</F2>25</E2>24</D2>23</C2>22</B2>21</A2>"); tw.WriteLine("</J1>19</I1>18</H1>17</G1>16</F1>15</E1>14</D1>13</C1>12</B1>11</A1>"); tw.Write("</J>9</I>8</H>7</G>6</F>5</E>4</D>3</C>2</B>1</A>"); tw.WriteLine("<EMPTY4 val=\"abc\"></EMPTY4>"); tw.WriteLine("<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>"); tw.WriteLine("<DUMMY />"); tw.WriteLine(string.Format("<MULTISPACES att=' {0} \t {0}{0} n1 {0} \t {0}{0} n2 {0} \t {0}{0} ' />", Environment.NewLine)); tw.WriteLine("<CAT>AB<![CDATA[CD]]> </CAT>"); tw.WriteLine("<CATMIXED>AB<![CDATA[CD]]> </CATMIXED>"); tw.WriteLine("<VALIDXMLLANG0 xml:lang=\"a\" />"); tw.WriteLine("<VALIDXMLLANG1 xml:lang=\"\" />"); tw.WriteLine("<VALIDXMLLANG2 xml:lang=\"ab-cd-\" />"); tw.WriteLine("<VALIDXMLLANG3 xml:lang=\"a b-cd\" />"); tw.Write("</PLAY>"); tw.Flush(); FilePathUtil.addStream(strFileName, ms); } public static void CreateBigElementTestFile(string strFileName) { MemoryStream ms = new MemoryStream(); TextWriter tw = new StreamWriter(ms); string str = new string('Z', (1 << 20) - 1); tw.WriteLine("<Root>"); tw.Write("<"); tw.Write(str); tw.WriteLine("X />"); tw.Flush(); tw.Write("<"); tw.Write(str); tw.WriteLine("Y />"); tw.WriteLine("</Root>"); tw.Flush(); FilePathUtil.addStream(strFileName, ms); } } }
// Copyright 2007: Christian Graefe // Copyright 2008: Dan Brecht and Joel Wilson // // This file is part of SharpMap. // SharpMap 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 of the License, or // (at your option) any later version. // // SharpMap 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 SharpMap; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using NetTopologySuite.Geometries; namespace SharpMap.Layers { /// <summary> /// The coefficients for transforming between pixel/line (X,Y) raster space, and projection coordinates (Xp,Yp) space.<br/> /// Xp = T[0] + T[1]*X + T[2]*Y<br/> /// Yp = T[3] + T[4]*X + T[5]*Y<br/> /// In a north up image, T[1] is the pixel width, and T[5] is the pixel height. /// The upper left corner of the upper left pixel is at position (T[0],T[3]). /// </summary> [Serializable] internal class GeoTransform { private const double Epsilon = double.Epsilon; private readonly double[] _inverseTransform = new double[6]; private readonly double[] _transform = new double[6]; #region public properties /// <summary> /// returns value of the transform array /// </summary> /// <param name="i">place in array</param> /// <returns>value dependent on i</returns> public double this[int i] { get { return _transform[i]; } set { _transform[i] = value; ComputeInverse(); } } public double[] Inverse { get { return _inverseTransform; } } /// <summary> /// Gets a value indicating if this transformation does not actually perform anything transformation /// </summary> public bool IsIdentity { get { return IsTrivial; } } /// <summary> /// Returns true if no values were fetched /// </summary> public bool IsTrivial { get { return //East-West Math.Abs(_transform[0] - 0) < Epsilon && Math.Abs(_transform[1] - 1) < Epsilon && Math.Abs(_transform[2] - 0) < Epsilon && //North-South Math.Abs(_transform[3] - 0) < Epsilon && Math.Abs(_transform[4] - 0) < Epsilon && Math.Abs(_transform[5] - 1) < Epsilon; } } /// <summary> /// Gets a value indicating if this transformation is scaling coordinates /// </summary> public bool IsScaling { get { return Math.Abs(_transform[1] - 1d) < Epsilon && Math.Abs(Math.Abs(_transform[5]) - 1d) < Epsilon; } } /// <summary> /// Gets a value indicating if this transformation is rotating coordinates /// </summary> public bool IsRotating { get { return Math.Abs(_transform[2] - 0d) > Epsilon || Math.Abs(_transform[4] - 0d) > Epsilon; } } /// <summary> /// Gets the left value of the image /// </summary> public double Left { get { return _transform[0]; } } /* /// <summary> /// right value of the image /// </summary> public double Right { get { return this.Left + (this.HorizontalPixelResolution * _gdalDataset.XSize); } } */ /// <summary> /// Gets or sets the top value of the image /// </summary> public double Top { get { return _transform[3]; } } #pragma warning disable CS1587 // XML comment is not placed on a valid language element /// <summary> /// bottom value of the image /// </summary> // public double Bottom // { // get { return this.Top + (this.VerticalPixelResolution * _gdalDataset.YSize); } //} /// <summary> /// Gets or sets the west to east pixel resolution /// </summary> public double HorizontalPixelResolution #pragma warning restore CS1587 // XML comment is not placed on a valid language element { get { return _transform[1]; } set { this[1] = value; } } /// <summary> /// Gets or sets the north to south pixel resolution /// </summary> public double VerticalPixelResolution { get { return _transform[5]; } set { this[5] = value; } } public double XRotation { get { return _transform[2]; } set { this[2] = value; } } public double YRotation { get { return _transform[4]; } set { this[4] = value; } } #endregion #region constructors /// <summary> /// Constructor /// </summary> public GeoTransform() { _transform = new double[6]; _transform[0] = 999.5; /* x-offset */ _transform[1] = 1; /* west-east pixel resolution */ _transform[2] = 0; /* rotation, 0 if image is "north up" */ _transform[3] = 1000.5; /* y-offset */ _transform[4] = 0; /* rotation, 0 if image is "north up" */ _transform[5] = -1; /* north-south pixel resolution */ ComputeInverse(); } /// <summary> /// Constructor /// </summary> /// <param name="array"></param> public GeoTransform(double[] array) { if (array.Length != 6) throw new ArgumentException("GeoTransform constructor invoked with invalid sized array", "array"); _transform = array; ComputeInverse(); } /// <summary> /// Constructor /// </summary> /// <param name="gdalDataset">The gdal dataset</param> public GeoTransform(OSGeo.GDAL.Dataset gdalDataset) { if (gdalDataset == null) throw new ArgumentException("GeoTransform constructor invoked with null dataset.", "gdalDataset"); var array = new double[6]; gdalDataset.GetGeoTransform(array); _transform = array; ComputeInverse(); } private void ComputeInverse() { // compute determinant var det = _transform[1] * _transform[5] - _transform[2] * _transform[4]; if (Math.Abs(det - 0.0) < Epsilon) return; // inverse rot/scale portion _inverseTransform[1] = _transform[5] / det; _inverseTransform[2] = -_transform[2] / det; _inverseTransform[4] = -_transform[4] / det; _inverseTransform[5] = _transform[1] / det; // compute translation elements _inverseTransform[0] = -_inverseTransform[1] * _transform[0] - _inverseTransform[2] * _transform[3]; _inverseTransform[3] = -_inverseTransform[4] * _transform[0] - _inverseTransform[5] * _transform[3]; } #endregion #region public methods /// <summary> /// converts image point into projected point /// </summary> /// <param name="imgX">image x value</param> /// <param name="imgY">image y value</param> /// <returns>projected x coordinate</returns> public double ProjectedX(double imgX, double imgY) { return _transform[0] + _transform[1] * imgX + _transform[2] * imgY; } /// <summary> /// converts image point into projected point /// </summary> /// <param name="imgX">image x value</param> /// <param name="imgY">image y value</param> /// <returns>projected y coordinate</returns> public double ProjectedY(double imgX, double imgY) { return _transform[3] + _transform[4] * imgX + _transform[5] * imgY; } public Coordinate ImageToGround(Coordinate imagePoint) { return new Coordinate { X = _transform[0] + _transform[1]*imagePoint.X + _transform[2]*imagePoint.Y, Y = _transform[3] + _transform[4]*imagePoint.X + _transform[5]*imagePoint.Y }; } public Coordinate GroundToImage(Coordinate groundPoint) { return new Coordinate { X = _inverseTransform[0] + _inverseTransform[1]*groundPoint.X + _inverseTransform[2]*groundPoint.Y, Y = _inverseTransform[3] + _inverseTransform[4]*groundPoint.X + _inverseTransform[5]*groundPoint.Y }; } public Envelope GroundToImage(Envelope e) { var res = new Envelope(GroundToImage(e.TopLeft())); res.ExpandToInclude(GroundToImage(e.TopRight())); res.ExpandToInclude(GroundToImage(e.BottomLeft())); res.ExpandToInclude(GroundToImage(e.BottomRight())); return res; } public double GndW(double imgWidth, double imgHeight) { // check for funky case if (_transform[2] < 0 && _transform[4] < 0 && _transform[5] < 0) return Math.Abs((_transform[1] * imgWidth) + (_transform[2] * imgHeight)); return Math.Abs((_transform[1] * imgWidth) - (_transform[2] * imgHeight)); } public double GndH(double imgWidth, double imgHeight) { // check for funky case if (_transform[2] < 0 && _transform[4] < 0 && _transform[5] < 0) return Math.Abs((_transform[4] * imgWidth) - (_transform[5] * imgHeight)); return Math.Abs((_transform[4] * imgWidth) - (_transform[5] * imgHeight)); } // finds leftmost pixel location (handles rotation) public double EnvelopeLeft(double imgWidth, double imgHeight) { var left = Math.Min(_transform[0], _transform[0] + (_transform[1] * imgWidth)); left = Math.Min(left, _transform[0] + (_transform[2] * imgHeight)); left = Math.Min(left, _transform[0] + (_transform[1] * imgWidth) + (_transform[2] * imgHeight)); return left; } // finds rightmost pixel location (handles rotation) public double EnvelopeRight(double imgWidth, double imgHeight) { var right = Math.Max(_transform[0], _transform[0] + (_transform[1] * imgWidth)); right = Math.Max(right, _transform[0] + (_transform[2] * imgHeight)); right = Math.Max(right, _transform[0] + (_transform[1] * imgWidth) + (_transform[2] * imgHeight)); return right; } // finds topmost pixel location (handles rotation) public double EnvelopeTop(double imgWidth, double imgHeight) { var top = Math.Max(_transform[3], _transform[3] + (_transform[4] * imgWidth)); top = Math.Max(top, _transform[3] + (_transform[5] * imgHeight)); top = Math.Max(top, _transform[3] + (_transform[4] * imgWidth) + (_transform[5] * imgHeight)); return top; } // finds bottommost pixel location (handles rotation) public double EnvelopeBottom(double imgWidth, double imgHeight) { var bottom = Math.Min(_transform[3], _transform[3] + (_transform[4] * imgWidth)); bottom = Math.Min(bottom, _transform[3] + (_transform[5] * imgHeight)); bottom = Math.Min(bottom, _transform[3] + (_transform[4] * imgWidth) + (_transform[5] * imgHeight)); return bottom; } // image was flipped horizontally public bool HorzFlip() { return _transform[4] > 0; } // image was flipped vertically public bool VertFlip() { return _transform[2] > 0; } public double PixelX(double lat) { return (_transform[0] - lat) / (_transform[1] - _transform[2]); } public double PixelY(double lon) { return Math.Abs(_transform[3] - lon) / (_transform[4] + _transform[5]); } public double PixelXwidth(double lat) { return Math.Abs(lat / (_transform[1] - _transform[2])); } public double PixelYwidth(double lon) { return Math.Abs(lon / (_transform[5] + _transform[4])); } /// <summary> /// Method to compute the rotation angle /// </summary> /// <returns>The rotation angle</returns> public double RotationAngle() { if (Math.Abs(_transform[5]) > double.Epsilon) return Math.Atan(_transform[2] / _transform[5]) * 57.2957795; return 0; } /// <summary> /// /// </summary> /// <returns></returns> public bool IsFlipped() { return _transform[5] > 0; } #endregion } }
using System; using System.Reflection; using System.Runtime.Remoting; using System.IO; using System.Collections.Generic; using bv.common.Diagnostics; using System.Linq; /// ----------------------------------------------------------------------------- /// Project : bv.common /// Class : common..Core.ClassLoader /// /// ----------------------------------------------------------------------------- /// <summary> /// Used to register .NET assemblies and load the class from registered assembly /// by class name using reflection mechanism /// </summary> /// <remarks> /// This class simplifies the class instance creation using <b>Reflection</b> mechanism. /// Any assembly that supposed to be called using <b>Reflection</b> should be registered by <i>Init</i> method call. /// To create the class instance call <i>LoadClass</i> or <i>LoadObject</i> method. /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- namespace bv.common.Core { public class ClassLoader { private static Dictionary<string, moduleInfo> m_Modules = new Dictionary<string, moduleInfo>(); private static Dictionary<string, string> m_AssemblyList = new Dictionary<string, string>(); private struct moduleInfo { public string FullName; public string AssemblyName; } /// ----------------------------------------------------------------------------- /// <summary> /// Registers all assemblies that fit to the passed wildcard mask. /// </summary> /// <param name="mask"> the wildcard mask for assemblies to be registered /// </param> /// <remarks> /// <i>Init</i> method can be called several times with different wildcard masks. /// All assemblies that fit the mask and not registered yet will be appended to the registered assemblies list. /// The following wildcard specifiers are permitted in <i>mask</i>. /// <list type="table"> ///<listheader> ///<term>Wildcard character</term> ///<description>Description</description> ///</listheader> ///<item><term>*</term> ///<description>Zero or more characters.</description></item> ///<item><term>?</term> /// <description>Exactly one character.</description></item> /// </list> ///Characters other than the wildcard specifiers represent themselves. For example, the <i>mask</i> string ///"*.dll" searches for all files having extension <i>dll</i> in the directory containing application executable. ///The <i>mask</i> string 'eidss*.dll' searches for all assemblies which names begin from 'eidss'. ///The <i>mask</i> parameter can point to absolute or relative path information. ///Relative path information is interpreted as relative to the directory containing application executable. ///The path parameter is not case-sensitive. ///For an example of using this method, see the <b>Example</b> section below. /// </remarks> /// <example> /// The following example registers all assemblies starting with "eidss" in the directory with the application executable /// creates the instance of the class HumanCaseList that is inherited from BaseForm, and uses this instance to show the created form. /// <code> /// ClassLoader.Init("eidss*.dll") /// Dim humanCaseForm As Object = ClassLoader.LoadControl("HumanCaseList") /// If Not humanCaseForm Is Nothing Then /// BaseForm.ShowNormal(CType(humanCaseForm, BaseForm)) /// End If /// </code> /// </example> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public static void Init(string mask, string appdir) { if (appdir == null) { appdir = Utils.GetExecutingPath(); } if (Path.GetDirectoryName(mask) != "") { appdir = Path.GetDirectoryName(mask); mask = Path.GetFileName(mask); } string[] files = Directory.GetFiles(appdir, mask); foreach (string file in files) { if (m_AssemblyList.ContainsKey(Path.GetFileName(file))) m_AssemblyList[Path.GetFileName(file)] = file; else m_AssemblyList.Add(Path.GetFileName(file), file); } } /// ----------------------------------------------------------------------------- /// <summary> /// Searches the class in the registered assemblies and creates the class instance. /// </summary> /// <param name="className"> /// the class name to load. /// </param> /// <returns> /// Returns the instance of the created class or throws the exception if class can't be created. /// </returns> /// <remarks> /// If method is called first time for the requested class name, it searches the class in the registered assemblies /// and cash the relation between class and assembly if assembly is found. If class is not found in the registered assemblies, SystemExeption with message 'Class not found' is thrown. /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public static object LoadClass(string className) { if (Utils.IsEmpty(className)) return null; Exception rethrow = null; ObjectHandle hdl = null; string AssemblyName = FindModuleAssembly(ref className, ref hdl); if (hdl == null) { try { //try to load from primary assembly //ClassLoader.AssemblyName should return assembly name related with specific form //if you will add new forms to the project be sure that GetAssemblyName method //will return correct assembly name for this form hdl = System.Activator.CreateInstance(AssemblyName, className); } catch (TargetInvocationException e) { rethrow = e.InnerException; Dbg.Debug(string.Format("EIDSS_LoadClass:Can\'t create class {0}, Assembly {1}:{2}{3}", className, AssemblyName, "\r\n", e.InnerException.Message), (System.Exception)null); } catch (Exception e) { Dbg.Debug(string.Format("EIDSS_LoadClass:Can\'t create class {0}, Assembly {1}:{2}{3}", className, AssemblyName, "\r\n", e.Message), (System.Exception)null); throw (new SystemException(string.Format("Can\'t create class {0}:{1}{2}", className, "\r\n", e.Message), e)); } if (rethrow != null) { throw (rethrow); } } return hdl.Unwrap(); } /// ----------------------------------------------------------------------------- /// <summary> /// Searches the class in the registered assemblies, and returns the full assembly name containing the class /// </summary> /// <param name="className"> /// the class name that should be contained by assembly. /// </param> /// <param name="hdl"> /// returns the <b>ObjectHandle</b> to the class instance if the class is requested first time. In other case this parameter returns <b>Nothing</b> /// </param> /// <returns> /// Returns the full qualified assembly name that contains the requested class /// </returns> /// <remarks> /// If method is called first time for this specific class, it tries to load the class from all registered assemblies /// and after successful attempt cash the assembly name for this class and returns the handler to the class instance in the <i>hdl</i> parameter. /// If class was already loaded before, it just returns the cashed class assembly name. /// If assembly for requested files was not found, SystemException with message 'Class not found' is thrown. /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- private static string FindModuleAssembly(ref string className, ref ObjectHandle hdl) { moduleInfo mi; if (m_Modules.ContainsKey(className)) { mi = m_Modules[className]; className = mi.FullName; return mi.AssemblyName; } string cName = className; bool wasError = false; foreach (var assemblyName in m_AssemblyList.Keys) { Assembly a; try { a = Assembly.LoadFrom(m_AssemblyList[assemblyName]); var type = a.GetTypes().FirstOrDefault(t => t.FullName == cName || t.Name == cName); if (type != null) { hdl = LoadClassByName(a.FullName, type.FullName); if (hdl != null) { mi.AssemblyName = a.FullName; mi.FullName = type.FullName; m_Modules[className] = mi; return a.FullName; } } } catch (Exception e) { Dbg.Debug(string.Format("EIDSS_LoadClass:Can\'t create class {0}, Assembly {1}{2}:{3}{4}", className, AppDomain.CurrentDomain.BaseDirectory, assemblyName, "\r\n", e.Message), (System.Exception)null); Dbg.Debug(string.Format("Stack trace:{0}", e.StackTrace), (System.Exception)null); if (e.InnerException != null) { Dbg.Debug(string.Format("InerException:Can\'t create class {0}, Assembly {1}{2}:{3}{4}", className, AppDomain.CurrentDomain.BaseDirectory, assemblyName, "\r\n", e.InnerException.Message), (System.Exception)null); Dbg.Debug(string.Format("Stack trace:{0}", e.InnerException.StackTrace), (System.Exception)null); } wasError = true; } } if (!wasError) throw (new Exception(string.Format("Class {0} is not found in registerd assemblies", className))); return String.Empty; } /// ----------------------------------------------------------------------------- /// <summary> /// Loads class from the specific assembly /// </summary> /// <param name="AssemblyName"> /// full qualified assembly name /// </param> /// <param name="className"> /// class name to load /// </param> /// <returns> /// the new instance of the class. Throws the exception if the instance can't be created /// </returns> /// <remarks> /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- private static ObjectHandle LoadClassByName(string AssemblyName, string ClassName) { try { return System.Activator.CreateInstance(AssemblyName, ClassName); } catch (TargetInvocationException e) { throw (e.InnerException); } catch (Exception) { throw; } } /// ----------------------------------------------------------------------------- /// <summary> /// Creates the new instance of the specific type /// </summary> /// <param name="ClassType"> /// the type of object to create /// </param> /// <returns> /// Returns the new instance of the class. Throws the exception if the instance can't be created /// </returns> /// <remarks> /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public static object LoadClass(Type ClassType) { if (ClassType == null) { return null; } try { return System.Activator.CreateInstance(ClassType); } catch (TargetInvocationException e) { throw (e.InnerException); } catch (Exception) { throw; } } //public static Type LoadType(string ClassName) //{ // if (ClassName == null) // { // return null; // } // foreach (string AssemblyName in m_AssemblyList.Keys) // { // Assembly a = null; // try // { // a = Assembly.LoadFrom(m_AssemblyList[AssemblyName]); // Type[] mytypes = a.GetTypes(); // foreach (Type t in mytypes) // { // if (t.FullName == ClassName || t.Name == ClassName) // { // return t; // } // } // } // catch (Exception e) // { // Dbg.Debug(string.Format("EIDSS_LoadClass:Can\'t load class type{0}, Assembly {1}{2}:{3}{4}", ClassName, AppDomain.CurrentDomain.BaseDirectory, AssemblyName, "\r\n", e.Message), (System.Exception)null); // Dbg.Debug(string.Format("Stack trace:{0}", e.StackTrace), (System.Exception)null); // if (e.InnerException != null) // { // Dbg.Debug(string.Format("InerException:Can\'t load class type {0}, Assembly {1}{2}:{3}{4}", ClassName, AppDomain.CurrentDomain.BaseDirectory, AssemblyName, "\r\n", e.InnerException.Message), (System.Exception)null); // Dbg.Debug(string.Format("Stack trace:{0}", e.InnerException.StackTrace)); // } // } // } // return null; //} } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_11_5_2 : EcmaTest { [Fact] [Trait("Category", "11.5.2")] public void WhiteSpaceAndLineTerminatorBetweenMultiplicativeexpressionAndOrBetweenAndUnaryexpressionAreAllowed() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYUsesGetvalue() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.1_T1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYUsesGetvalue2() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.1_T2.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYUsesGetvalue3() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.1_T3.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYUsesDefaultValue() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.2_T1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TonumberFirstExpressionIsCalledFirstAndThenTonumberSecondExpression() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.3_T1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.4_T1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression2() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.4_T2.js", false); } [Fact] [Trait("Category", "11.5.2")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression3() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A2.4_T3.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T1.1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY2() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T1.2.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY3() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T1.3.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY4() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T1.4.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY5() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T1.5.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY6() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY7() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.2.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY8() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.3.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY9() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.4.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY10() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.5.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY11() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.6.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY12() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.7.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY13() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.8.js", false); } [Fact] [Trait("Category", "11.5.2")] public void OperatorXYReturnsTonumberXTonumberY14() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A3_T2.9.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T1.1.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics2() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T1.2.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics3() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T10.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics4() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T2.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics5() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T3.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics6() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T4.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics7() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T5.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics8() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T6.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics9() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T7.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics10() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T8.js", false); } [Fact] [Trait("Category", "11.5.2")] public void TheResultOfDivisionIsDeterminedByTheSpecificationOfIeee754Arithmetics11() { RunTest(@"TestCases/ch11/11.5/11.5.2/S11.5.2_A4_T9.js", false); } } }
#if UNITY_ANDROID #pragma warning disable 0642 // Possible mistaken empty statement namespace GooglePlayGames.Android { using System; using System.Collections.Generic; using System.Text.RegularExpressions; using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.SavedGame; using GooglePlayGames.OurUtils; using UnityEngine; internal class AndroidSavedGameClient : ISavedGameClient { // Regex for a valid filename. Valid file names are between 1 and 100 characters (inclusive) // and only include URL-safe characters: a-z, A-Z, 0-9, or the symbols "-", ".", "_", or "~". // This regex is guarded by \A and \Z which guarantee that the entire string matches this // regex. If these were omitted, then illegal strings containing legal subsequences would be // allowed (since the regex would match those subsequences). private static readonly Regex ValidFilenameRegex = new Regex(@"\A[a-zA-Z0-9-._~]{1,100}\Z"); private volatile AndroidJavaObject mSnapshotsClient; private volatile AndroidClient mAndroidClient; public AndroidSavedGameClient(AndroidClient androidClient, AndroidJavaObject account) { mAndroidClient = androidClient; using (var gamesClass = new AndroidJavaClass("com.google.android.gms.games.Games")) { mSnapshotsClient = gamesClass.CallStatic<AndroidJavaObject>("getSnapshotsClient", AndroidHelperFragment.GetActivity(), account); } } public void OpenWithAutomaticConflictResolution(string filename, DataSource source, ConflictResolutionStrategy resolutionStrategy, Action<SavedGameRequestStatus, ISavedGameMetadata> completedCallback) { Misc.CheckNotNull(filename); Misc.CheckNotNull(completedCallback); bool prefetchDataOnConflict = false; ConflictCallback conflictCallback = null; completedCallback = ToOnGameThread(completedCallback); if (conflictCallback == null) { conflictCallback = (resolver, original, originalData, unmerged, unmergedData) => { switch (resolutionStrategy) { case ConflictResolutionStrategy.UseOriginal: resolver.ChooseMetadata(original); return; case ConflictResolutionStrategy.UseUnmerged: resolver.ChooseMetadata(unmerged); return; case ConflictResolutionStrategy.UseLongestPlaytime: if (original.TotalTimePlayed >= unmerged.TotalTimePlayed) { resolver.ChooseMetadata(original); } else { resolver.ChooseMetadata(unmerged); } return; default: OurUtils.Logger.e("Unhandled strategy " + resolutionStrategy); completedCallback(SavedGameRequestStatus.InternalError, null); return; } }; } conflictCallback = ToOnGameThread(conflictCallback); if (!IsValidFilename(filename)) { OurUtils.Logger.e("Received invalid filename: " + filename); completedCallback(SavedGameRequestStatus.BadInputError, null); return; } InternalOpen(filename, source, resolutionStrategy, prefetchDataOnConflict, conflictCallback, completedCallback); } public void OpenWithManualConflictResolution(string filename, DataSource source, bool prefetchDataOnConflict, ConflictCallback conflictCallback, Action<SavedGameRequestStatus, ISavedGameMetadata> completedCallback) { Misc.CheckNotNull(filename); Misc.CheckNotNull(conflictCallback); Misc.CheckNotNull(completedCallback); conflictCallback = ToOnGameThread(conflictCallback); completedCallback = ToOnGameThread(completedCallback); if (!IsValidFilename(filename)) { OurUtils.Logger.e("Received invalid filename: " + filename); completedCallback(SavedGameRequestStatus.BadInputError, null); return; } InternalOpen(filename, source, ConflictResolutionStrategy.UseManual, prefetchDataOnConflict, conflictCallback, completedCallback); } private void InternalOpen(string filename, DataSource source, ConflictResolutionStrategy resolutionStrategy, bool prefetchDataOnConflict, ConflictCallback conflictCallback, Action<SavedGameRequestStatus, ISavedGameMetadata> completedCallback) { int conflictPolicy; // SnapshotsClient.java#RetentionPolicy switch (resolutionStrategy) { case ConflictResolutionStrategy.UseLastKnownGood: conflictPolicy = 2 /* RESOLUTION_POLICY_LAST_KNOWN_GOOD */; break; case ConflictResolutionStrategy.UseMostRecentlySaved: conflictPolicy = 3 /* RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED */; break; case ConflictResolutionStrategy.UseLongestPlaytime: conflictPolicy = 1 /* RESOLUTION_POLICY_LONGEST_PLAYTIME*/; break; case ConflictResolutionStrategy.UseManual: conflictPolicy = -1 /* RESOLUTION_POLICY_MANUAL */; break; default: conflictPolicy = 3 /* RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED */; break; } using (var task = mSnapshotsClient.Call<AndroidJavaObject>("open", filename, /* createIfNotFound= */ true, conflictPolicy)) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, dataOrConflict => { if (dataOrConflict.Call<bool>("isConflict")) { var conflict = dataOrConflict.Call<AndroidJavaObject>("getConflict"); AndroidSnapshotMetadata original = new AndroidSnapshotMetadata(conflict.Call<AndroidJavaObject>("getSnapshot")); AndroidSnapshotMetadata unmerged = new AndroidSnapshotMetadata( conflict.Call<AndroidJavaObject>("getConflictingSnapshot")); // Instantiate the conflict resolver. Note that the retry callback closes over // all the parameters we need to retry the open attempt. Once the conflict is // resolved by invoking the appropriate resolution method on // AndroidConflictResolver, the resolver will invoke this callback, which will // result in this method being re-executed. This recursion will continue until // all conflicts are resolved or an error occurs. AndroidConflictResolver resolver = new AndroidConflictResolver( this, mSnapshotsClient, conflict, original, unmerged, completedCallback, () => InternalOpen(filename, source, resolutionStrategy, prefetchDataOnConflict, conflictCallback, completedCallback)); var originalBytes = original.JavaContents.Call<byte[]>("readFully"); var unmergedBytes = unmerged.JavaContents.Call<byte[]>("readFully"); conflictCallback(resolver, original, originalBytes, unmerged, unmergedBytes); } else { using (var snapshot = dataOrConflict.Call<AndroidJavaObject>("getData")) { AndroidJavaObject metadata = snapshot.Call<AndroidJavaObject>("freeze"); completedCallback(SavedGameRequestStatus.Success, new AndroidSnapshotMetadata(metadata)); } } }); AddOnFailureListenerWithSignOut( task, exception => { OurUtils.Logger.d("InternalOpen has failed: " + exception.Call<string>("toString")); var status = mAndroidClient.IsAuthenticated() ? SavedGameRequestStatus.InternalError : SavedGameRequestStatus.AuthenticationError; completedCallback(status, null); } ); } } public void ReadBinaryData(ISavedGameMetadata metadata, Action<SavedGameRequestStatus, byte[]> completedCallback) { Misc.CheckNotNull(metadata); Misc.CheckNotNull(completedCallback); completedCallback = ToOnGameThread(completedCallback); AndroidSnapshotMetadata convertedMetadata = metadata as AndroidSnapshotMetadata; if (convertedMetadata == null) { OurUtils.Logger.e("Encountered metadata that was not generated by this ISavedGameClient"); completedCallback(SavedGameRequestStatus.BadInputError, null); return; } if (!convertedMetadata.IsOpen) { OurUtils.Logger.e("This method requires an open ISavedGameMetadata."); completedCallback(SavedGameRequestStatus.BadInputError, null); return; } byte[] data = convertedMetadata.JavaContents.Call<byte[]>("readFully"); if (data == null) { completedCallback(SavedGameRequestStatus.BadInputError, null); } else { completedCallback(SavedGameRequestStatus.Success, data); } } public void ShowSelectSavedGameUI(string uiTitle, uint maxDisplayedSavedGames, bool showCreateSaveUI, bool showDeleteSaveUI, Action<SelectUIStatus, ISavedGameMetadata> callback) { Misc.CheckNotNull(uiTitle); Misc.CheckNotNull(callback); callback = ToOnGameThread(callback); if (!(maxDisplayedSavedGames > 0)) { OurUtils.Logger.e("maxDisplayedSavedGames must be greater than 0"); callback(SelectUIStatus.BadInputError, null); return; } AndroidHelperFragment.ShowSelectSnapshotUI( showCreateSaveUI, showDeleteSaveUI, (int) maxDisplayedSavedGames, uiTitle, callback); } public void CommitUpdate(ISavedGameMetadata metadata, SavedGameMetadataUpdate updateForMetadata, byte[] updatedBinaryData, Action<SavedGameRequestStatus, ISavedGameMetadata> callback) { Misc.CheckNotNull(metadata); Misc.CheckNotNull(updatedBinaryData); Misc.CheckNotNull(callback); callback = ToOnGameThread(callback); AndroidSnapshotMetadata convertedMetadata = metadata as AndroidSnapshotMetadata; if (convertedMetadata == null) { OurUtils.Logger.e("Encountered metadata that was not generated by this ISavedGameClient"); callback(SavedGameRequestStatus.BadInputError, null); return; } if (!convertedMetadata.IsOpen) { OurUtils.Logger.e("This method requires an open ISavedGameMetadata."); callback(SavedGameRequestStatus.BadInputError, null); return; } if (!convertedMetadata.JavaContents.Call<bool>("writeBytes", updatedBinaryData)) { OurUtils.Logger.e("This method requires an open ISavedGameMetadata."); callback(SavedGameRequestStatus.BadInputError, null); } using (var convertedMetadataChange = AsMetadataChange(updateForMetadata)) using (var task = mSnapshotsClient.Call<AndroidJavaObject>("commitAndClose", convertedMetadata.JavaSnapshot, convertedMetadataChange)) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, /* disposeResult= */ false, snapshotMetadata => { Debug.Log("commitAndClose.succeed"); callback(SavedGameRequestStatus.Success, new AndroidSnapshotMetadata(snapshotMetadata, /* contents= */null)); }); AddOnFailureListenerWithSignOut( task, exception => { Debug.Log("commitAndClose.failed: " + exception.Call<string>("toString")); var status = mAndroidClient.IsAuthenticated() ? SavedGameRequestStatus.InternalError : SavedGameRequestStatus.AuthenticationError; callback(status, null); }); } } public void FetchAllSavedGames(DataSource source, Action<SavedGameRequestStatus, List<ISavedGameMetadata>> callback) { Misc.CheckNotNull(callback); callback = ToOnGameThread(callback); using (var task = mSnapshotsClient.Call<AndroidJavaObject>("load", /* forecReload= */ source == DataSource.ReadNetworkOnly)) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, annotatedData => { using (var buffer = annotatedData.Call<AndroidJavaObject>("get")) { int count = buffer.Call<int>("getCount"); List<ISavedGameMetadata> result = new List<ISavedGameMetadata>(); for (int i = 0; i < count; ++i) { using (var metadata = buffer.Call<AndroidJavaObject>("get", i)) { result.Add(new AndroidSnapshotMetadata( metadata.Call<AndroidJavaObject>("freeze"), /* contents= */null)); } } buffer.Call("release"); callback(SavedGameRequestStatus.Success, result); } }); AddOnFailureListenerWithSignOut( task, exception => { OurUtils.Logger.d("FetchAllSavedGames failed: " + exception.Call<string>("toString")); var status = mAndroidClient.IsAuthenticated() ? SavedGameRequestStatus.InternalError : SavedGameRequestStatus.AuthenticationError; callback(status, new List<ISavedGameMetadata>()); } ); } } public void Delete(ISavedGameMetadata metadata) { AndroidSnapshotMetadata androidMetadata = metadata as AndroidSnapshotMetadata; Misc.CheckNotNull(androidMetadata); using (mSnapshotsClient.Call<AndroidJavaObject>("delete", androidMetadata.JavaMetadata)) ; } private void AddOnFailureListenerWithSignOut(AndroidJavaObject task, Action<AndroidJavaObject> callback) { AndroidTaskUtils.AddOnFailureListener( task, exception => { var statusCode = exception.Call<int>("getStatusCode"); if (statusCode == /* CommonStatusCodes.SignInRequired */ 4 || statusCode == /* GamesClientStatusCodes.CLIENT_RECONNECT_REQUIRED */ 26502) { mAndroidClient.SignOut(); } callback(exception); }); } private ConflictCallback ToOnGameThread(ConflictCallback conflictCallback) { return (resolver, original, originalData, unmerged, unmergedData) => { OurUtils.Logger.d("Invoking conflict callback"); PlayGamesHelperObject.RunOnGameThread(() => conflictCallback(resolver, original, originalData, unmerged, unmergedData)); }; } /// <summary> /// A helper class that encapsulates the state around resolving a file conflict. It holds all /// the state that is necessary to invoke <see cref="SnapshotManager.Resolve"/> as well as a /// callback that will re-attempt to open the file after the resolution concludes. /// </summary> private class AndroidConflictResolver : IConflictResolver { private readonly AndroidJavaObject mSnapshotsClient; private readonly AndroidJavaObject mConflict; private readonly AndroidSnapshotMetadata mOriginal; private readonly AndroidSnapshotMetadata mUnmerged; private readonly Action<SavedGameRequestStatus, ISavedGameMetadata> mCompleteCallback; private readonly Action mRetryFileOpen; private readonly AndroidSavedGameClient mAndroidSavedGameClient; internal AndroidConflictResolver(AndroidSavedGameClient androidSavedGameClient, AndroidJavaObject snapshotClient, AndroidJavaObject conflict, AndroidSnapshotMetadata original, AndroidSnapshotMetadata unmerged, Action<SavedGameRequestStatus, ISavedGameMetadata> completeCallback, Action retryOpen) { this.mAndroidSavedGameClient = androidSavedGameClient; this.mSnapshotsClient = Misc.CheckNotNull(snapshotClient); this.mConflict = Misc.CheckNotNull(conflict); this.mOriginal = Misc.CheckNotNull(original); this.mUnmerged = Misc.CheckNotNull(unmerged); this.mCompleteCallback = Misc.CheckNotNull(completeCallback); this.mRetryFileOpen = Misc.CheckNotNull(retryOpen); } public void ResolveConflict(ISavedGameMetadata chosenMetadata, SavedGameMetadataUpdate metadataUpdate, byte[] updatedData) { AndroidSnapshotMetadata convertedMetadata = chosenMetadata as AndroidSnapshotMetadata; if (convertedMetadata != mOriginal && convertedMetadata != mUnmerged) { OurUtils.Logger.e("Caller attempted to choose a version of the metadata that was not part " + "of the conflict"); mCompleteCallback(SavedGameRequestStatus.BadInputError, null); return; } using (var contentUpdate = mConflict.Call<AndroidJavaObject>("getResolutionSnapshotContents")) { if (!contentUpdate.Call<bool>("writeBytes", updatedData)) { OurUtils.Logger.e("Can't update snapshot contents during conflict resolution."); mCompleteCallback(SavedGameRequestStatus.BadInputError, null); } using (var convertedMetadataChange = AsMetadataChange(metadataUpdate)) using (var task = mSnapshotsClient.Call<AndroidJavaObject>( "resolveConflict", mConflict.Call<string>("getConflictId"), convertedMetadata.JavaMetadata.Call<string>("getSnapshotId"), convertedMetadataChange, contentUpdate)) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, dataOrConflict => mRetryFileOpen()); mAndroidSavedGameClient.AddOnFailureListenerWithSignOut( task, exception => { OurUtils.Logger.d("ResolveConflict failed: " + exception.Call<string>("toString")); var status = mAndroidSavedGameClient.mAndroidClient.IsAuthenticated() ? SavedGameRequestStatus.InternalError : SavedGameRequestStatus.AuthenticationError; mCompleteCallback(status, null); } ); } } } public void ChooseMetadata(ISavedGameMetadata chosenMetadata) { AndroidSnapshotMetadata convertedMetadata = chosenMetadata as AndroidSnapshotMetadata; if (convertedMetadata != mOriginal && convertedMetadata != mUnmerged) { OurUtils.Logger.e("Caller attempted to choose a version of the metadata that was not part " + "of the conflict"); mCompleteCallback(SavedGameRequestStatus.BadInputError, null); return; } using (var task = mSnapshotsClient.Call<AndroidJavaObject>( "resolveConflict", mConflict.Call<string>("getConflictId"), convertedMetadata.JavaSnapshot)) { AndroidTaskUtils.AddOnSuccessListener<AndroidJavaObject>( task, dataOrConflict => mRetryFileOpen()); mAndroidSavedGameClient.AddOnFailureListenerWithSignOut( task, exception => { OurUtils.Logger.d("ChooseMetadata failed: " + exception.Call<string>("toString")); var status = mAndroidSavedGameClient.mAndroidClient.IsAuthenticated() ? SavedGameRequestStatus.InternalError : SavedGameRequestStatus.AuthenticationError; mCompleteCallback(status, null); } ); } } } internal static bool IsValidFilename(string filename) { if (filename == null) { return false; } return ValidFilenameRegex.IsMatch(filename); } private static AndroidJavaObject AsMetadataChange(SavedGameMetadataUpdate update) { using (var builder = new AndroidJavaObject("com.google.android.gms.games.snapshot.SnapshotMetadataChange$Builder")) { if (update.IsCoverImageUpdated) { using (var bitmapFactory = new AndroidJavaClass("android.graphics.BitmapFactory")) using (var bitmap = bitmapFactory.CallStatic<AndroidJavaObject>( "decodeByteArray", update.UpdatedPngCoverImage, /* offset= */0, update.UpdatedPngCoverImage.Length)) using (builder.Call<AndroidJavaObject>("setCoverImage", bitmap)) ; } if (update.IsDescriptionUpdated) { using (builder.Call<AndroidJavaObject>("setDescription", update.UpdatedDescription)) ; } if (update.IsPlayedTimeUpdated) { using (builder.Call<AndroidJavaObject>("setPlayedTimeMillis", Convert.ToInt64(update.UpdatedPlayedTime.Value.TotalMilliseconds))) ; } return builder.Call<AndroidJavaObject>("build"); } } private static Action<T1, T2> ToOnGameThread<T1, T2>(Action<T1, T2> toConvert) { return (val1, val2) => PlayGamesHelperObject.RunOnGameThread(() => toConvert(val1, val2)); } } } #endif
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; using u32 = System.UInt32; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the implementation of generic hash-tables ** used in SQLite. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <assert.h> /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. ** ** "pNew" is a pointer to the hash table that is to be initialized. */ static void sqlite3HashInit( Hash pNew ) { Debug.Assert( pNew != null ); pNew.first = null; pNew.count = 0; pNew.htsize = 0; pNew.ht = null; } /* Remove all entries from a hash table. Reclaim all memory. ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ static void sqlite3HashClear( Hash pH ) { HashElem elem; /* For looping over all elements of the table */ Debug.Assert( pH != null ); elem = pH.first; pH.first = null; //sqlite3_free( ref pH.ht ); pH.ht = null; pH.htsize = 0; while ( elem != null ) { HashElem next_elem = elem.next; ////sqlite3_free(ref elem ); elem = next_elem; } pH.count = 0; } /* ** The hashing function. */ static u32 strHash( string z, int nKey ) { int h = 0; Debug.Assert( nKey >= 0 ); int _z = 0; while ( nKey > 0 ) { h = ( h << 3 ) ^ h ^ ( ( _z < z.Length ) ? (int)sqlite3UpperToLower[(byte)z[_z++]] : 0 ); nKey--; } return (u32)h; } /* Link pNew element into the hash table pH. If pEntry!=0 then also ** insert pNew into the pEntry hash bucket. */ static void insertElement( Hash pH, /* The complete hash table */ _ht pEntry, /* The entry into which pNew is inserted */ HashElem pNew /* The element to be inserted */ ) { HashElem pHead; /* First element already in pEntry */ if ( pEntry != null ) { pHead = pEntry.count != 0 ? pEntry.chain : null; pEntry.count++; pEntry.chain = pNew; } else { pHead = null; } if ( pHead != null ) { pNew.next = pHead; pNew.prev = pHead.prev; if ( pHead.prev != null ) { pHead.prev.next = pNew; } else { pH.first = pNew; } pHead.prev = pNew; } else { pNew.next = pH.first; if ( pH.first != null ) { pH.first.prev = pNew; } pNew.prev = null; pH.first = pNew; } } /* Resize the hash table so that it cantains "new_size" buckets. ** ** The hash table might fail to resize if sqlite3_malloc() fails or ** if the new size is the same as the prior size. ** Return TRUE if the resize occurs and false if not. */ static bool rehash( ref Hash pH, u32 new_size ) { _ht[] new_ht; /* The new hash table */ HashElem elem; HashElem next_elem; /* For looping over existing elements */ #if SQLITE_MALLOC_SOFT_LIMIT if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){ new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht); } if( new_size==pH->htsize ) return false; #endif /* There is a call to sqlite3Malloc() inside rehash(). If there is ** already an allocation at pH.ht, then if this malloc() fails it ** is benign (since failing to resize a hash table is a performance ** hit only, not a fatal error). */ sqlite3BeginBenignMalloc(); new_ht = new _ht[new_size]; //(struct _ht )sqlite3Malloc( new_size*sizeof(struct _ht) ); for ( int i = 0; i < new_size; i++ ) new_ht[i] = new _ht(); sqlite3EndBenignMalloc(); if ( new_ht == null ) return false; //sqlite3_free( ref pH.ht ); pH.ht = new_ht; // pH.htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); //memset(new_ht, 0, new_size*sizeof(struct _ht)); pH.htsize = new_size; for ( elem = pH.first, pH.first = null; elem != null; elem = next_elem ) { u32 h = strHash( elem.pKey, elem.nKey ) % new_size; next_elem = elem.next; insertElement( pH, new_ht[h], elem ); } return true; } /* This function (for internal use only) locates an element in an ** hash table that matches the given key. The hash for this key has ** already been computed and is passed as the 4th parameter. */ static HashElem findElementGivenHash( Hash pH, /* The pH to be searched */ string pKey, /* The key we are searching for */ int nKey, /* Bytes in key (not counting zero terminator) */ u32 h /* The hash for this key. */ ) { HashElem elem; /* Used to loop thru the element list */ int count; /* Number of elements left to test */ if ( pH.ht != null && pH.ht[h] != null ) { _ht pEntry = pH.ht[h]; elem = pEntry.chain; count = (int)pEntry.count; } else { elem = pH.first; count = (int)pH.count; } while ( count-- > 0 && ALWAYS( elem ) ) { if ( elem.nKey == nKey && elem.pKey.Equals( pKey, StringComparison.InvariantCultureIgnoreCase ) ) { return elem; } elem = elem.next; } return null; } /* Remove a single entry from the hash table given a pointer to that ** element and a hash on the element's key. */ static void removeElementGivenHash( Hash pH, /* The pH containing "elem" */ ref HashElem elem, /* The element to be removed from the pH */ u32 h /* Hash value for the element */ ) { _ht pEntry; if ( elem.prev != null ) { elem.prev.next = elem.next; } else { pH.first = elem.next; } if ( elem.next != null ) { elem.next.prev = elem.prev; } if ( pH.ht != null && pH.ht[h] != null ) { pEntry = pH.ht[h]; if ( pEntry.chain == elem ) { pEntry.chain = elem.next; } pEntry.count--; Debug.Assert( pEntry.count >= 0 ); } //sqlite3_free( ref elem ); pH.count--; if ( pH.count <= 0 ) { Debug.Assert( pH.first == null ); Debug.Assert( pH.count == 0 ); sqlite3HashClear( pH ); } } /* Attempt to locate an element of the hash table pH with a key ** that matches pKey,nKey. Return the data for this element if it is ** found, or NULL if there is no match. */ static T sqlite3HashFind<T>( Hash pH, string pKey, int nKey, T nullType ) where T : class { HashElem elem; /* The element that matches key */ u32 h; /* A hash on key */ Debug.Assert( pH != null ); Debug.Assert( pKey != null ); Debug.Assert( nKey >= 0 ); if ( pH.ht != null ) { h = strHash( pKey, nKey ) % pH.htsize; } else { h = 0; } elem = findElementGivenHash( pH, pKey, nKey, h ); return elem != null ? (T)elem.data : nullType; } /* Insert an element into the hash table pH. The key is pKey,nKey ** and the data is "data". ** ** If no element exists with a matching key, then a new ** element is created and NULL is returned. ** ** If another element already exists with the same key, then the ** new data replaces the old data and the old data is returned. ** The key is not copied in this instance. If a malloc fails, then ** the new data is returned and the hash table is unchanged. ** ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ static T sqlite3HashInsert<T>( ref Hash pH, string pKey, int nKey, T data ) where T : class { u32 h; /* the hash of the key modulo hash table size */ HashElem elem; /* Used to loop thru the element list */ HashElem new_elem; /* New element added to the pH */ Debug.Assert( pH != null ); Debug.Assert( pKey != null ); Debug.Assert( nKey >= 0 ); if ( pH.htsize != 0 ) { h = strHash( pKey, nKey ) % pH.htsize; } else { h = 0; } elem = findElementGivenHash( pH, pKey, nKey, h ); if ( elem != null ) { T old_data = (T)elem.data; if ( data == null ) { removeElementGivenHash( pH, ref elem, h ); } else { elem.data = data; elem.pKey = pKey; Debug.Assert( nKey == elem.nKey ); } return old_data; } if ( data == null ) return data; new_elem = new HashElem();//(HashElem)sqlite3Malloc( sizeof(HashElem) ); if ( new_elem == null ) return data; new_elem.pKey = pKey; new_elem.nKey = nKey; new_elem.data = data; pH.count++; if ( pH.count >= 10 && pH.count > 2 * pH.htsize ) { if ( rehash( ref pH, pH.count * 2 ) ) { Debug.Assert( pH.htsize > 0 ); h = strHash( pKey, nKey ) % pH.htsize; } } if ( pH.ht != null ) { insertElement( pH, pH.ht[h], new_elem ); } else { insertElement( pH, null, new_elem ); } return null; } } }
using System; using System.Collections; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Cms.Tests { [TestFixture] public class Rfc4134Test { private static readonly byte[] exContent = GetRfc4134Data("ExContent.bin"); private static readonly byte[] sha1 = Hex.Decode("406aec085279ba6e16022d9e0629c0229687dd48"); [Test] public void Test4_1() { byte[] data = GetRfc4134Data("4.1.bin"); CmsSignedData signedData = new CmsSignedData(data); VerifySignatures(signedData); CmsSignedDataParser parser = new CmsSignedDataParser(data); VerifySignatures(parser); } [Test] public void Test4_2() { byte[] data = GetRfc4134Data("4.2.bin"); CmsSignedData signedData = new CmsSignedData(data); VerifySignatures(signedData); CmsSignedDataParser parser = new CmsSignedDataParser(data); VerifySignatures(parser); } [Test] public void Test4_3() { CmsProcessableByteArray unencap = new CmsProcessableByteArray(exContent); byte[] data = GetRfc4134Data("4.3.bin"); CmsSignedData signedData = new CmsSignedData(unencap, data); VerifySignatures(signedData, sha1); CmsSignedDataParser parser = new CmsSignedDataParser( new CmsTypedStream(unencap.GetInputStream()), data); VerifySignatures(parser); } [Test] public void Test4_4() { byte[] data = GetRfc4134Data("4.4.bin"); byte[] counterSigCert = GetRfc4134Data("AliceRSASignByCarl.cer"); CmsSignedData signedData = new CmsSignedData(data); VerifySignatures(signedData, sha1); VerifySignerInfo4_4(GetFirstSignerInfo(signedData.GetSignerInfos()), counterSigCert); CmsSignedDataParser parser = new CmsSignedDataParser(data); VerifySignatures(parser); VerifySignerInfo4_4(GetFirstSignerInfo(parser.GetSignerInfos()), counterSigCert); } [Test] public void Test4_5() { byte[] data = GetRfc4134Data("4.5.bin"); CmsSignedData signedData = new CmsSignedData(data); VerifySignatures(signedData); CmsSignedDataParser parser = new CmsSignedDataParser(data); VerifySignatures(parser); } [Test] public void Test4_6() { byte[] data = GetRfc4134Data("4.6.bin"); CmsSignedData signedData = new CmsSignedData(data); VerifySignatures(signedData); CmsSignedDataParser parser = new CmsSignedDataParser(data); VerifySignatures(parser); } [Test] public void Test4_7() { byte[] data = GetRfc4134Data("4.7.bin"); CmsSignedData signedData = new CmsSignedData(data); VerifySignatures(signedData); CmsSignedDataParser parser = new CmsSignedDataParser(data); VerifySignatures(parser); } [Test] public void Test5_1() { byte[] data = GetRfc4134Data("5.1.bin"); CmsEnvelopedData envelopedData = new CmsEnvelopedData(data); VerifyEnvelopedData(envelopedData, CmsEnvelopedDataGenerator.DesEde3Cbc); CmsEnvelopedDataParser envelopedParser = new CmsEnvelopedDataParser(data); VerifyEnvelopedData(envelopedParser, CmsEnvelopedDataGenerator.DesEde3Cbc); } [Test] public void Test5_2() { byte[] data = GetRfc4134Data("5.2.bin"); CmsEnvelopedData envelopedData = new CmsEnvelopedData(data); VerifyEnvelopedData(envelopedData, CmsEnvelopedDataGenerator.RC2Cbc); CmsEnvelopedDataParser envelopedParser = new CmsEnvelopedDataParser(data); VerifyEnvelopedData(envelopedParser, CmsEnvelopedDataGenerator.RC2Cbc); } private void VerifyEnvelopedData(CmsEnvelopedData envelopedData, string symAlgorithmOID) { byte[] privKeyData = GetRfc4134Data("BobPrivRSAEncrypt.pri"); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyData); Assert.IsTrue(privKey.IsPrivate); Assert.IsTrue(privKey is RsaKeyParameters); RecipientInformationStore recipients = envelopedData.GetRecipientInfos(); Assert.AreEqual(envelopedData.EncryptionAlgOid, symAlgorithmOID); ArrayList c = new ArrayList(recipients.GetRecipients()); Assert.LessOrEqual(1, c.Count); Assert.GreaterOrEqual(2, c.Count); VerifyRecipient((RecipientInformation)c[0], privKey); if (c.Count == 2) { RecipientInformation recInfo = (RecipientInformation)c[1]; Assert.AreEqual(PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id, recInfo.KeyEncryptionAlgOid); } } private void VerifyEnvelopedData(CmsEnvelopedDataParser envelopedParser, string symAlgorithmOID) { byte[] privKeyData = GetRfc4134Data("BobPrivRSAEncrypt.pri"); AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyData); Assert.IsTrue(privKey.IsPrivate); Assert.IsTrue(privKey is RsaKeyParameters); RecipientInformationStore recipients = envelopedParser.GetRecipientInfos(); Assert.AreEqual(envelopedParser.EncryptionAlgOid, symAlgorithmOID); ArrayList c = new ArrayList(recipients.GetRecipients()); Assert.LessOrEqual(1, c.Count); Assert.GreaterOrEqual(2, c.Count); VerifyRecipient((RecipientInformation)c[0], privKey); if (c.Count == 2) { RecipientInformation recInfo = (RecipientInformation)c[1]; Assert.AreEqual(PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id, recInfo.KeyEncryptionAlgOid); } } private void VerifyRecipient(RecipientInformation recipient, AsymmetricKeyParameter privKey) { Assert.IsTrue(privKey.IsPrivate); Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id); byte[] recData = recipient.GetContent(privKey); Assert.IsTrue(Arrays.AreEqual(exContent, recData)); } private void VerifySignerInfo4_4(SignerInformation signerInfo, byte[] counterSigCert) { VerifyCounterSignature(signerInfo, counterSigCert); VerifyContentHint(signerInfo); } private SignerInformation GetFirstSignerInfo(SignerInformationStore store) { IEnumerator e = store.GetSigners().GetEnumerator(); e.MoveNext(); return (SignerInformation)e.Current; } private void VerifyCounterSignature(SignerInformation signInfo, byte[] certificate) { SignerInformation csi = GetFirstSignerInfo(signInfo.GetCounterSignatures()); X509Certificate cert = new X509CertificateParser().ReadCertificate(certificate); Assert.IsTrue(csi.Verify(cert)); } private void VerifyContentHint(SignerInformation signInfo) { Asn1.Cms.AttributeTable attrTable = signInfo.UnsignedAttributes; Asn1.Cms.Attribute attr = attrTable[CmsAttributes.ContentHint]; Assert.AreEqual(1, attr.AttrValues.Count); Asn1EncodableVector v = new Asn1EncodableVector( new DerUtf8String("Content Hints Description Buffer"), CmsObjectIdentifiers.Data); Assert.IsTrue(attr.AttrValues[0].Equals(new DerSequence(v))); } private void VerifySignatures(CmsSignedData s, byte[] contentDigest) { IX509Store x509Certs = s.GetCertificates("Collection"); IX509Store x509Crls = s.GetCrls("Collection"); SignerInformationStore signers = s.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; VerifySigner(signer, cert); if (contentDigest != null) { Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest())); } } ICollection certColl = x509Certs.GetMatches(null); ICollection crlColl = x509Crls.GetMatches(null); Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count); Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count); } private void VerifySignatures(CmsSignedData s) { VerifySignatures(s, null); } private void VerifySignatures(CmsSignedDataParser sp) { CmsTypedStream sc = sp.GetSignedContent(); if (sc != null) { sc.Drain(); } IX509Store x509Certs = sp.GetCertificates("Collection"); SignerInformationStore signers = sp.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate)certEnum.Current; VerifySigner(signer, cert); } } private void VerifySigner(SignerInformation signer, X509Certificate cert) { if (cert.GetPublicKey() is DsaPublicKeyParameters) { DsaPublicKeyParameters key = (DsaPublicKeyParameters)cert.GetPublicKey(); if (key.Parameters == null) { Assert.IsTrue(signer.Verify(GetInheritedKey(key))); } else { Assert.IsTrue(signer.Verify(cert)); } } else { Assert.IsTrue(signer.Verify(cert)); } } private DsaPublicKeyParameters GetInheritedKey(DsaPublicKeyParameters dsaPubKey) { X509Certificate cert = new X509CertificateParser().ReadCertificate( GetRfc4134Data("CarlDSSSelf.cer")); DsaParameters dsaParams = ((DsaPublicKeyParameters)cert.GetPublicKey()).Parameters; return new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams); } private static byte[] GetRfc4134Data(string name) { return Streams.ReadAll(SimpleTest.GetTestDataAsStream("rfc4134." + name)); } } }
// 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 Internal.Runtime.Augments; namespace System.Threading { /// <summary> /// A lightweight non-recursive mutex. /// /// Used by the wait subsystem on Unix, so this class cannot have any dependencies on the wait subsystem. /// </summary> internal sealed class LowLevelLock : IDisposable { private const int LockedMask = 1; private const int WaiterCountIncrement = 2; private const int MaximumPreemptingAcquireDurationMilliseconds = 200; /// <summary> /// Layout: /// - Bit 0: 1 if the lock is locked, 0 otherwise /// - Remaining bits: Number of threads waiting to acquire a lock /// </summary> private int _state; #if DEBUG private Thread _ownerThread; #endif /// <summary> /// Indicates whether a thread has been signaled, but has not yet been released from the wait. See /// <see cref="SignalWaiter"/>. Reads and writes must occur while <see cref="_monitor"/> is locked. /// </summary> private bool _isAnyWaitingThreadSignaled; private LowLevelSpinWaiter _spinWaiter; private readonly Func<bool> _spinWaitTryAcquireCallback; private readonly LowLevelMonitor _monitor; public LowLevelLock() { #if DEBUG _ownerThread = null; #endif _spinWaiter = new LowLevelSpinWaiter(); _spinWaitTryAcquireCallback = SpinWaitTryAcquireCallback; _monitor = new LowLevelMonitor(); } ~LowLevelLock() { Dispose(); } public void Dispose() { VerifyIsNotLockedByAnyThread(); if (_monitor != null) { _monitor.Dispose(); } GC.SuppressFinalize(this); } #if DEBUG public bool IsLocked { get { bool isLocked = _ownerThread == Thread.CurrentThread; Debug.Assert(!isLocked || (_state & LockedMask) != 0); return isLocked; } } #endif public void VerifyIsLocked() { #if DEBUG Debug.Assert(_ownerThread == Thread.CurrentThread); Debug.Assert((_state & LockedMask) != 0); #endif } public void VerifyIsNotLocked() { #if DEBUG Debug.Assert(_ownerThread != Thread.CurrentThread); #endif } private void VerifyIsNotLockedByAnyThread() { #if DEBUG Debug.Assert(_ownerThread == null); #endif } private void ResetOwnerThread() { #if DEBUG VerifyIsLocked(); _ownerThread = null; #endif } private void SetOwnerThreadToCurrent() { #if DEBUG VerifyIsNotLockedByAnyThread(); _ownerThread = Thread.CurrentThread; #endif } public bool TryAcquire() { VerifyIsNotLocked(); // A common case is that there are no waiters, so hope for that and try to acquire the lock int state = Interlocked.CompareExchange(ref _state, LockedMask, 0); if (state == 0 || TryAcquire_NoFastPath(state)) { SetOwnerThreadToCurrent(); return true; } return false; } private bool TryAcquire_NoFastPath(int state) { // The lock may be available, but there may be waiters. This thread could acquire the lock in that case. Acquiring // the lock means that if this thread is repeatedly acquiring and releasing the lock, it could permanently starve // waiters. Waiting instead in the same situation would deterministically create a lock convoy. Here, we opt for // acquiring the lock to prevent a deterministic lock convoy in that situation, and rely on the system's // waiting/waking implementation to mitigate starvation, even in cases where there are enough logical processors to // accommodate all threads. return (state & LockedMask) == 0 && Interlocked.CompareExchange(ref _state, state + LockedMask, state) == state; } private bool SpinWaitTryAcquireCallback() => TryAcquire_NoFastPath(_state); public void Acquire() { if (!TryAcquire()) { WaitAndAcquire(); } } private void WaitAndAcquire() { VerifyIsNotLocked(); // Spin a bit to see if the lock becomes available, before forcing the thread into a wait state if (_spinWaiter.SpinWaitForCondition(_spinWaitTryAcquireCallback)) { Debug.Assert((_state & LockedMask) != 0); SetOwnerThreadToCurrent(); return; } _monitor.Acquire(); /// Register this thread as a waiter by incrementing the waiter count. Incrementing the waiter count and waiting on /// the monitor need to appear atomic to <see cref="SignalWaiter"/> so that its signal won't be lost. int state = Interlocked.Add(ref _state, WaiterCountIncrement); // Wait on the monitor until signaled, repeatedly until the lock can be acquired by this thread while (true) { // The lock may have been released before the waiter count was incremented above, so try to acquire the lock // with the new state before waiting if ((state & LockedMask) == 0 && Interlocked.CompareExchange(ref _state, state + (LockedMask - WaiterCountIncrement), state) == state) { break; } _monitor.Wait(); /// Indicate to <see cref="SignalWaiter"/> that the signaled thread has woken up _isAnyWaitingThreadSignaled = false; state = _state; Debug.Assert((uint)state >= WaiterCountIncrement); } _monitor.Release(); Debug.Assert((_state & LockedMask) != 0); SetOwnerThreadToCurrent(); } public void Release() { Debug.Assert((_state & LockedMask) != 0); ResetOwnerThread(); if (Interlocked.Decrement(ref _state) != 0) { SignalWaiter(); } } private void SignalWaiter() { // Since the lock was already released by the caller, there are no guarantees on the state at this point. For // instance, if there was only one thread waiting before the lock was released, then after the lock was released, // another thread may have acquired and released the lock, and signaled the waiter, before the first thread arrives // here. The monitor's lock is used to synchronize changes to the waiter count, so acquire the monitor and recheck // the waiter count before signaling. _monitor.Acquire(); /// Keep track of whether a thread has been signaled but has not yet been released from the wait. /// <see cref="_isAnyWaitingThreadSignaled"/> is set to false when a signaled thread wakes up. Since threads can /// preempt waiting threads and acquire the lock (see <see cref="TryAcquire"/>), it allows for example, one thread /// to acquire and release the lock multiple times while there are multiple waiting threads. In such a case, we /// don't want that thread to signal a waiter every time it releases the lock, as that will cause unnecessary /// context switches with more and more signaled threads waking up, finding that the lock is still locked, and going /// right back into a wait state. So, signal only one waiting thread at a time. if ((uint)_state >= WaiterCountIncrement && !_isAnyWaitingThreadSignaled) { _isAnyWaitingThreadSignaled = true; _monitor.Signal_Release(); return; } _monitor.Release(); } } }
// 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, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using Microsoft.PythonTools; using Microsoft.PythonTools.Editor.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; using TestUtilities.Mocks; namespace PythonToolsTests { [TestClass] public class CommentBlockTests { [TestMethod, Priority(1)] public void TestCommentCurrentLine() { var view = new MockTextView( MockTextBuffer(@"print 'hello' print 'goodbye' ")); view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(0).Start); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"#print 'hello' print 'goodbye' ", view.TextBuffer.CurrentSnapshot.GetText()); view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestUnCommentCurrentLine() { var view = new MockTextView( MockTextBuffer(@"#print 'hello' #print 'goodbye'")); view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(0).Start); view.CommentOrUncommentBlock(false); Assert.AreEqual(@"print 'hello' #print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start); view.CommentOrUncommentBlock(false); Assert.AreEqual(@"print 'hello' print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestComment() { var view = new MockTextView( MockTextBuffer(@"print 'hello' print 'goodbye' ")); view.Selection.Select( new SnapshotSpan(view.TextBuffer.CurrentSnapshot, new Span(0, view.TextBuffer.CurrentSnapshot.Length)), false ); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestCommentEmptyLine() { var view = new MockTextView( MockTextBuffer(@"print 'hello' print 'goodbye' ")); view.Selection.Select( new SnapshotSpan(view.TextBuffer.CurrentSnapshot, new Span(0, view.TextBuffer.CurrentSnapshot.Length)), false ); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.TextBuffer.CurrentSnapshot.GetText()); } private static MockTextBuffer MockTextBuffer(string code) { return new MockTextBuffer(code, PythonCoreConstants.ContentType, "C:\\fob.py"); } [TestMethod, Priority(1)] public void TestCommentWhiteSpaceLine() { var view = new MockTextView( MockTextBuffer(@"print 'hello' print 'goodbye' ")); view.Selection.Select( new SnapshotSpan(view.TextBuffer.CurrentSnapshot, new Span(0, view.TextBuffer.CurrentSnapshot.Length)), false ); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"#print 'hello' #print 'goodbye' ", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestCommentIndented() { var view = new MockTextView( MockTextBuffer(@"def f(): print 'hello' print 'still here' print 'goodbye'")); view.Selection.Select( new SnapshotSpan( view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start, view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(2).End ), false ); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"def f(): #print 'hello' #print 'still here' print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestCommentIndentedBlankLine() { var view = new MockTextView( MockTextBuffer(@"def f(): print 'hello' print 'still here' print 'goodbye'")); view.Selection.Select( new SnapshotSpan( view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start, view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(3).End ), false ); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"def f(): #print 'hello' #print 'still here' print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestCommentBlankLine() { var view = new MockTextView( MockTextBuffer(@"print('hi') print('bye')")); view.Caret.MoveTo(view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"print('hi') print('bye')", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestCommentIndentedWhiteSpaceLine() { var view = new MockTextView( MockTextBuffer(@"def f(): print 'hello' print 'still here' print 'goodbye'")); view.Selection.Select( new SnapshotSpan( view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start, view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(3).End ), false ); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"def f(): #print 'hello' #print 'still here' print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestUnCommentIndented() { var view = new MockTextView( MockTextBuffer(@"def f(): #print 'hello' #print 'still here' print 'goodbye'")); view.Selection.Select( new SnapshotSpan( view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1).Start, view.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(2).End ), false ); view.CommentOrUncommentBlock(false); Assert.AreEqual(@"def f(): print 'hello' print 'still here' print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestUnComment() { var view = new MockTextView( MockTextBuffer(@"#print 'hello' #print 'goodbye'")); view.Selection.Select( new SnapshotSpan(view.TextBuffer.CurrentSnapshot, new Span(0, view.TextBuffer.CurrentSnapshot.Length)), false ); view.CommentOrUncommentBlock(false); Assert.AreEqual(@"print 'hello' print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } /// <summary> /// http://pytools.codeplex.com/workitem/814 /// </summary> [TestMethod, Priority(1)] public void TestCommentStartOfLastLine() { var view = new MockTextView( MockTextBuffer(@"print 'hello' print 'goodbye'")); view.Selection.Select( new SnapshotSpan(view.TextBuffer.CurrentSnapshot, new Span(0, view.TextBuffer.CurrentSnapshot.GetText().IndexOf("print 'goodbye'"))), false ); view.CommentOrUncommentBlock(true); Assert.AreEqual(@"#print 'hello' print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } [TestMethod, Priority(1)] public void TestCommentAfterCodeIsNotUncommented() { var view = new MockTextView( MockTextBuffer(@"print 'hello' #comment that should stay a comment #print 'still here' # another comment that should stay a comment print 'goodbye'")); view.Selection.Select( new SnapshotSpan(view.TextBuffer.CurrentSnapshot, new Span(0, view.TextBuffer.CurrentSnapshot.GetText().IndexOf("print 'goodbye'"))), false ); view.CommentOrUncommentBlock(false); Assert.AreEqual(@"print 'hello' #comment that should stay a comment print 'still here' # another comment that should stay a comment print 'goodbye'", view.TextBuffer.CurrentSnapshot.GetText()); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Stored SQL Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class QSDataSet : EduHubDataSet<QS> { /// <inheritdoc /> public override string Name { get { return "QS"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal QSDataSet(EduHubContext Context) : base(Context) { Index_QSKEY = new Lazy<Dictionary<string, QS>>(() => this.ToDictionary(i => i.QSKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="QS" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="QS" /> fields for each CSV column header</returns> internal override Action<QS, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<QS, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "QSKEY": mapper[i] = (e, v) => e.QSKEY = v; break; case "TITLE": mapper[i] = (e, v) => e.TITLE = v; break; case "SQLTEXT": mapper[i] = (e, v) => e.SQLTEXT = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="QS" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="QS" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="QS" /> entities</param> /// <returns>A merged <see cref="IEnumerable{QS}"/> of entities</returns> internal override IEnumerable<QS> ApplyDeltaEntities(IEnumerable<QS> Entities, List<QS> DeltaEntities) { HashSet<string> Index_QSKEY = new HashSet<string>(DeltaEntities.Select(i => i.QSKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.QSKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_QSKEY.Remove(entity.QSKEY); if (entity.QSKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, QS>> Index_QSKEY; #endregion #region Index Methods /// <summary> /// Find QS by QSKEY field /// </summary> /// <param name="QSKEY">QSKEY value used to find QS</param> /// <returns>Related QS entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public QS FindByQSKEY(string QSKEY) { return Index_QSKEY.Value[QSKEY]; } /// <summary> /// Attempt to find QS by QSKEY field /// </summary> /// <param name="QSKEY">QSKEY value used to find QS</param> /// <param name="Value">Related QS entity</param> /// <returns>True if the related QS entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByQSKEY(string QSKEY, out QS Value) { return Index_QSKEY.Value.TryGetValue(QSKEY, out Value); } /// <summary> /// Attempt to find QS by QSKEY field /// </summary> /// <param name="QSKEY">QSKEY value used to find QS</param> /// <returns>Related QS entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public QS TryFindByQSKEY(string QSKEY) { QS value; if (Index_QSKEY.Value.TryGetValue(QSKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a QS table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[QS]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[QS]( [QSKEY] varchar(10) NOT NULL, [TITLE] varchar(30) NULL, [SQLTEXT] varchar(MAX) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [QS_Index_QSKEY] PRIMARY KEY CLUSTERED ( [QSKEY] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="QSDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="QSDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="QS"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="QS"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<QS> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_QSKEY = new List<string>(); foreach (var entity in Entities) { Index_QSKEY.Add(entity.QSKEY); } builder.AppendLine("DELETE [dbo].[QS] WHERE"); // Index_QSKEY builder.Append("[QSKEY] IN ("); for (int index = 0; index < Index_QSKEY.Count; index++) { if (index != 0) builder.Append(", "); // QSKEY var parameterQSKEY = $"@p{parameterIndex++}"; builder.Append(parameterQSKEY); command.Parameters.Add(parameterQSKEY, SqlDbType.VarChar, 10).Value = Index_QSKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the QS data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the QS data set</returns> public override EduHubDataSetDataReader<QS> GetDataSetDataReader() { return new QSDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the QS data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the QS data set</returns> public override EduHubDataSetDataReader<QS> GetDataSetDataReader(List<QS> Entities) { return new QSDataReader(new EduHubDataSetLoadedReader<QS>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class QSDataReader : EduHubDataSetDataReader<QS> { public QSDataReader(IEduHubDataSetReader<QS> Reader) : base (Reader) { } public override int FieldCount { get { return 6; } } public override object GetValue(int i) { switch (i) { case 0: // QSKEY return Current.QSKEY; case 1: // TITLE return Current.TITLE; case 2: // SQLTEXT return Current.SQLTEXT; case 3: // LW_DATE return Current.LW_DATE; case 4: // LW_TIME return Current.LW_TIME; case 5: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // TITLE return Current.TITLE == null; case 2: // SQLTEXT return Current.SQLTEXT == null; case 3: // LW_DATE return Current.LW_DATE == null; case 4: // LW_TIME return Current.LW_TIME == null; case 5: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // QSKEY return "QSKEY"; case 1: // TITLE return "TITLE"; case 2: // SQLTEXT return "SQLTEXT"; case 3: // LW_DATE return "LW_DATE"; case 4: // LW_TIME return "LW_TIME"; case 5: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "QSKEY": return 0; case "TITLE": return 1; case "SQLTEXT": return 2; case "LW_DATE": return 3; case "LW_TIME": return 4; case "LW_USER": return 5; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using FluentAssertions; using NSubstitute; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Threading.Tasks; using Toggl.Core.DataSources.Interfaces; using Toggl.Core.Models.Interfaces; using Toggl.Core.Sync.States.CleanUp; using Toggl.Core.Tests.Generators; using Toggl.Core.Tests.Mocks; using Toggl.Storage; using Toggl.Storage.Models; using Xunit; namespace Toggl.Core.Tests.Sync.States.CleanUp { public class DeleteNonReferencedInaccessibleWorkspacesStateTests { private readonly DeleteNonReferencedInaccessibleWorkspacesState state; private readonly IDataSource<IThreadSafeWorkspace, IDatabaseWorkspace> workspacesDataSource = Substitute.For<IDataSource<IThreadSafeWorkspace, IDatabaseWorkspace>>(); private readonly IDataSource<IThreadSafeTimeEntry, IDatabaseTimeEntry> timeEntriesDataSource = Substitute.For<IDataSource<IThreadSafeTimeEntry, IDatabaseTimeEntry>>(); private readonly IDataSource<IThreadSafeProject, IDatabaseProject> projectsDataSource = Substitute.For<IDataSource<IThreadSafeProject, IDatabaseProject>>(); private readonly IDataSource<IThreadSafeTask, IDatabaseTask> tasksDataSource = Substitute.For<IDataSource<IThreadSafeTask, IDatabaseTask>>(); private readonly IDataSource<IThreadSafeClient, IDatabaseClient> clientsDataSource = Substitute.For<IDataSource<IThreadSafeClient, IDatabaseClient>>(); private readonly IDataSource<IThreadSafeTag, IDatabaseTag> tagsDataSource = Substitute.For<IDataSource<IThreadSafeTag, IDatabaseTag>>(); public DeleteNonReferencedInaccessibleWorkspacesStateTests() { state = new DeleteNonReferencedInaccessibleWorkspacesState( workspacesDataSource, timeEntriesDataSource, projectsDataSource, tasksDataSource, clientsDataSource, tagsDataSource ); } [Theory, LogIfTooSlow] [ConstructorData] public void ThrowsIfAnyOfTheArgumentsIsNull( bool useWorkspaces, bool useTimeEntries, bool useProjects, bool useTasks, bool useClients, bool useTags) { var theWorkspaces = useWorkspaces ? workspacesDataSource : null; var theTimeEntries = useTimeEntries ? timeEntriesDataSource : null; var theProjects = useProjects ? projectsDataSource : null; var theTasks = useTasks ? tasksDataSource : null; var theClients = useClients ? clientsDataSource : null; var theTags = useTags ? tagsDataSource : null; Action tryingToConstructWithEmptyParameters = () => new DeleteNonReferencedInaccessibleWorkspacesState( theWorkspaces, theTimeEntries, theProjects, theTasks, theClients, theTags ); tryingToConstructWithEmptyParameters.Should().Throw<Exception>(); } [Fact, LogIfTooSlow] public async Task DeleteInaccessibleWorkspacesNotReferencedByTimeEntries() { var accessibleReferenced = new MockWorkspace(1, false, SyncStatus.InSync); var accessibleUnreferenced = new MockWorkspace(2, false, SyncStatus.InSync); var inaccessibleReferenced = new MockWorkspace(3, true, SyncStatus.InSync); var inaccessibleUnreferenced = new MockWorkspace(4, true, SyncStatus.InSync); var timeEntry1 = new MockTimeEntry(11, accessibleReferenced, syncStatus: SyncStatus.InSync); var timeEntry2 = new MockTimeEntry(22, inaccessibleReferenced, syncStatus: SyncStatus.InSync); var workspaces = new[] { accessibleReferenced, accessibleUnreferenced, inaccessibleReferenced, inaccessibleUnreferenced }; var timeEntries = new[] { timeEntry1, timeEntry2 }; configureDataSources(workspaces, timeEntries: timeEntries); await state.Start().SingleAsync(); workspacesDataSource.Received().DeleteAll(Arg.Is<IEnumerable<IThreadSafeWorkspace>>( arg => arg.All(ws => ws == inaccessibleUnreferenced))); } [Fact, LogIfTooSlow] public async Task DeleteInaccessibleWorkspacesNotReferencedByProjects() { var accessibleReferenced = new MockWorkspace(1, false, SyncStatus.InSync); var accessibleUnreferenced = new MockWorkspace(2, false, SyncStatus.InSync); var inaccessibleReferenced = new MockWorkspace(3, true, SyncStatus.InSync); var inaccessibleUnreferenced = new MockWorkspace(4, true, SyncStatus.InSync); var project1 = new MockProject(11, accessibleReferenced, syncStatus: SyncStatus.InSync); var project2 = new MockProject(22, inaccessibleReferenced, syncStatus: SyncStatus.InSync); var workspaces = new[] { accessibleReferenced, accessibleUnreferenced, inaccessibleReferenced, inaccessibleUnreferenced }; var projects = new[] { project1, project2 }; configureDataSources(workspaces, projects: projects); await state.Start().SingleAsync(); workspacesDataSource.Received().DeleteAll(Arg.Is<IEnumerable<IThreadSafeWorkspace>>( arg => arg.All(ws => ws == inaccessibleUnreferenced))); } [Fact, LogIfTooSlow] public async Task DeleteInaccessibleWorkspacesNotReferencedByTasks() { var accessibleReferenced = new MockWorkspace(1, false, SyncStatus.InSync); var accessibleUnreferenced = new MockWorkspace(2, false, SyncStatus.InSync); var inaccessibleReferenced = new MockWorkspace(3, true, SyncStatus.InSync); var inaccessibleUnreferenced = new MockWorkspace(4, true, SyncStatus.InSync); var project1 = new MockProject(11, accessibleReferenced, syncStatus: SyncStatus.InSync); var project2 = new MockProject(22, inaccessibleReferenced, syncStatus: SyncStatus.InSync); var task1 = new MockTask(11, accessibleReferenced, project1, syncStatus: SyncStatus.InSync); var task2 = new MockTask(22, inaccessibleReferenced, project2, syncStatus: SyncStatus.InSync); var workspaces = new[] { accessibleReferenced, accessibleUnreferenced, inaccessibleReferenced, inaccessibleUnreferenced }; var tasks = new[] { task1, task2 }; configureDataSources(workspaces, tasks: tasks); await state.Start().SingleAsync(); workspacesDataSource.Received().DeleteAll(Arg.Is<IEnumerable<IThreadSafeWorkspace>>( arg => arg.All(ws => ws == inaccessibleUnreferenced))); } [Fact, LogIfTooSlow] public async Task DeleteInaccessibleWorkspacesNotReferencedByClients() { var accessibleReferenced = new MockWorkspace(1, false, SyncStatus.InSync); var accessibleUnreferenced = new MockWorkspace(2, false, SyncStatus.InSync); var inaccessibleReferenced = new MockWorkspace(3, true, SyncStatus.InSync); var inaccessibleUnreferenced = new MockWorkspace(4, true, SyncStatus.InSync); var client1 = new MockClient(11, accessibleReferenced, syncStatus: SyncStatus.InSync); var client2 = new MockClient(22, inaccessibleReferenced, syncStatus: SyncStatus.InSync); var workspaces = new[] { accessibleReferenced, accessibleUnreferenced, inaccessibleReferenced, inaccessibleUnreferenced }; var clients = new[] { client1, client2 }; configureDataSources(workspaces, clients: clients); await state.Start().SingleAsync(); workspacesDataSource.Received().DeleteAll(Arg.Is<IEnumerable<IThreadSafeWorkspace>>( arg => arg.All(ws => ws == inaccessibleUnreferenced))); } [Fact, LogIfTooSlow] public async Task DeleteInaccessibleWorkspacesNotReferencedByTags() { var accessibleReferenced = new MockWorkspace(1, false, SyncStatus.InSync); var accessibleUnreferenced = new MockWorkspace(2, false, SyncStatus.InSync); var inaccessibleReferenced = new MockWorkspace(3, true, SyncStatus.InSync); var inaccessibleUnreferenced = new MockWorkspace(4, true, SyncStatus.InSync); var tag1 = new MockTag(11, accessibleReferenced, syncStatus: SyncStatus.InSync); var tag2 = new MockTag(22, inaccessibleReferenced, syncStatus: SyncStatus.InSync); var workspaces = new[] { accessibleReferenced, accessibleUnreferenced, inaccessibleReferenced, inaccessibleUnreferenced }; var tags = new[] { tag1, tag2 }; configureDataSources(workspaces, tags: tags); await state.Start().SingleAsync(); workspacesDataSource.Received().DeleteAll(Arg.Is<IEnumerable<IThreadSafeWorkspace>>( arg => arg.All(ws => ws == inaccessibleUnreferenced))); } private void configureDataSources( IEnumerable<IThreadSafeWorkspace> workspaces, IEnumerable<IThreadSafeTimeEntry> timeEntries = null, IEnumerable<IThreadSafeProject> projects = null, IEnumerable<IThreadSafeTask> tasks = null, IEnumerable<IThreadSafeClient> clients = null, IEnumerable<IThreadSafeTag> tags = null) { configureDataSource(workspacesDataSource, workspaces); configureDataSource(timeEntriesDataSource, timeEntries ?? Array.Empty<IThreadSafeTimeEntry>()); configureDataSource(projectsDataSource, projects ?? Array.Empty<IThreadSafeProject>()); configureDataSource(tasksDataSource, tasks ?? Array.Empty<IThreadSafeTask>()); configureDataSource(clientsDataSource, clients ?? Array.Empty<IThreadSafeClient>()); configureDataSource(tagsDataSource, tags ?? Array.Empty<IThreadSafeTag>()); } private void configureDataSource<TInterface, TDatabaseInterface>( IDataSource<TInterface, TDatabaseInterface> dataSource, IEnumerable<TInterface> collection) where TInterface : TDatabaseInterface, IThreadSafeModel where TDatabaseInterface : IDatabaseModel { dataSource .GetAll(Arg.Any<Func<TDatabaseInterface, bool>>(), Arg.Is(true)) .Returns(callInfo => { var predicate = callInfo[0] as Func<TDatabaseInterface, bool>; var filteredCollection = collection.Cast<TDatabaseInterface>().Where(predicate); return Observable.Return(filteredCollection.Cast<TInterface>()); }); } } }
///////////////////////////////////////////////////////////////////////////////// // Paint.NET (MIT,from version 3.36.7, see=> https://github.com/rivy/OpenPDN // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See src/Resources/Files/License.txt for full licensing and attribution // // details. // // . // ///////////////////////////////////////////////////////////////////////////////// //MIT, 2017-present, WinterDev using System; using PixelFarm.Drawing; namespace PaintFx { /// <summary> /// Histogram is used to calculate a histogram for a surface (in a selection, /// if desired). This can then be used to retrieve percentile, average, peak, /// and distribution information. /// </summary> public abstract class Histogram { protected long[][] _histogram; public long[][] HistogramValues { get { return _histogram; } set { if (value.Length == _histogram.Length && value[0].Length == _histogram[0].Length) { _histogram = value; OnHistogramUpdated(); } else { throw new ArgumentException("value muse be an array of arrays of matching size", "value"); } } } public int Channels => _histogram.Length; public int Entries => _histogram[0].Length; protected internal Histogram(int channels, int entries) { _histogram = new long[channels][]; for (int channel = 0; channel < channels; ++channel) { _histogram[channel] = new long[entries]; } } public event EventHandler HistogramChanged; protected void OnHistogramUpdated() { if (HistogramChanged != null) { HistogramChanged(this, EventArgs.Empty); } } protected ColorBgra[] _visualColors; public ColorBgra GetVisualColor(int channel) => _visualColors[channel]; public long GetOccurrences(int channel, int val) => _histogram[channel][val]; public long GetMax() { long max = -1; foreach (long[] channelHistogram in _histogram) { foreach (long i in channelHistogram) { if (i > max) { max = i; } } } return max; } public long GetMax(int channel) { long max = -1; foreach (long i in _histogram[channel]) { if (i > max) { max = i; } } return max; } public float[] GetMean() { float[] ret = new float[Channels]; for (int channel = 0; channel < Channels; ++channel) { long[] channelHistogram = _histogram[channel]; long avg = 0; long sum = 0; for (int j = 0; j < channelHistogram.Length; j++) { avg += j * channelHistogram[j]; sum += channelHistogram[j]; } if (sum != 0) { ret[channel] = (float)avg / (float)sum; } else { ret[channel] = 0; } } return ret; } public int[] GetPercentile(float fraction) { int[] ret = new int[Channels]; for (int channel = 0; channel < Channels; ++channel) { long[] channelHistogram = _histogram[channel]; long integral = 0; long sum = 0; for (int j = 0; j < channelHistogram.Length; j++) { sum += channelHistogram[j]; } for (int j = 0; j < channelHistogram.Length; j++) { integral += channelHistogram[j]; if (integral > sum * fraction) { ret[channel] = j; break; } } } return ret; } public abstract ColorBgra GetMeanColor(); public abstract ColorBgra GetPercentileColor(float fraction); /// <summary> /// Sets the histogram to be all zeros. /// </summary> protected void Clear() { _histogram.Initialize(); } protected abstract void AddSurfaceRectangleToHistogram(Surface surface, Rectangle rect); public void UpdateHistogram(Surface surface) { Clear(); AddSurfaceRectangleToHistogram(surface, surface.Bounds); OnHistogramUpdated(); } public void UpdateHistogram(Surface surface, Rectangle rect) { Clear(); AddSurfaceRectangleToHistogram(surface, rect); OnHistogramUpdated(); } //public void UpdateHistogram(Surface surface, PdnRegion roi) //{ // Clear(); // foreach (Rectangle rect in roi.GetRegionScansReadOnlyInt()) // { // AddSurfaceRectangleToHistogram(surface, rect); // } // OnHistogramUpdated(); //} } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // This is used internally to create best fit behavior as per the original windows best fit behavior. // using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Text; using System.Threading; namespace System.Text { internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal BaseCodePageEncoding encoding = null; internal char[] arrayBestFit = null; internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding) { // Need to load our replacement characters table. encoding = _encoding; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals(Object value) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if (that != null) { return (encoding.CodePage == that.encoding.CodePage); } return (false); } public override int GetHashCode() { return encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char _cBestFit = '\0'; private InternalEncoderBestFitFallback _oFallback; private int _iCount = -1; private int _iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback.arrayBestFit == null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. if (_oFallback.arrayBestFit == null) _oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData(); } } } // Fallback methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); _iCount = _iSize = 1; _cBestFit = TryBestFit(charUnknown); if (_cBestFit == '\0') _cBestFit = '?'; return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException("charUnknownHigh", SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException("CharUnknownLow", SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit _cBestFit = '?'; _iCount = _iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs 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. _iCount--; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (_iCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } // Return the best fit character return _cBestFit; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if (_iCount >= 0) _iCount++; // Return true if we could do it. return (_iCount >= 0 && _iCount <= _iSize); } // How many characters left to output? public override int Remaining { get { return (_iCount > 0) ? _iCount : 0; } } // Clear the buffer [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe void Reset() { _iCount = -1; } // private helper methods private char TryBestFit(char cUnknown) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = _oFallback.arrayBestFit.Length; int index; // Binary search the array int iDiff; while ((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = _oFallback.arrayBestFit[index]; if (cTest == cUnknown) { // We found it Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback.arrayBestFit[index + 1]; } else if (cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for (index = lowBound; index < highBound; index += 2) { if (_oFallback.arrayBestFit[index] == cUnknown) { // We found it Debug.Assert(index + 1 < _oFallback.arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback.arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { public sealed class BuildJobExtension : JobExtension { public override Type ExtensionType => typeof(IJobExtension); public override HostTypes HostType => HostTypes.Build; public override IStep GetExtensionPreJobStep(IExecutionContext jobContext) { return null; } public override IStep GetExtensionPostJobStep(IExecutionContext jobContext) { return null; } // 1. use source provide to solve path, if solved result is rooted, return full path. // 2. prefix default path root (build.sourcesDirectory), if result is rooted, return full path. public override string GetRootedPath(IExecutionContext context, string path) { string rootedPath = null; TryGetRepositoryInfo(context, out RepositoryInfo repoInfo); if (repoInfo.SourceProvider != null && repoInfo.PrimaryRepository != null && StringUtil.ConvertToBoolean(repoInfo.PrimaryRepository.Properties.Get<string>("__AZP_READY"))) { path = repoInfo.SourceProvider.GetLocalPath(context, repoInfo.PrimaryRepository, path) ?? string.Empty; Trace.Info($"Build JobExtension resolving path use source provide: {path}"); if (!string.IsNullOrEmpty(path) && path.IndexOfAny(Path.GetInvalidPathChars()) < 0 && Path.IsPathRooted(path)) { try { rootedPath = Path.GetFullPath(path); Trace.Info($"Path resolved by source provider is a rooted path, return absolute path: {rootedPath}"); return rootedPath; } catch (Exception ex) { Trace.Info($"Path resolved by source provider is a rooted path, but it is not a full qualified path: {path}"); Trace.Error(ex); } } } string defaultPathRoot = null; if (RepositoryUtil.HasMultipleCheckouts(context.JobSettings)) { // If there are multiple checkouts, set the default directory to the sources root folder (_work/1/s) defaultPathRoot = context.Variables.Get(Constants.Variables.Build.SourcesDirectory); Trace.Info($"The Default Path Root of Build JobExtension is build.sourcesDirectory: {defaultPathRoot}"); } else if (repoInfo.PrimaryRepository != null) { // If there is only one checkout/repository, set it to the repository path defaultPathRoot = repoInfo.PrimaryRepository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Path); Trace.Info($"The Default Path Root of Build JobExtension is repository.path: {defaultPathRoot}"); } if (defaultPathRoot != null && defaultPathRoot.IndexOfAny(Path.GetInvalidPathChars()) < 0 && path != null && path.IndexOfAny(Path.GetInvalidPathChars()) < 0) { path = Path.Combine(defaultPathRoot, path); Trace.Info($"After prefix Default Path Root provide by JobExtension: {path}"); if (Path.IsPathRooted(path)) { try { rootedPath = Path.GetFullPath(path); Trace.Info($"Return absolute path after prefix DefaultPathRoot: {rootedPath}"); return rootedPath; } catch (Exception ex) { Trace.Error(ex); Trace.Info($"After prefix Default Path Root provide by JobExtension, the Path is a rooted path, but it is not full qualified, return the path: {path}."); return path; } } } return rootedPath; } public override void ConvertLocalPath(IExecutionContext context, string localPath, out string repoName, out string sourcePath) { repoName = ""; TryGetRepositoryInfoFromLocalPath(context, localPath, out RepositoryInfo repoInfo); // If no repo was found, send back an empty repo with original path. sourcePath = localPath; if (!string.IsNullOrEmpty(localPath) && File.Exists(localPath) && repoInfo.PrimaryRepository != null && repoInfo.SourceProvider != null) { // If we found a repo, calculate the relative path to the file var repoPath = repoInfo.PrimaryRepository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Path); if (!string.IsNullOrEmpty(repoPath)) { sourcePath = IOUtil.MakeRelative(localPath, repoPath); } } } // Prepare build directory // Set all build related variables public override void InitializeJobExtension(IExecutionContext executionContext, IList<Pipelines.JobStep> steps, Pipelines.WorkspaceOptions workspace) { // Validate args. Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); // This flag can be false for jobs like cleanup artifacts. // If syncSources = false, we will not set source related build variable, not create build folder, not sync source. bool syncSources = executionContext.Variables.Build_SyncSources ?? true; if (!syncSources) { Trace.Info($"{Constants.Variables.Build.SyncSources} = false, we will not set source related build variable, not create build folder and not sync source"); return; } // We set the variables based on the 'self' repository if (!TryGetRepositoryInfo(executionContext, out RepositoryInfo repoInfo)) { throw new Exception(StringUtil.Loc("SupportedRepositoryEndpointNotFound")); } executionContext.Debug($"Triggering repository: {repoInfo.TriggeringRepository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Name)}. repository type: {repoInfo.TriggeringRepository.Type}"); // Set the repo variables. if (!string.IsNullOrEmpty(repoInfo.TriggeringRepository.Id)) // TODO: Move to const after source artifacts PR is merged. { executionContext.SetVariable(Constants.Variables.Build.RepoId, repoInfo.TriggeringRepository.Id); } executionContext.SetVariable(Constants.Variables.Build.RepoName, repoInfo.TriggeringRepository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Name)); executionContext.SetVariable(Constants.Variables.Build.RepoProvider, ConvertToLegacyRepositoryType(repoInfo.TriggeringRepository.Type)); executionContext.SetVariable(Constants.Variables.Build.RepoUri, repoInfo.TriggeringRepository.Url?.AbsoluteUri); // Prepare the build directory. executionContext.Output(StringUtil.Loc("PrepareBuildDir")); var directoryManager = HostContext.GetService<IBuildDirectoryManager>(); TrackingConfig trackingConfig = directoryManager.PrepareDirectory( executionContext, executionContext.Repositories, workspace); string _workDirectory = HostContext.GetDirectory(WellKnownDirectory.Work); string pipelineWorkspaceDirectory = Path.Combine(_workDirectory, trackingConfig.BuildDirectory); UpdateCheckoutTasksAndVariables(executionContext, steps, pipelineWorkspaceDirectory); // Get default value for RepoLocalPath variable string selfRepoPath = GetDefaultRepoLocalPathValue(executionContext, steps, trackingConfig, repoInfo); // Set the directory variables. executionContext.Output(StringUtil.Loc("SetBuildVars")); executionContext.SetVariable(Constants.Variables.Agent.BuildDirectory, pipelineWorkspaceDirectory, isFilePath: true); executionContext.SetVariable(Constants.Variables.System.ArtifactsDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory), isFilePath: true); executionContext.SetVariable(Constants.Variables.System.DefaultWorkingDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory), isFilePath: true); executionContext.SetVariable(Constants.Variables.Common.TestResultsDirectory, Path.Combine(_workDirectory, trackingConfig.TestResultsDirectory), isFilePath: true); executionContext.SetVariable(Constants.Variables.Build.BinariesDirectory, Path.Combine(_workDirectory, trackingConfig.BuildDirectory, Constants.Build.Path.BinariesDirectory), isFilePath: true); executionContext.SetVariable(Constants.Variables.Build.SourcesDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory), isFilePath: true); executionContext.SetVariable(Constants.Variables.Build.StagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory), isFilePath: true); executionContext.SetVariable(Constants.Variables.Build.ArtifactStagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory), isFilePath: true); executionContext.SetVariable(Constants.Variables.Build.RepoLocalPath, Path.Combine(_workDirectory, selfRepoPath), isFilePath: true); executionContext.SetVariable(Constants.Variables.Pipeline.Workspace, pipelineWorkspaceDirectory, isFilePath: true); } private void UpdateCheckoutTasksAndVariables(IExecutionContext executionContext, IList<JobStep> steps, string pipelineWorkspaceDirectory) { bool? submoduleCheckout = null; // RepoClean may be set from the server, so start with the server value bool? repoCleanFromServer = executionContext.Variables.GetBoolean(Constants.Variables.Build.RepoClean); // The value for the global clean option will be set in this variable based on Self repository clean input if the global value weren't set by the server bool? repoCleanFromSelf = null; var checkoutTasks = steps.Where(x => x.IsCheckoutTask()).Select(x => x as TaskStep).ToList(); var hasOnlyOneCheckoutTask = checkoutTasks.Count == 1; foreach (var checkoutTask in checkoutTasks) { if (!checkoutTask.Inputs.TryGetValue(PipelineConstants.CheckoutTaskInputs.Repository, out string repositoryAlias)) { // If the checkout task isn't associated with a repo, just skip it Trace.Info($"Checkout task {checkoutTask.Name} does not have a repository property."); continue; } // Update the checkout "Clean" property for all repos, if the variable was set by the server. if (repoCleanFromServer.HasValue) { checkoutTask.Inputs[PipelineConstants.CheckoutTaskInputs.Clean] = repoCleanFromServer.Value.ToString(); } Trace.Info($"Checking repository name {repositoryAlias}"); // If this is the primary repository, use it to get the variable values // A repository is considered the primary one if the name is 'self' or if there is only // one checkout task. This is because Designer builds set the name of the repository something // other than 'self' if (hasOnlyOneCheckoutTask || RepositoryUtil.IsPrimaryRepositoryName(repositoryAlias)) { submoduleCheckout = checkoutTask.Inputs.ContainsKey(PipelineConstants.CheckoutTaskInputs.Submodules); if (!repoCleanFromServer.HasValue && checkoutTask.Inputs.TryGetValue(PipelineConstants.CheckoutTaskInputs.Clean, out string cleanInputValue)) { repoCleanFromSelf = Boolean.TryParse(cleanInputValue, out bool cleanValue) ? cleanValue : true; } } // Update the checkout task display name if not already set if (string.IsNullOrEmpty(checkoutTask.DisplayName) || string.Equals(checkoutTask.DisplayName, "Checkout", StringComparison.OrdinalIgnoreCase) || // this is the default for jobs string.Equals(checkoutTask.DisplayName, checkoutTask.Name, StringComparison.OrdinalIgnoreCase)) // this is the default for deployment jobs { var repository = RepositoryUtil.GetRepository(executionContext.Repositories, repositoryAlias); if (repository != null) { string repoName = repository.Properties.Get<string>(RepositoryPropertyNames.Name); string version = RepositoryUtil.TrimStandardBranchPrefix(repository.Properties.Get<string>(RepositoryPropertyNames.Ref)); string path = null; if (checkoutTask.Inputs.ContainsKey(PipelineConstants.CheckoutTaskInputs.Path)) { path = checkoutTask.Inputs[PipelineConstants.CheckoutTaskInputs.Path]; } else { path = IOUtil.MakeRelative(repository.Properties.Get<string>(RepositoryPropertyNames.Path), pipelineWorkspaceDirectory); } checkoutTask.DisplayName = StringUtil.Loc("CheckoutTaskDisplayNameFormat", repoName, version, path); } else { Trace.Info($"Checkout task {checkoutTask.Name} has a repository property {repositoryAlias} that does not match any repository resource."); } } } // Set variables if (submoduleCheckout.HasValue) { executionContext.SetVariable(Constants.Variables.Build.RepoGitSubmoduleCheckout, submoduleCheckout.Value.ToString()); } if (repoCleanFromSelf.HasValue) { executionContext.SetVariable(Constants.Variables.Build.RepoClean, repoCleanFromSelf.Value.ToString()); } } private bool TryGetRepositoryInfoFromLocalPath(IExecutionContext executionContext, string localPath, out RepositoryInfo repoInfo) { // Return the matching repository resource and its source provider. Trace.Entering(); var repo = RepositoryUtil.GetRepositoryForLocalPath(executionContext.Repositories, localPath); repoInfo = new RepositoryInfo { PrimaryRepository = repo, SourceProvider = GetSourceProvider(executionContext, repo), }; return repoInfo.SourceProvider != null; } private bool TryGetRepositoryInfo(IExecutionContext executionContext, out RepositoryInfo repoInfo) { // Return the matching repository resource and its source provider. Trace.Entering(); var primaryRepo = RepositoryUtil.GetPrimaryRepository(executionContext.Repositories); var triggeringRepo = RepositoryUtil.GetTriggeringRepository(executionContext.Repositories); repoInfo = new RepositoryInfo { PrimaryRepository = primaryRepo, TriggeringRepository = triggeringRepo, SourceProvider = GetSourceProvider(executionContext, primaryRepo), }; return repoInfo.SourceProvider != null; } private ISourceProvider GetSourceProvider(IExecutionContext executionContext, RepositoryResource repository) { if (repository != null) { var extensionManager = HostContext.GetService<IExtensionManager>(); List<ISourceProvider> sourceProviders = extensionManager.GetExtensions<ISourceProvider>(); var sourceProvider = sourceProviders.FirstOrDefault(x => string.Equals(x.RepositoryType, repository.Type, StringComparison.OrdinalIgnoreCase)); return sourceProvider; } return null; } private string ConvertToLegacyRepositoryType(string pipelineRepositoryType) { if (String.Equals(pipelineRepositoryType, Pipelines.RepositoryTypes.Bitbucket, StringComparison.OrdinalIgnoreCase)) { return "Bitbucket"; } else if (String.Equals(pipelineRepositoryType, Pipelines.RepositoryTypes.ExternalGit, StringComparison.OrdinalIgnoreCase)) { return "Git"; } else if (String.Equals(pipelineRepositoryType, Pipelines.RepositoryTypes.Git, StringComparison.OrdinalIgnoreCase)) { return "TfsGit"; } else if (String.Equals(pipelineRepositoryType, Pipelines.RepositoryTypes.GitHub, StringComparison.OrdinalIgnoreCase)) { return "GitHub"; } else if (String.Equals(pipelineRepositoryType, Pipelines.RepositoryTypes.GitHubEnterprise, StringComparison.OrdinalIgnoreCase)) { return "GitHubEnterprise"; } else if (String.Equals(pipelineRepositoryType, Pipelines.RepositoryTypes.Svn, StringComparison.OrdinalIgnoreCase)) { return "Svn"; } else if (String.Equals(pipelineRepositoryType, Pipelines.RepositoryTypes.Tfvc, StringComparison.OrdinalIgnoreCase)) { return "TfsVersionControl"; } else { throw new NotSupportedException(pipelineRepositoryType); } } private string GetDefaultRepoLocalPathValue(IExecutionContext executionContext, IList<Pipelines.JobStep> steps, TrackingConfig trackingConfig, RepositoryInfo repoInfo) { string selfRepoPath = null; // For saving backward compatibility with the behavior of the Build.RepoLocalPath that was before this PR https://github.com/microsoft/azure-pipelines-agent/pull/3237 // We need to change how we set the default value of this variable // We need to allow the setting of paths from RepositoryTrackingInfo for checkout tasks where path input was provided by the user // and this input is not point to the default location for this repository // This is the only case where the value of Build.RepoLocalPath variable is not pointing to the root of sources directory /s. // The new logic is not affecting single checkout jobs and jobs with multiple checkouts and default paths for Self repository if (RepositoryUtil.HasMultipleCheckouts(executionContext.JobSettings)) { // get checkout task for self repo var selfCheckoutTask = GetSelfCheckoutTask(steps); // Check if the task has path input with custom path, if so we need to set as a value of selfRepoPath the value of SourcesDirectory from RepositoryTrackingInfo if (IsCheckoutToCustomPath(trackingConfig, repoInfo, selfCheckoutTask)) { selfRepoPath = trackingConfig.RepositoryTrackingInfo .Where(repo => RepositoryUtil.IsPrimaryRepositoryName(repo.Identifier)) .Select(props => props.SourcesDirectory).FirstOrDefault(); } } // For single checkout jobs and multicheckout jobs with default paths set selfRepoPath to the default sources directory if (selfRepoPath == null) { selfRepoPath = trackingConfig.SourcesDirectory; } return selfRepoPath; } private bool IsCheckoutToCustomPath(TrackingConfig trackingConfig, RepositoryInfo repoInfo, TaskStep selfCheckoutTask) { string path; string selfRepoName = RepositoryUtil.GetCloneDirectory(repoInfo.PrimaryRepository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Name)); string defaultRepoCheckoutPath = Path.GetFullPath(Path.Combine(trackingConfig.SourcesDirectory, selfRepoName)); return selfCheckoutTask != null && selfCheckoutTask.Inputs.TryGetValue(PipelineConstants.CheckoutTaskInputs.Path, out path) && !string.Equals(Path.GetFullPath(Path.Combine(trackingConfig.BuildDirectory, path)), defaultRepoCheckoutPath, IOUtil.FilePathStringComparison); } private TaskStep GetSelfCheckoutTask(IList<JobStep> steps) { return steps.Select(x => x as TaskStep) .Where(task => task.IsCheckoutTask() && task.Inputs.TryGetValue(PipelineConstants.CheckoutTaskInputs.Repository, out string repositoryAlias) && RepositoryUtil.IsPrimaryRepositoryName(repositoryAlias)).FirstOrDefault(); } private class RepositoryInfo { public Pipelines.RepositoryResource PrimaryRepository { set; get; } public Pipelines.RepositoryResource TriggeringRepository { set; get; } public ISourceProvider SourceProvider { set; get; } } } }
// // Collection.cs // // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using ScriptSharp.Importer.IL; namespace ScriptSharp.Collections.Generic { internal /* public */ class Collection<T> : IList<T>, IList { internal T [] items; internal int size; int version; public int Count { get { return size; } } public T this [int index] { get { if (index >= size) throw new ArgumentOutOfRangeException (); return items [index]; } set { CheckIndex (index); if (index == size) throw new ArgumentOutOfRangeException (); OnSet (value, index); items [index] = value; } } bool ICollection<T>.IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this [int index] { get { return this [index]; } set { CheckIndex (index); try { this [index] = (T) value; return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } } int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } public Collection () { items = Empty<T>.Array; } public Collection (int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException (); items = new T [capacity]; } public Collection (ICollection<T> items) { this.items = new T [items.Count]; items.CopyTo (this.items, 0); this.size = this.items.Length; } public void Add (T item) { if (size == items.Length) Grow (1); OnAdd (item, size); items [size++] = item; version++; } public bool Contains (T item) { return IndexOf (item) != -1; } public int IndexOf (T item) { return Array.IndexOf (items, item, 0, size); } public void Insert (int index, T item) { CheckIndex (index); if (size == items.Length) Grow (1); OnInsert (item, index); Shift (index, 1); items [index] = item; version++; } public void RemoveAt (int index) { if (index < 0 || index >= size) throw new ArgumentOutOfRangeException (); var item = items [index]; OnRemove (item, index); Shift (index, -1); Array.Clear (items, size, 1); version++; } public bool Remove (T item) { var index = IndexOf (item); if (index == -1) return false; OnRemove (item, index); Shift (index, -1); Array.Clear (items, size, 1); version++; return true; } public void Clear () { OnClear (); Array.Clear (items, 0, size); size = 0; version++; } public void CopyTo (T [] array, int arrayIndex) { Array.Copy (items, 0, array, arrayIndex, size); } public T [] ToArray () { var array = new T [size]; Array.Copy (items, 0, array, 0, size); return array; } void CheckIndex (int index) { if (index < 0 || index > size) throw new ArgumentOutOfRangeException (); } void Shift (int start, int delta) { if (delta < 0) start -= delta; if (start < size) Array.Copy (items, start, items, start + delta, size - start); size += delta; if (delta < 0) Array.Clear (items, size, -delta); } protected virtual void OnAdd (T item, int index) { } protected virtual void OnInsert (T item, int index) { } protected virtual void OnSet (T item, int index) { } protected virtual void OnRemove (T item, int index) { } protected virtual void OnClear () { } internal virtual void Grow (int desired) { int new_size = size + desired; if (new_size <= items.Length) return; const int default_capacity = 4; new_size = System.Math.Max ( System.Math.Max (items.Length * 2, default_capacity), new_size); #if !CF Array.Resize (ref items, new_size); #else var array = new T [new_size]; Array.Copy (items, array, size); items = array; #endif } int IList.Add (object value) { try { Add ((T) value); return size - 1; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } void IList.Clear () { Clear (); } bool IList.Contains (object value) { return ((IList) this).IndexOf (value) > -1; } int IList.IndexOf (object value) { try { return IndexOf ((T) value); } catch (InvalidCastException) { } catch (NullReferenceException) { } return -1; } void IList.Insert (int index, object value) { CheckIndex (index); try { Insert (index, (T) value); return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } void IList.Remove (object value) { try { Remove ((T) value); } catch (InvalidCastException) { } catch (NullReferenceException) { } } void IList.RemoveAt (int index) { RemoveAt (index); } void ICollection.CopyTo (Array array, int index) { Array.Copy (items, 0, array, index, size); } public Enumerator GetEnumerator () { return new Enumerator (this); } IEnumerator IEnumerable.GetEnumerator () { return new Enumerator (this); } IEnumerator<T> IEnumerable<T>.GetEnumerator () { return new Enumerator (this); } public struct Enumerator : IEnumerator<T>, IDisposable { Collection<T> collection; T current; int next; readonly int version; public T Current { get { return current; } } object IEnumerator.Current { get { CheckState (); if (next <= 0) throw new InvalidOperationException (); return current; } } internal Enumerator (Collection<T> collection) : this () { this.collection = collection; this.version = collection.version; } public bool MoveNext () { CheckState (); if (next < 0) return false; if (next < collection.size) { current = collection.items [next++]; return true; } next = -1; return false; } public void Reset () { CheckState (); next = 0; } void CheckState () { if (collection == null) throw new ObjectDisposedException (GetType ().FullName); if (version != collection.version) throw new InvalidOperationException (); } public void Dispose () { collection = null; } } } }
using System; using System.Collections; using UnityEngine; namespace Assets.SpatialMatchmaking { /// <summary> /// Primary interface for communicating with the matchmaking service. /// /// Apply this component to a GameObject and initialize the public fields to control the matchmaking process. /// </summary> public class MatchClient : MonoBehaviour { /// <summary> /// The INetworkInterface implementation to use for low level networking with other peers /// </summary> public INetworkInterface NetworkInterface; /// <summary> /// The ILocationInterface implementation to use when sending location data to the server /// </summary> public ILocationInterface LocationInterface; /// <summary> /// The base URL of the matchmaking service /// </summary> public string BaseUrl; /// <summary> /// A game name, which is converted into a matchmaking requirement so you only match with other instances of the same game /// </summary> public string GameName; /// <summary> /// Maximum radius for location-based matching /// </summary> public int MaxMatchRadius; /// <summary> /// Called after successful connection /// </summary> public event Action OnSuccess; /// <summary> /// Called on giving up, when MaxFailures matchmaking attempts have been made and failed /// </summary> public event Action OnFailure; /// <summary> /// Called during the connection process to report status changes and errors /// </summary> public event Action<bool, string> OnLogEvent; /// <summary> /// Indicates whether a connection has been established /// </summary> public bool Connected { get; private set; } /// <summary> /// Maximum number of failed matchmaking attempts before giving up /// </summary> public int MaxFailures = 10; /// <summary> /// Maximum number of seconds to wait for location service initialization /// </summary> public int LocationInitTimeout = 20; /// <summary> /// Delay after unexpected server errors, before reattempting matchmaking /// </summary> public int UnexpectedServerErrorRetryDelay = 5; /// <summary> /// Delay after failing to connect to a host, before retrying the connection /// </summary> public int ConnectToHostFailRetryDelay = 1; /// <summary> /// Duration a host will wait for a client to connect before giving up and requesting a new match /// </summary> public float HostWaitForClientTimeout = 20; /// <summary> /// Duration a client will wait while attempting to connect to a host before abandoning the connection /// </summary> public int ConnectToHostTimeout = 9; private void Log(string message) { if (OnLogEvent != null) OnLogEvent(false, message); } private void LogError(string message) { if (OnLogEvent != null) OnLogEvent(true, message); } private static JsonObject RequireAttribute(string attribute, params string[] values) { return new JsonObject { { "@type", "requireAttribute" }, { "attribute", attribute }, { "values", new JsonArray(values) } }; } private static JsonObject RequireNotUuid(string uuid) { return new JsonObject { { "@type", "requireNotUuid" }, { "uuid", uuid } }; } private static JsonObject RequireLocationWithin(int radius) { return new JsonObject { { "@type", "requireLocationWithin" }, { "radius", radius } }; } public IEnumerator Start() { Log("waiting for location"); yield return StartCoroutine(LocationInterface.Init(LocationInitTimeout)); if (!LocationInterface.Ready) { LogError("Location service failed"); if (OnFailure != null) OnFailure(); yield break; } Log("registering"); var requirements = new JsonArray { RequireAttribute("gameName", GameName), RequireLocationWithin(MaxMatchRadius) }; var location = LocationInterface.Location; var postData = new JsonObject { { "uuid", Guid.NewGuid().ToString() }, { "connectionInfo", NetworkInterface.GetConnectionInfo() }, { "location", new JsonObject { {"longitude", location.Longitude}, {"latitude", location.Latitude}, }}, { "requirements", requirements }, }; var headers = new Hashtable(); headers["Content-Type"] = "application/json"; var www = new WWW(BaseUrl + "/clients", postData.ToByteArray(), headers); yield return www; if (www.error != null) { Debug.LogError("WWW error: " + www.error); LogError("registration failed"); yield break; } if (www.responseHeaders["CONTENT-TYPE"] != "application/json") { Debug.LogError("Bad content type received: " + www.responseHeaders["CONTENT-TYPE"]); LogError("registration failed"); yield break; } var clientData = new JsonObject(www.text); // "failures" counts the number of times we hit error cases from the server, so we can retry on errors but still give up if it's really broken. // It doesn't necessarily increase each time through the loop. var failures = 0; while (failures < MaxFailures) { Log("waiting for match"); while (true) { www = new WWW(BaseUrl + string.Format("/matches?client={0}", clientData.GetInteger("id"))); yield return www; if (www.error != null) { LogError("WWW error: " + www.error); yield break; } if (www.text == "") { Log("still waiting for match"); continue; } break; } if (www.error != null) { Log("wait-for-match failure, trying again in a while"); ++failures; yield return new WaitForSeconds(UnexpectedServerErrorRetryDelay); continue; } Log("fetching match data"); var sessionId = new JsonObject(www.text).GetInteger("id"); www = new WWW(BaseUrl + string.Format("/matches/{0}", sessionId)); yield return www; if (www.error != null) { LogError("WWW error: " + www.error); Log("failed to fetch match data, trying again in a while"); ++failures; yield return new WaitForSeconds(UnexpectedServerErrorRetryDelay); continue; } var clients = new JsonObject(www.text).GetArray("clients"); var otherClient = clients.GetInteger(0) + clients.GetInteger(1) - clientData.GetInteger("id"); Log("fetching other client data"); www = new WWW(BaseUrl + string.Format("/clients/{0}", otherClient)); yield return www; if (www.error != null) { LogError("WWW error: " + www.error); Log("failed to fetch other client data, trying again in a while"); ++failures; yield return new WaitForSeconds(UnexpectedServerErrorRetryDelay); continue; } var otherClientData = new JsonObject(www.text); var isHost = clients.GetInteger(0) == clientData.GetInteger("id"); if (isHost) { Log("hosting - waiting for other client to join"); var startTime = Time.realtimeSinceStartup; if (NetworkInterface.StartListening(otherClientData.GetString("uuid"))) { while (!NetworkInterface.Connected) { if (Time.realtimeSinceStartup - startTime > HostWaitForClientTimeout) { NetworkInterface.StopListening(); Log("Timeout waiting for client to connect"); yield return new WaitForSeconds(1); break; } yield return null; } } else { LogError(NetworkInterface.NetworkError); Log("failed to initialize as host"); yield return new WaitForSeconds(1); } } else { // This really shouldn't be here. We probably need a way for the host to not fill in the connectionInfo until // it is ready to accept connections, and this delay should be replaced by the client polling for that info to // become available. (The barrier to this is that currently updating client info clears all matches...) Log("waiting for a few seconds to let the host start"); yield return new WaitForSeconds(4); var attempts = 0; while (!NetworkInterface.Connected) { Log("connecting to host"); var startTime = Time.realtimeSinceStartup; var startConnectingOk = NetworkInterface.StartConnecting(otherClientData.GetString("connectionInfo"), clientData.GetString("uuid")); var timedOut = false; if (startConnectingOk) { while (NetworkInterface.Connecting && !timedOut) { timedOut = Time.realtimeSinceStartup - startTime > ConnectToHostTimeout; yield return null; } } if (NetworkInterface.Connected) continue; if (!startConnectingOk) { LogError(NetworkInterface.NetworkError); Log("error connecting to host - trying again"); } else if (timedOut) { Log("timeout connecting to host - trying again"); } else { LogError(NetworkInterface.NetworkError); Log("error connecting to host - trying again"); } ++attempts; if (attempts >= 3) break; yield return new WaitForSeconds(ConnectToHostFailRetryDelay); } } if (!NetworkInterface.Connected) { Log("giving up connecting, will find another match"); // We failed to connect to the peer, so explicitly ask the server not to match us with the same peer again requirements.Add(RequireNotUuid(otherClientData.GetString("uuid"))); postData.Set("requirements", requirements); www = new WWW(BaseUrl + string.Format("/clients/{0}/update", clientData.GetInteger("id")), postData.ToByteArray(), headers); yield return www; if (www.error != null) { LogError("WWW error: " + www.error); Log("error while updating requirements to exclude this partner"); } ++failures; yield return new WaitForSeconds(1); continue; } // connected Log("Connected"); Connected = true; break; } // either connected or given up connecting // tidy up yield return new WWW(BaseUrl + string.Format("/clients/{0}/delete", clientData.GetInteger("id")), new JsonObject().ToByteArray()); if (Connected && OnSuccess != null) OnSuccess(); else if (!Connected && OnFailure != null) OnFailure(); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections.Generic; using System.Globalization; using NLog.Config; using NLog.Targets; using NLog.UnitTests.Common; namespace NLog.UnitTests.Fluent { using System; using System.IO; using Xunit; using NLog.Fluent; public class LogBuilderTests : NLogTestBase { private static readonly ILogger _logger = LogManager.GetLogger("logger1"); private LogEventInfo _lastLogEventInfo; public LogBuilderTests() { var configuration = new LoggingConfiguration(); var t1 = new MethodCallTarget("t1", (l, parms) => _lastLogEventInfo = l); var t2 = new DebugTarget { Name = "t2", Layout = "${message}" }; configuration.AddTarget(t1); configuration.AddTarget(t2); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t1)); configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, t2)); LogManager.Configuration = configuration; } [Fact] public void TraceWrite() { TraceWrite_internal(() => _logger.Trace()); } #if NET4_5 [Fact] public void TraceWrite_static_builder() { TraceWrite_internal(() => Log.Trace(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void TraceWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "TraceWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } var ticks = DateTime.Now.Ticks; logBuilder() .Message("This is a test fluent message '{0}'.", ticks) .Property("Test", "TraceWrite") .Write(); { var rendered = $"This is a test fluent message '{ticks}'."; var expectedEvent = new LogEventInfo(LogLevel.Trace, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessage("t2", rendered); } } [Fact] public void TraceWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Trace() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void WarnWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Warn() .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Warn, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void LogWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } [Fact] public void LogOffWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; var props2 = new Dictionary<string, object> { {"prop1", "4"}, {"prop2", "5"}, }; _logger.Log(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); _logger.Log(LogLevel.Off) .Message("dont log this.") .Properties(props2).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "logger1", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #if NET4_5 [Fact] public void LevelWriteProperties() { var props = new Dictionary<string, object> { {"prop1", "1"}, {"prop2", "2"}, }; Log.Level(LogLevel.Fatal) .Message("This is a test fluent message.") .Properties(props).Write(); { var expectedEvent = new LogEventInfo(LogLevel.Fatal, "LogBuilderTests", "This is a test fluent message."); expectedEvent.Properties["prop1"] = "1"; expectedEvent.Properties["prop2"] = "2"; AssertLastLogEventTarget(expectedEvent); } } #endif [Fact] public void TraceIfWrite() { _logger.Trace() .Message("This is a test fluent message.1") .Property("Test", "TraceWrite") .Write(); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent message.1"); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); } int v = 1; _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("dont write this! '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(() => { return false; }); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("This is a test fluent WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v == 1); { var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } _logger.Trace() .Message("Should Not WriteIf message '{0}'.", DateTime.Now.Ticks) .Property("Test", "TraceWrite") .WriteIf(v > 1); { //previous var expectedEvent = new LogEventInfo(LogLevel.Trace, "logger1", "This is a test fluent WriteIf message '{0}'."); expectedEvent.Properties["Test"] = "TraceWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent WriteIf message "); } } [Fact] public void InfoWrite() { InfoWrite_internal(() => _logger.Info()); } #if NET4_5 [Fact] public void InfoWrite_static_builder() { InfoWrite_internal(() => Log.Info(), true); } #endif ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void InfoWrite_internal(Func<LogBuilder> logBuilder, bool isStatic = false) { logBuilder() .Message("This is a test fluent message.") .Property("Test", "InfoWrite") .Write(); var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "InfoWrite") .Write(); { //previous var expectedEvent = new LogEventInfo(LogLevel.Info, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "InfoWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } [Fact] public void DebugWrite() { ErrorWrite_internal(() => _logger.Debug(), LogLevel.Debug); } #if NET4_5 [Fact] public void DebugWrite_static_builder() { ErrorWrite_internal(() => Log.Debug(), LogLevel.Debug, true); } #endif [Fact] public void FatalWrite() { ErrorWrite_internal(() => _logger.Fatal(), LogLevel.Fatal); } #if NET4_5 [Fact] public void FatalWrite_static_builder() { ErrorWrite_internal(() => Log.Fatal(), LogLevel.Fatal, true); } #endif [Fact] public void ErrorWrite() { ErrorWrite_internal(() => _logger.Error(), LogLevel.Error); } #if NET4_5 [Fact] public void ErrorWrite_static_builder() { ErrorWrite_internal(() => Log.Error(), LogLevel.Error, true); } #endif [Fact] public void LogBuilder_null_lead_to_ArgumentNullException() { var logger = LogManager.GetLogger("a"); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null, LogLevel.Debug)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(null)); Assert.Throws<ArgumentNullException>(() => new LogBuilder(logger, null)); var logBuilder = new LogBuilder(logger); Assert.Throws<ArgumentNullException>(() => logBuilder.Properties(null)); Assert.Throws<ArgumentNullException>(() => logBuilder.Property(null, "b")); } [Fact] public void LogBuilder_nLogEventInfo() { var d = new DateTime(2015, 01, 30, 14, 30, 5); var logEventInfo = new LogBuilder(LogManager.GetLogger("a")).LoggerName("b").Level(LogLevel.Fatal).TimeStamp(d).LogEventInfo; Assert.Equal("b", logEventInfo.LoggerName); Assert.Equal(LogLevel.Fatal, logEventInfo.Level); Assert.Equal(d, logEventInfo.TimeStamp); } [Fact] public void LogBuilder_exception_only() { var ex = new Exception("Exception message1"); _logger.Error() .Exception(ex) .Write(); var expectedEvent = new LogEventInfo(LogLevel.Error, "logger1", null) { Exception = ex }; AssertLastLogEventTarget(expectedEvent); } [Fact] public void LogBuilder_null_logLevel() { Assert.Throws<ArgumentNullException>(() => _logger.Error().Level(null)); } [Fact] public void LogBuilder_message_overloadsTest() { LogManager.ThrowExceptions = true; _logger.Debug() .Message("Message with {0} arg", 1) .Write(); AssertDebugLastMessage("t2", "Message with 1 arg"); _logger.Debug() .Message("Message with {0} args. {1}", 2, "YES") .Write(); AssertDebugLastMessage("t2", "Message with 2 args. YES"); _logger.Debug() .Message("Message with {0} args. {1} {2}", 3, ":) ", 2) .Write(); AssertDebugLastMessage("t2", "Message with 3 args. :) 2"); _logger.Debug() .Message("Message with {0} args. {1} {2}{3}", "more", ":) ", 2, "b") .Write(); AssertDebugLastMessage("t2", "Message with more args. :) 2b"); } [Fact] public void LogBuilder_message_cultureTest() { if (IsTravis()) { Console.WriteLine("[SKIP] LogBuilderTests.LogBuilder_message_cultureTest because we are running in Travis"); return; } LogManager.Configuration.DefaultCultureInfo = GetCultureInfo("en-US"); _logger.Debug() .Message("Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4.1 4.001 12/31/2016 12:00:00 AM True"); _logger.Debug() .Message(GetCultureInfo("nl-nl"), "Message with {0} {1} {2} {3}", 4.1, 4.001, new DateTime(2016, 12, 31), true) .Write(); AssertDebugLastMessage("t2", "Message with 4,1 4,001 31-12-2016 00:00:00 True"); } [Fact] public void LogBuilder_Structured_Logging_Test() { var logEvent = _logger.Info().Property("Property1Key", "Property1Value").Message("{@message}", "My custom message").LogEventInfo; Assert.NotEmpty(logEvent.Properties); Assert.Contains("message", logEvent.Properties.Keys); Assert.Contains("Property1Key", logEvent.Properties.Keys); } ///<remarks> /// func because 1 logbuilder creates 1 message /// /// Caution: don't use overloading, that will break xUnit: /// CATASTROPHIC ERROR OCCURRED: /// System.ArgumentException: Ambiguous method named TraceWrite in type NLog.UnitTests.Fluent.LogBuilderTests /// </remarks> private void ErrorWrite_internal(Func<LogBuilder> logBuilder, LogLevel logLevel, bool isStatic = false) { Exception catchedException = null; string path = "blah.txt"; try { string text = File.ReadAllText(path); } catch (Exception ex) { catchedException = ex; logBuilder() .Message("Error reading file '{0}'.", path) .Exception(ex) .Property("Test", "ErrorWrite") .Write(); } var loggerName = isStatic ? "LogBuilderTests" : "logger1"; { var expectedEvent = new LogEventInfo(logLevel, loggerName, "Error reading file '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; expectedEvent.Exception = catchedException; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "Error reading file '"); } logBuilder() .Message("This is a test fluent message.") .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); } logBuilder() .Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks) .Property("Test", "ErrorWrite") .Write(); { var expectedEvent = new LogEventInfo(logLevel, loggerName, "This is a test fluent message '{0}'."); expectedEvent.Properties["Test"] = "ErrorWrite"; AssertLastLogEventTarget(expectedEvent); AssertDebugLastMessageContains("t2", "This is a test fluent message '"); } } /// <summary> /// Test the written logevent /// </summary> /// <param name="expected">exptected event to be logged.</param> void AssertLastLogEventTarget(LogEventInfo expected) { Assert.NotNull(_lastLogEventInfo); Assert.Equal(expected.Message, _lastLogEventInfo.Message); Assert.NotNull(_lastLogEventInfo.Properties); // TODO NLog ver. 5 - Remove these properties _lastLogEventInfo.Properties.Remove("CallerMemberName"); _lastLogEventInfo.Properties.Remove("CallerLineNumber"); _lastLogEventInfo.Properties.Remove("CallerFilePath"); Assert.Equal(expected.Properties, _lastLogEventInfo.Properties); Assert.Equal(expected.LoggerName, _lastLogEventInfo.LoggerName); Assert.Equal(expected.Level, _lastLogEventInfo.Level); Assert.Equal(expected.Exception, _lastLogEventInfo.Exception); Assert.Equal(expected.FormatProvider, _lastLogEventInfo.FormatProvider); } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2009 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; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; #if NETFX_CORE using MarkerMetro.Unity.WinLegacy.Plugin.Collections; #endif #if NETFX_CORE using MarkerMetro.Unity.WinLegacy.Reflection; #endif namespace Pathfinding.Serialization.JsonFx { /// <summary> /// Reader for consuming JSON data /// </summary> public class JsonReader { #region Constants internal const string LiteralFalse = "false"; internal const string LiteralTrue = "true"; internal const string LiteralNull = "null"; internal const string LiteralUndefined = "undefined"; internal const string LiteralNotANumber = "NaN"; internal const string LiteralPositiveInfinity = "Infinity"; internal const string LiteralNegativeInfinity = "-Infinity"; internal const char OperatorNegate = '-'; internal const char OperatorUnaryPlus = '+'; internal const char OperatorArrayStart = '['; internal const char OperatorArrayEnd = ']'; internal const char OperatorObjectStart = '{'; internal const char OperatorObjectEnd = '}'; internal const char OperatorStringDelim = '"'; internal const char OperatorStringDelimAlt = '\''; internal const char OperatorValueDelim = ','; internal const char OperatorNameDelim = ':'; internal const char OperatorCharEscape = '\\'; private const string CommentStart = "/*"; private const string CommentEnd = "*/"; private const string CommentLine = "//"; private const string LineEndings = "\r\n"; internal const string TypeGenericIDictionary = "System.Collections.Generic.IDictionary`2"; private const string ErrorUnrecognizedToken = "Illegal JSON sequence."; private const string ErrorUnterminatedComment = "Unterminated comment block."; private const string ErrorUnterminatedObject = "Unterminated JSON object."; private const string ErrorUnterminatedArray = "Unterminated JSON array."; private const string ErrorUnterminatedString = "Unterminated JSON string."; private const string ErrorIllegalNumber = "Illegal JSON number."; private const string ErrorExpectedString = "Expected JSON string."; private const string ErrorExpectedObject = "Expected JSON object."; private const string ErrorExpectedArray = "Expected JSON array."; private const string ErrorExpectedPropertyName = "Expected JSON object property name."; private const string ErrorExpectedPropertyNameDelim = "Expected JSON object property name delimiter."; private const string ErrorGenericIDictionary = "Types which implement Generic IDictionary<TKey, TValue> also need to implement IDictionary to be deserialized. ({0})"; private const string ErrorGenericIDictionaryKeys = "Types which implement Generic IDictionary<TKey, TValue> need to have string keys to be deserialized. ({0})"; #endregion Constants #region Fields private readonly JsonReaderSettings Settings = new JsonReaderSettings(); private readonly string Source = null; private readonly int SourceLength = 0; private int index; /** List of previously deserialized objects. * Used for reference cycle handling. */ private readonly List<object> previouslyDeserialized = new List<object>(); /** Cache ArrayLists. Otherwise every new deseriaization of an array wil allocate * a new ArrayList. */ private readonly Stack<ArrayList> jsArrays = new Stack<ArrayList>(); #endregion Fields #region Init /// <summary> /// Ctor /// </summary> /// <param name="input">TextReader containing source</param> public JsonReader(TextReader input) : this(input, new JsonReaderSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="input">TextReader containing source</param> /// <param name="settings">JsonReaderSettings</param> public JsonReader(TextReader input, JsonReaderSettings settings) { this.Settings = settings; this.Source = input.ReadToEnd(); this.SourceLength = this.Source.Length; } /// <summary> /// Ctor /// </summary> /// <param name="input">Stream containing source</param> public JsonReader(Stream input) : this(input, new JsonReaderSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="input">Stream containing source</param> /// <param name="settings">JsonReaderSettings</param> public JsonReader(Stream input, JsonReaderSettings settings) { this.Settings = settings; using (StreamReader reader = new StreamReader(input, true)) { this.Source = reader.ReadToEnd(); } this.SourceLength = this.Source.Length; } /// <summary> /// Ctor /// </summary> /// <param name="input">string containing source</param> public JsonReader(string input) : this(input, new JsonReaderSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="input">string containing source</param> /// <param name="settings">JsonReaderSettings</param> public JsonReader(string input, JsonReaderSettings settings) { this.Settings = settings; this.Source = input; this.SourceLength = this.Source.Length; } /// <summary> /// Ctor /// </summary> /// <param name="input">StringBuilder containing source</param> public JsonReader(StringBuilder input) : this(input, new JsonReaderSettings()) { } /// <summary> /// Ctor /// </summary> /// <param name="input">StringBuilder containing source</param> /// <param name="settings">JsonReaderSettings</param> public JsonReader(StringBuilder input, JsonReaderSettings settings) { this.Settings = settings; this.Source = input.ToString(); this.SourceLength = this.Source.Length; } #endregion Init #region Properties /// <summary> /// Gets and sets if ValueTypes can accept values of null /// </summary> /// <remarks> /// Only affects deserialization: if a ValueType is assigned the /// value of null, it will receive the value default(TheType). /// Setting this to false, throws an exception if null is /// specified for a ValueType member. /// </remarks> [Obsolete("This has been deprecated in favor of JsonReaderSettings object")] public bool AllowNullValueTypes { get { return this.Settings.AllowNullValueTypes; } set { this.Settings.AllowNullValueTypes = value; } } /// <summary> /// Gets and sets the property name used for type hinting. /// </summary> [Obsolete("This has been deprecated in favor of JsonReaderSettings object")] public string TypeHintName { get { return this.Settings.TypeHintName; } set { this.Settings.TypeHintName = value; } } #endregion Properties #region Parsing Methods /// <summary> /// Convert from JSON string to Object graph /// </summary> /// <returns></returns> public object Deserialize() { return this.Deserialize((Type)null); } /// <summary> /// Convert from JSON string to Object graph /// </summary> /// <returns></returns> public object Deserialize(int start) { this.index = start; return this.Deserialize((Type)null); } /// <summary> /// Convert from JSON string to Object graph of specific Type /// </summary> /// <param name="type"></param> /// <returns></returns> public object Deserialize(Type type) { // should this run through a preliminary test here? return this.Read(type, false); } /* /// <summary> /// Convert from JSON string to Object graph of specific Type /// </summary> /// <param name="type"></param> /// <returns></returns> public T Deserialize<T>() { // should this run through a preliminary test here? return (T)this.Read(typeof(T), false); }*/ /// <summary> /// Convert from JSON string to Object graph of specific Type /// </summary> /// <param name="type"></param> /// <returns></returns> public object Deserialize(int start, Type type) { this.index = start; // should this run through a preliminary test here? return this.Read(type, false); } /// <summary> /// Convert from JSON string to Object graph of specific Type /// </summary> /// <param name="type"></param> /// <returns></returns> /*public T Deserialize<T>(int start) { this.index = start; // should this run through a preliminary test here? return (T)this.Read(typeof(T), false); }*/ private object Read(Type expectedType, bool typeIsHint) { if (expectedType == typeof(Object)) { expectedType = null; } JsonToken token = this.Tokenize(); #if NETFX_CORE if (expectedType != null && !expectedType.IsPrimitive()) { #else if (expectedType != null && !expectedType.IsPrimitive) { #endif JsonConverter converter = this.Settings.GetConverter(expectedType); if (converter != null) { object val; try { val = Read(typeof(Dictionary<string,object>),false); Dictionary<string,object> dict = val as Dictionary<string,object>; if (dict == null) return null; object obj = converter.Read (this,expectedType,dict); return obj; } catch (JsonTypeCoercionException e) { #if !NETFX_CORE Console.WriteLine ("Could not cast to dictionary for converter processing. Ignoring field.\n"+e); #else System.Diagnostics.Debug.WriteLine("Could not cast to dictionary for converter processing. Ignoring field.\n"+e); #endif } return null; } } switch (token) { case JsonToken.ObjectStart: { return this.ReadObject(typeIsHint ? null : expectedType); } case JsonToken.ArrayStart: { return this.ReadArray(typeIsHint ? null : expectedType); } case JsonToken.String: { return this.ReadString(typeIsHint ? null : expectedType); } case JsonToken.Number: { return this.ReadNumber(typeIsHint ? null : expectedType); } case JsonToken.False: { this.index += JsonReader.LiteralFalse.Length; return false; } case JsonToken.True: { this.index += JsonReader.LiteralTrue.Length; return true; } case JsonToken.Null: { this.index += JsonReader.LiteralNull.Length; return null; } case JsonToken.NaN: { this.index += JsonReader.LiteralNotANumber.Length; return Double.NaN; } case JsonToken.PositiveInfinity: { this.index += JsonReader.LiteralPositiveInfinity.Length; return Double.PositiveInfinity; } case JsonToken.NegativeInfinity: { this.index += JsonReader.LiteralNegativeInfinity.Length; return Double.NegativeInfinity; } case JsonToken.Undefined: { this.index += JsonReader.LiteralUndefined.Length; return null; } case JsonToken.End: default: { return null; } } } // IZ: Added public void PopulateObject(object obj) { object other = obj; PopulateObject(ref other); if(!object.ReferenceEquals(other, obj)) throw new InvalidOperationException("Object reference has changed, please use ref call, which you can't do because it is private :)"); } /** Populates an object with serialized data. * Note that in case the object has been loaded before (another reference to it) * the passed object will be changed to the previously loaded object (this only applies * if you have enabled CyclicReferenceHandling in the settings). */ private void PopulateObject (ref object obj) { Type objectType = obj.GetType(); Dictionary<string, MemberInfo> memberMap = this.Settings.Coercion.GetMemberMap(objectType); Type genericDictionaryType = null; if (memberMap == null) { genericDictionaryType = GetGenericDictionaryType(objectType); } PopulateObject (ref obj, objectType, memberMap, genericDictionaryType); } private object ReadObject (Type objectType) { Type genericDictionaryType = null; Dictionary<string, MemberInfo> memberMap = null; Object result; if (objectType != null) { result = this.Settings.Coercion.InstantiateObject(objectType, out memberMap); Debug.WriteLine(string.Format("Adding: {0} ({1})", result, previouslyDeserialized.Count)); previouslyDeserialized.Add (result); if (memberMap == null) { genericDictionaryType = GetGenericDictionaryType(objectType); } } else { result = new Dictionary<String, Object>(); } object prev = result; PopulateObject (ref result, objectType, memberMap, genericDictionaryType); if (prev != result) { // If prev != result, then the PopulateObject method has used a previously loaded object // then we should not add the object to the list of deserialized objects since it // already is there (the correct version of it, that is) Debug.WriteLine(string.Format("Removing: {0} ({1})", result, previouslyDeserialized.Count)); previouslyDeserialized.RemoveAt(previouslyDeserialized.Count-1); } return result; } private Type GetGenericDictionaryType (Type objectType) { // this allows specific IDictionary<string, T> to deserialize T Type genericDictionary = objectType.GetInterface(JsonReader.TypeGenericIDictionary); if (genericDictionary != null) { Type[] genericArgs = genericDictionary.GetGenericArguments(); if (genericArgs.Length == 2) { if (genericArgs[0] != typeof(String)) { throw new JsonDeserializationException( String.Format(JsonReader.ErrorGenericIDictionaryKeys, objectType), this.index); } if (genericArgs[1] != typeof(Object)) { return genericArgs[1]; } } } return null; } private void PopulateObject (ref object result, Type objectType, Dictionary<string, MemberInfo> memberMap, Type genericDictionaryType) { if (this.Source[this.index] != JsonReader.OperatorObjectStart) { throw new JsonDeserializationException(JsonReader.ErrorExpectedObject, this.index); } IDictionary idict = result as IDictionary; if (idict == null && objectType.GetInterface(JsonReader.TypeGenericIDictionary) != null ) { throw new JsonDeserializationException( String.Format(JsonReader.ErrorGenericIDictionary, objectType), this.index); } JsonToken token; do { Type memberType; MemberInfo memberInfo; // consume opening brace or delim this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index); } // get next token token = this.Tokenize(this.Settings.AllowUnquotedObjectKeys); if (token == JsonToken.ObjectEnd) { break; } if (token != JsonToken.String && token != JsonToken.UnquotedName) { throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyName, this.index); } // parse object member value string memberName = (token == JsonToken.String) ? (String)this.ReadString(null) : this.ReadUnquotedKey(); // if (genericDictionaryType == null && memberMap != null) { // determine the type of the property/field memberType = TypeCoercionUtility.GetMemberInfo(memberMap, memberName, out memberInfo); } else { memberType = genericDictionaryType; memberInfo = null; } // get next token token = this.Tokenize(); if (token != JsonToken.NameDelim) { throw new JsonDeserializationException(JsonReader.ErrorExpectedPropertyNameDelim, this.index); } // consume delim this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index); } object value; // Reference to previously deserialized value if (Settings.HandleCyclicReferences && memberName == "@ref") { // parse object member value int refId = (int)this.Read(typeof(int), false); // Change result object to the one previously deserialized result = previouslyDeserialized[refId]; // get next token // this will probably be the end of the object token = this.Tokenize(); continue; } else { // Normal serialized value // parse object member value value = this.Read(memberType, false); } if (idict != null) { if (objectType == null && this.Settings.IsTypeHintName(memberName)) { result = this.Settings.Coercion.ProcessTypeHint(idict, value as string, out objectType, out memberMap); } else { idict[memberName] = value; } } else { this.Settings.Coercion.SetMemberValue(result, memberType, memberInfo, value); } // get next token token = this.Tokenize(); } while (token == JsonToken.ValueDelim); if (token != JsonToken.ObjectEnd) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedObject, this.index); } // consume closing brace this.index++; //return result; } private IEnumerable ReadArray(Type arrayType) { if (this.Source[this.index] != JsonReader.OperatorArrayStart) { throw new JsonDeserializationException(JsonReader.ErrorExpectedArray, this.index); } bool isArrayItemTypeSet = (arrayType != null); bool isArrayTypeAHint = !isArrayItemTypeSet; Type arrayItemType = null; if (isArrayItemTypeSet) { if (arrayType.HasElementType) { arrayItemType = arrayType.GetElementType(); } #if NETFX_CORE else if (arrayType.IsGenericType()) #else else if (arrayType.IsGenericType) #endif { Type[] generics = arrayType.GetGenericArguments(); if (generics.Length == 1) { // could use the first or last, but this more correct arrayItemType = generics[0]; } } } // using ArrayList since has .ToArray(Type) method // cannot create generic list at runtime ArrayList jsArray = jsArrays.Count > 0 ? jsArrays.Pop() : new ArrayList(); jsArray.Clear(); JsonToken token; do { // consume opening bracket or delim this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index); } // get next token token = this.Tokenize(); if (token == JsonToken.ArrayEnd) { break; } // parse array item object value = this.Read(arrayItemType, isArrayTypeAHint); jsArray.Add(value); // establish if array is of common type if (value == null) { #if NETFX_CORE if (arrayItemType != null && arrayItemType.IsValueType()) #else if (arrayItemType != null && arrayItemType.IsValueType) #endif { // use plain object to hold null arrayItemType = null; } isArrayItemTypeSet = true; } else if (arrayItemType != null && !arrayItemType.IsAssignableFrom(value.GetType())) { if (value.GetType().IsAssignableFrom(arrayItemType)) { // attempt to use the more general type arrayItemType = value.GetType(); } else { // use plain object to hold value arrayItemType = null; isArrayItemTypeSet = true; } } else if (!isArrayItemTypeSet) { // try out a hint type // if hasn't been set before arrayItemType = value.GetType(); isArrayItemTypeSet = true; } // get next token token = this.Tokenize(); } while (token == JsonToken.ValueDelim); if (token != JsonToken.ArrayEnd) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedArray, this.index); } // consume closing bracket this.index++; // TODO: optimize to reduce number of conversions on lists jsArrays.Push (jsArray); if (arrayItemType != null && arrayItemType != typeof(object)) { // if all items are of same type then convert to array of that type return jsArray.ToArray(arrayItemType); } // convert to an object array for consistency return jsArray.ToArray(); } /// <summary> /// Reads an unquoted JSON object key /// </summary> /// <returns></returns> private string ReadUnquotedKey() { int start = this.index; do { // continue scanning until reach a valid token this.index++; } while (this.Tokenize(true) == JsonToken.UnquotedName); return this.Source.Substring(start, this.index - start); } /// <summary> /// Reads a JSON string /// </summary> /// <param name="expectedType"></param> /// <returns>string or value which is represented as a string in JSON</returns> private object ReadString(Type expectedType) { if (this.Source[this.index] != JsonReader.OperatorStringDelim && this.Source[this.index] != JsonReader.OperatorStringDelimAlt) { throw new JsonDeserializationException(JsonReader.ErrorExpectedString, this.index); } char startStringDelim = this.Source[this.index]; // consume opening quote this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index); } int start = this.index; StringBuilder builder = new StringBuilder(); while (this.Source[this.index] != startStringDelim) { if (this.Source[this.index] == JsonReader.OperatorCharEscape) { // copy chunk before decoding builder.Append(this.Source, start, this.index - start); // consume escape char this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index); } // decode switch (this.Source[this.index]) { case '0': { // don't allow NULL char '\0' // causes CStrings to terminate break; } case 'b': { // backspace builder.Append('\b'); break; } case 'f': { // formfeed builder.Append('\f'); break; } case 'n': { // newline builder.Append('\n'); break; } case 'r': { // carriage return builder.Append('\r'); break; } case 't': { // tab builder.Append('\t'); break; } case 'u': { // Unicode escape sequence // e.g. Copyright: "\u00A9" // unicode ordinal int utf16; if (this.index+4 < this.SourceLength && Int32.TryParse( this.Source.Substring(this.index+1, 4), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out utf16)) { builder.Append(Char.ConvertFromUtf32(utf16)); this.index += 4; } else { // using FireFox style recovery, if not a valid hex // escape sequence then treat as single escaped 'u' // followed by rest of string builder.Append(this.Source[this.index]); } break; } default: { builder.Append(this.Source[this.index]); break; } } this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index); } start = this.index; } else { // next char this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedString, this.index); } } } // copy rest of string builder.Append(this.Source, start, this.index-start); // consume closing quote this.index++; if (expectedType != null && expectedType != typeof(String)) { return this.Settings.Coercion.CoerceType(expectedType, builder.ToString()); } return builder.ToString(); } private object ReadNumber(Type expectedType) { bool hasDecimal = false; bool hasExponent = false; int start = this.index; int precision = 0; int exponent = 0; // optional minus part if (this.Source[this.index] == JsonReader.OperatorNegate) { // consume sign this.index++; if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index])) throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index); } // integer part while ((this.index < this.SourceLength) && Char.IsDigit(this.Source[this.index])) { // consume digit this.index++; } // optional decimal part if ((this.index < this.SourceLength) && (this.Source[this.index] == '.')) { hasDecimal = true; // consume decimal this.index++; if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index])) { throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index); } // fraction part while (this.index < this.SourceLength && Char.IsDigit(this.Source[this.index])) { // consume digit this.index++; } } // note the number of significant digits precision = this.index-start - (hasDecimal ? 1 : 0); // optional exponent part if (this.index < this.SourceLength && (this.Source[this.index] == 'e' || this.Source[this.index] == 'E')) { hasExponent = true; // consume 'e' this.index++; if (this.index >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index); } int expStart = this.index; // optional minus/plus part if (this.Source[this.index] == JsonReader.OperatorNegate || this.Source[this.index] == JsonReader.OperatorUnaryPlus) { // consume sign this.index++; if (this.index >= this.SourceLength || !Char.IsDigit(this.Source[this.index])) { throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index); } } else { if (!Char.IsDigit(this.Source[this.index])) { throw new JsonDeserializationException(JsonReader.ErrorIllegalNumber, this.index); } } // exp part while (this.index < this.SourceLength && Char.IsDigit(this.Source[this.index])) { // consume digit this.index++; } Int32.TryParse(this.Source.Substring(expStart, this.index-expStart), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out exponent); } // at this point, we have the full number string and know its characteristics string numberString = this.Source.Substring(start, this.index - start); if (!hasDecimal && !hasExponent && precision < 19) { // is Integer value // parse as most flexible decimal number = Decimal.Parse( numberString, NumberStyles.Integer, NumberFormatInfo.InvariantInfo); if (expectedType != null) { return this.Settings.Coercion.CoerceType(expectedType, number); } if (number >= Int32.MinValue && number <= Int32.MaxValue) { // use most common return (int)number; } if (number >= Int64.MinValue && number <= Int64.MaxValue) { // use more flexible return (long)number; } // use most flexible return number; } else { // is Floating Point value if (expectedType == typeof(Decimal)) { // special case since Double does not convert to Decimal return Decimal.Parse( numberString, NumberStyles.Float, NumberFormatInfo.InvariantInfo); } // use native EcmaScript number (IEEE 754) double number = Double.Parse( numberString, NumberStyles.Float, NumberFormatInfo.InvariantInfo); if (expectedType != null) { return this.Settings.Coercion.CoerceType(expectedType, number); } return number; } } #endregion Parsing Methods #region Static Methods /// <summary> /// A fast method for deserializing an object from JSON /// </summary> /// <param name="value"></param> /// <returns></returns> public static object Deserialize(string value) { return JsonReader.Deserialize(value, 0, null); } /// <summary> /// A fast method for deserializing an object from JSON /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public static T Deserialize<T>(string value) { return (T)JsonReader.Deserialize(value, 0, typeof(T)); } /// <summary> /// A fast method for deserializing an object from JSON /// </summary> /// <param name="value"></param> /// <param name="start"></param> /// <returns></returns> public static object Deserialize(string value, int start) { return JsonReader.Deserialize(value, start, null); } /// <summary> /// A fast method for deserializing an object from JSON /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <param name="start"></param> /// <returns></returns> public static T Deserialize<T>(string value, int start) { return (T)JsonReader.Deserialize(value, start, typeof(T)); } /// <summary> /// A fast method for deserializing an object from JSON /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> public static object Deserialize(string value, Type type) { return JsonReader.Deserialize(value, 0, type); } /// <summary> /// A fast method for deserializing an object from JSON /// </summary> /// <param name="value">source text</param> /// <param name="start">starting position</param> /// <param name="type">expected type</param> /// <returns></returns> public static object Deserialize(string value, int start, Type type) { return (new JsonReader(value)).Deserialize(start, type); } #endregion Static Methods #region Tokenizing Methods private JsonToken Tokenize() { // unquoted object keys are only allowed in object properties return this.Tokenize(false); } private JsonToken Tokenize(bool allowUnquotedString) { if (this.index >= this.SourceLength) { return JsonToken.End; } // skip whitespace while (Char.IsWhiteSpace(this.Source[this.index])) { this.index++; if (this.index >= this.SourceLength) { return JsonToken.End; } } #region Skip Comments // skip block and line comments if (this.Source[this.index] == JsonReader.CommentStart[0]) { if (this.index+1 >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index); } // skip over first char of comment start this.index++; bool isBlockComment = false; if (this.Source[this.index] == JsonReader.CommentStart[1]) { isBlockComment = true; } else if (this.Source[this.index] != JsonReader.CommentLine[1]) { throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index); } // skip over second char of comment start this.index++; if (isBlockComment) { // store index for unterminated case int commentStart = this.index-2; if (this.index+1 >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedComment, commentStart); } // skip over everything until reach block comment ending while (this.Source[this.index] != JsonReader.CommentEnd[0] || this.Source[this.index+1] != JsonReader.CommentEnd[1]) { this.index++; if (this.index+1 >= this.SourceLength) { throw new JsonDeserializationException(JsonReader.ErrorUnterminatedComment, commentStart); } } // skip block comment end token this.index += 2; if (this.index >= this.SourceLength) { return JsonToken.End; } } else { // skip over everything until reach line ending while (JsonReader.LineEndings.IndexOf(this.Source[this.index]) < 0) { this.index++; if (this.index >= this.SourceLength) { return JsonToken.End; } } } // skip whitespace again while (Char.IsWhiteSpace(this.Source[this.index])) { this.index++; if (this.index >= this.SourceLength) { return JsonToken.End; } } } #endregion Skip Comments // consume positive signing (as is extraneous) if (this.Source[this.index] == JsonReader.OperatorUnaryPlus) { this.index++; if (this.index >= this.SourceLength) { return JsonToken.End; } } switch (this.Source[this.index]) { case JsonReader.OperatorArrayStart: { return JsonToken.ArrayStart; } case JsonReader.OperatorArrayEnd: { return JsonToken.ArrayEnd; } case JsonReader.OperatorObjectStart: { return JsonToken.ObjectStart; } case JsonReader.OperatorObjectEnd: { return JsonToken.ObjectEnd; } case JsonReader.OperatorStringDelim: case JsonReader.OperatorStringDelimAlt: { return JsonToken.String; } case JsonReader.OperatorValueDelim: { return JsonToken.ValueDelim; } case JsonReader.OperatorNameDelim: { return JsonToken.NameDelim; } default: { break; } } // number if (Char.IsDigit(this.Source[this.index]) || ((this.Source[this.index] == JsonReader.OperatorNegate) && (this.index+1 < this.SourceLength) && Char.IsDigit(this.Source[this.index+1]))) { return JsonToken.Number; } // "false" literal if (this.MatchLiteral(JsonReader.LiteralFalse)) { return JsonToken.False; } // "true" literal if (this.MatchLiteral(JsonReader.LiteralTrue)) { return JsonToken.True; } // "null" literal if (this.MatchLiteral(JsonReader.LiteralNull)) { return JsonToken.Null; } // "NaN" literal if (this.MatchLiteral(JsonReader.LiteralNotANumber)) { return JsonToken.NaN; } // "Infinity" literal if (this.MatchLiteral(JsonReader.LiteralPositiveInfinity)) { return JsonToken.PositiveInfinity; } // "-Infinity" literal if (this.MatchLiteral(JsonReader.LiteralNegativeInfinity)) { return JsonToken.NegativeInfinity; } // "undefined" literal if (this.MatchLiteral(JsonReader.LiteralUndefined)) { return JsonToken.Undefined; } if (allowUnquotedString) { return JsonToken.UnquotedName; } throw new JsonDeserializationException(JsonReader.ErrorUnrecognizedToken, this.index); } /// <summary> /// Determines if the next token is the given literal /// </summary> /// <param name="literal"></param> /// <returns></returns> private bool MatchLiteral(string literal) { int literalLength = literal.Length; for (int i=0, j=this.index; i<literalLength && j<this.SourceLength; i++, j++) { if (literal[i] != this.Source[j]) { return false; } } return true; } #endregion Tokenizing Methods #region Type Methods /// <summary> /// Converts a value into the specified type using type inference. /// </summary> /// <typeparam name="T">target type</typeparam> /// <param name="value">value to convert</param> /// <param name="typeToMatch">example object to get the type from</param> /// <returns></returns> public static T CoerceType<T>(object value, T typeToMatch) { return (T)new TypeCoercionUtility().CoerceType(typeof(T), value); } /// <summary> /// Converts a value into the specified type. /// </summary> /// <typeparam name="T">target type</typeparam> /// <param name="value">value to convert</param> /// <returns></returns> public static T CoerceType<T>(object value) { return (T)new TypeCoercionUtility().CoerceType(typeof(T), value); } /// <summary> /// Converts a value into the specified type. /// </summary> /// <param name="targetType">target type</param> /// <param name="value">value to convert</param> /// <returns></returns> public static object CoerceType(Type targetType, object value) { return new TypeCoercionUtility().CoerceType(targetType, value); } #endregion Type Methods } }
// // PlayerEngineService.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2006-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.IO; using System.Collections.Generic; using System.Reflection; using Mono.Unix; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.Streaming; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Query; using Banshee.Metadata; using Banshee.Configuration; using Banshee.Collection; using Banshee.Equalizer; using Banshee.Collection.Database; namespace Banshee.MediaEngine { public delegate bool TrackInterceptHandler (TrackInfo track); public class PlayerEngineService : IInitializeService, IDelayedInitializeService, IRequiredService, IPlayerEngineService, IDisposable { private List<PlayerEngine> engines = new List<PlayerEngine> (); private PlayerEngine active_engine; private PlayerEngine default_engine; private PlayerEngine pending_engine; private object pending_playback_for_not_ready; private bool pending_playback_for_not_ready_play; private TrackInfo synthesized_contacting_track; private string preferred_engine_id = null; public event EventHandler PlayWhenIdleRequest; public event TrackInterceptHandler TrackIntercept; public event Action<PlayerEngine> EngineBeforeInitialize; public event Action<PlayerEngine> EngineAfterInitialize; private event DBusPlayerEventHandler dbus_event_changed; event DBusPlayerEventHandler IPlayerEngineService.EventChanged { add { dbus_event_changed += value; } remove { dbus_event_changed -= value; } } private event DBusPlayerStateHandler dbus_state_changed; event DBusPlayerStateHandler IPlayerEngineService.StateChanged { add { dbus_state_changed += value; } remove { dbus_state_changed -= value; } } public PlayerEngineService () { } void IInitializeService.Initialize () { preferred_engine_id = EngineSchema.Get(); if (default_engine == null && engines.Count > 0) { default_engine = engines[0]; } foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/MediaEngine/PlayerEngine")) { LoadEngine (node); } if (default_engine != null) { active_engine = default_engine; Log.Debug (Catalog.GetString ("Default player engine"), active_engine.Name); } else { default_engine = active_engine; } if (default_engine == null || active_engine == null || engines == null || engines.Count == 0) { Log.Warning (Catalog.GetString ( "No player engines were found. Please ensure Banshee has been cleanly installed."), "Using the featureless NullPlayerEngine."); PlayerEngine null_engine = new NullPlayerEngine (); LoadEngine (null_engine); active_engine = null_engine; default_engine = null_engine; } MetadataService.Instance.HaveResult += OnMetadataServiceHaveResult; TrackInfo.IsPlayingMethod = track => IsPlaying (track) && track.CacheModelId == CurrentTrack.CacheModelId && (track.CacheEntryId == null || track.CacheEntryId.Equals (CurrentTrack.CacheEntryId)); } private void InitializeEngine (PlayerEngine engine) { var handler = EngineBeforeInitialize; if (handler != null) { handler (engine); } engine.Initialize (); engine.IsInitialized = true; handler = EngineAfterInitialize; if (handler != null) { handler (engine); } } void IDelayedInitializeService.DelayedInitialize () { foreach (var engine in Engines) { if (engine.DelayedInitialize) { InitializeEngine (engine); } } } private void LoadEngine (TypeExtensionNode node) { LoadEngine ((PlayerEngine) node.CreateInstance (typeof (PlayerEngine))); } private void LoadEngine (PlayerEngine engine) { if (!engine.DelayedInitialize) { InitializeEngine (engine); } engine.EventChanged += OnEngineEventChanged; if (engine.Id == preferred_engine_id) { DefaultEngine = engine; } else { if (active_engine == null) { active_engine = engine; } engines.Add (engine); } } public void Dispose () { MetadataService.Instance.HaveResult -= OnMetadataServiceHaveResult; foreach (PlayerEngine engine in engines) { engine.Dispose (); } active_engine = null; default_engine = null; pending_engine = null; preferred_engine_id = null; engines.Clear (); } private void OnMetadataServiceHaveResult (object o, MetadataLookupResultArgs args) { if (CurrentTrack != null && CurrentTrack.TrackEqual (args.Track as TrackInfo)) { foreach (StreamTag tag in args.ResultTags) { StreamTagger.TrackInfoMerge (CurrentTrack, tag); } OnEngineEventChanged (new PlayerEventArgs (PlayerEvent.TrackInfoUpdated)); } } private void HandleStateChange (PlayerEventStateChangeArgs args) { if (args.Current == PlayerState.Loaded && CurrentTrack != null) { MetadataService.Instance.Lookup (CurrentTrack); } else if (args.Current == PlayerState.Ready) { // Enable our preferred equalizer if it exists and was enabled last time. if (SupportsEqualizer) { EqualizerManager.Instance.Select (); } if (pending_playback_for_not_ready != null) { OpenCheck (pending_playback_for_not_ready, pending_playback_for_not_ready_play); pending_playback_for_not_ready = null; pending_playback_for_not_ready_play = false; } } DBusPlayerStateHandler dbus_handler = dbus_state_changed; if (dbus_handler != null) { dbus_handler (args.Current.ToString ().ToLower ()); } } private void OnEngineEventChanged (PlayerEventArgs args) { if (CurrentTrack != null) { if (args.Event == PlayerEvent.Error && CurrentTrack.PlaybackError == StreamPlaybackError.None) { CurrentTrack.SavePlaybackError (StreamPlaybackError.Unknown); } else if (args.Event == PlayerEvent.Iterate && CurrentTrack.PlaybackError != StreamPlaybackError.None) { CurrentTrack.SavePlaybackError (StreamPlaybackError.None); } } if (args.Event == PlayerEvent.StartOfStream) { incremented_last_played = false; } else if (args.Event == PlayerEvent.EndOfStream) { IncrementLastPlayed (); } RaiseEvent (args); // Do not raise iterate across DBus to avoid so many calls; // DBus clients should do their own iterating and // event/state checking locally if (args.Event == PlayerEvent.Iterate) { return; } DBusPlayerEventHandler dbus_handler = dbus_event_changed; if (dbus_handler != null) { dbus_handler (args.Event.ToString ().ToLower (), args is PlayerEventErrorArgs ? ((PlayerEventErrorArgs)args).Message : String.Empty, args is PlayerEventBufferingArgs ? ((PlayerEventBufferingArgs)args).Progress : 0 ); } } private void OnPlayWhenIdleRequest () { EventHandler handler = PlayWhenIdleRequest; if (handler != null) { handler (this, EventArgs.Empty); } } private bool OnTrackIntercept (TrackInfo track) { TrackInterceptHandler handler = TrackIntercept; if (handler == null) { return false; } bool handled = false; foreach (TrackInterceptHandler single_handler in handler.GetInvocationList ()) { handled |= single_handler (track); } return handled; } public void Open (TrackInfo track) { OpenPlay (track, false); } public void Open (SafeUri uri) { // Check if the uri exists if (uri == null || !File.Exists (uri.AbsolutePath)) { return; } bool found = false; if (ServiceManager.DbConnection != null) { // Try to find uri in the library long track_id = DatabaseTrackInfo.GetTrackIdForUri (uri); if (track_id > 0) { DatabaseTrackInfo track_db = DatabaseTrackInfo.Provider.FetchSingle (track_id); found = true; Open (track_db); } } if (!found) { // Not in the library, get info from the file TrackInfo track = new TrackInfo (); using (var file = StreamTagger.ProcessUri (uri)) { StreamTagger.TrackInfoMerge (track, file, false); } Open (track); } } void IPlayerEngineService.Open (string uri) { Open (new SafeUri (uri)); } public void SetNextTrack (TrackInfo track) { if (track != null && EnsureActiveEngineCanPlay (track.Uri)) { active_engine.SetNextTrack (track); } else { active_engine.SetNextTrack ((TrackInfo) null); } } public void SetNextTrack (SafeUri uri) { if (EnsureActiveEngineCanPlay (uri)) { active_engine.SetNextTrack (uri); } else { active_engine.SetNextTrack ((SafeUri) null); } } private bool EnsureActiveEngineCanPlay (SafeUri uri) { if (uri == null) { // No engine can play the null URI. return false; } if (active_engine != FindSupportingEngine (uri)) { if (active_engine.CurrentState == PlayerState.Playing) { // If we're currently playing then we can't switch engines now. // We can't ensure the active engine can play this URI. return false; } else { // If we're not playing, we can switch the active engine to // something that will play this URI. SwitchToEngine (FindSupportingEngine (uri)); CheckPending (); return true; } } return true; } public void OpenPlay (TrackInfo track) { OpenPlay (track, true); } private void OpenPlay (TrackInfo track, bool play) { if (track == null || !track.CanPlay || OnTrackIntercept (track)) { return; } try { OpenCheck (track, play); } catch (Exception e) { Log.Error (e); Log.Error (Catalog.GetString ("Problem with Player Engine"), e.Message, true); Close (); ActiveEngine = default_engine; } } private void OpenCheck (object o, bool play) { if (CurrentState == PlayerState.NotReady) { pending_playback_for_not_ready = o; pending_playback_for_not_ready_play = play; return; } SafeUri uri = null; TrackInfo track = null; if (o is SafeUri) { uri = (SafeUri)o; } else if (o is TrackInfo) { track = (TrackInfo)o; uri = track.Uri; } else { return; } if (track != null && (track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) { RaiseEvent (new PlayerEventArgs (PlayerEvent.EndOfStream)); return; } PlayerEngine supportingEngine = FindSupportingEngine (uri); SwitchToEngine (supportingEngine); CheckPending (); if (track != null) { active_engine.Open (track); } else if (uri != null) { active_engine.Open (uri); } if (play) { active_engine.Play (); } } public void IncrementLastPlayed () { // If Length <= 0 assume 100% completion. IncrementLastPlayed (active_engine.Length <= 0 ? 1.0 : (double)active_engine.Position / active_engine.Length); } private bool incremented_last_played = true; public void IncrementLastPlayed (double completed) { if (!incremented_last_played && CurrentTrack != null && CurrentTrack.PlaybackError == StreamPlaybackError.None) { CurrentTrack.OnPlaybackFinished (completed); incremented_last_played = true; } } private PlayerEngine FindSupportingEngine (SafeUri uri) { foreach (PlayerEngine engine in engines) { foreach (string extension in engine.ExplicitDecoderCapabilities) { if (!uri.AbsoluteUri.EndsWith (extension)) { continue; } return engine; } } foreach (PlayerEngine engine in engines) { foreach (string scheme in engine.SourceCapabilities) { bool supported = scheme == uri.Scheme; if (supported) { return engine; } } } // If none of our engines support this URI, return the currently active one. // There doesn't seem to be anything better to do. return active_engine; } private bool SwitchToEngine (PlayerEngine switchTo) { if (active_engine != switchTo) { Close (); pending_engine = switchTo; Log.DebugFormat ("Switching engine to: {0}", switchTo.GetType ()); return true; } return false; } public void Close () { Close (false); } public void Close (bool fullShutdown) { IncrementLastPlayed (); active_engine.Close (fullShutdown); } public void Play () { if (CurrentState == PlayerState.Idle) { OnPlayWhenIdleRequest (); } else { active_engine.Play (); } } public void Pause () { if (!CanPause) { Close (); } else { active_engine.Pause (); } } public void RestartCurrentTrack () { var track = CurrentTrack; if (track != null) { // Don't process the track as played through IncrementLastPlayed, just play it again active_engine.Close (false); OpenPlay (track); } } // For use by RadioTrackInfo // TODO remove this method once RadioTrackInfo playlist downloading/parsing logic moved here? internal void StartSynthesizeContacting (TrackInfo track) { //OnStateChanged (PlayerState.Contacting); RaiseEvent (new PlayerEventStateChangeArgs (CurrentState, PlayerState.Contacting)); synthesized_contacting_track = track; } internal void EndSynthesizeContacting (TrackInfo track, bool idle) { if (track == synthesized_contacting_track) { synthesized_contacting_track = null; if (idle) { RaiseEvent (new PlayerEventStateChangeArgs (PlayerState.Contacting, PlayerState.Idle)); } } } public void TogglePlaying () { if (IsPlaying () && CurrentState != PlayerState.Paused) { Pause (); } else if (CurrentState != PlayerState.NotReady) { Play (); } } public void Seek (uint position, bool accurate_seek) { active_engine.Seek (position, accurate_seek); } public void Seek (uint position) { Seek (position, false); } public void VideoExpose (IntPtr displayContext, bool direct) { active_engine.VideoExpose (displayContext, direct); } public void VideoWindowRealize (IntPtr displayContext) { active_engine.VideoWindowRealize (displayContext); } public IntPtr VideoDisplayContext { set { active_engine.VideoDisplayContext = value; } get { return active_engine.VideoDisplayContext; } } public void TrackInfoUpdated () { active_engine.TrackInfoUpdated (); } public bool IsPlaying (TrackInfo track) { return IsPlaying () && track != null && track.TrackEqual (CurrentTrack); } public bool IsPlaying () { return CurrentState == PlayerState.Playing || CurrentState == PlayerState.Paused || CurrentState == PlayerState.Loaded || CurrentState == PlayerState.Loading || CurrentState == PlayerState.Contacting; } public string GetSubtitleDescription (int index) { return active_engine.GetSubtitleDescription (index); } public void NotifyMouseMove (double x, double y) { active_engine.NotifyMouseMove (x, y); } public void NotifyMouseButtonPressed (int button, double x, double y) { active_engine.NotifyMouseButtonPressed (button, x, y); } public void NotifyMouseButtonReleased (int button, double x, double y) { active_engine.NotifyMouseButtonReleased (button, x, y); } public void NavigateToLeftMenu () { active_engine.NavigateToLeftMenu (); } public void NavigateToRightMenu () { active_engine.NavigateToRightMenu (); } public void NavigateToUpMenu () { active_engine.NavigateToUpMenu (); } public void NavigateToDownMenu () { active_engine.NavigateToDownMenu (); } public void NavigateToMenu () { active_engine.NavigateToMenu (); } public void ActivateCurrentMenu () { active_engine.ActivateCurrentMenu (); } public void GoToNextChapter () { active_engine.GoToNextChapter (); } public void GoToPreviousChapter () { active_engine.GoToPreviousChapter (); } private void CheckPending () { if (pending_engine != null && pending_engine != active_engine) { if (active_engine.CurrentState == PlayerState.Idle) { Close (); } active_engine = pending_engine; pending_engine = null; } } public TrackInfo CurrentTrack { get { return active_engine == null ? null : active_engine.CurrentTrack ?? synthesized_contacting_track; } } private Dictionary<string, object> dbus_sucks; IDictionary<string, object> IPlayerEngineService.CurrentTrack { get { // FIXME: Managed DBus sucks - it explodes if you transport null // or even an empty dictionary (a{sv} in our case). Piece of shit. if (dbus_sucks == null) { dbus_sucks = new Dictionary<string, object> (); dbus_sucks.Add (String.Empty, String.Empty); } return CurrentTrack == null ? dbus_sucks : CurrentTrack.GenerateExportable (); } } public SafeUri CurrentSafeUri { get { return active_engine.CurrentUri; } } string IPlayerEngineService.CurrentUri { get { return CurrentSafeUri == null ? String.Empty : CurrentSafeUri.AbsoluteUri; } } public PlayerState CurrentState { get { if (active_engine == null) { return PlayerState.NotReady; } return synthesized_contacting_track != null ? PlayerState.Contacting : active_engine.CurrentState; } } string IPlayerEngineService.CurrentState { get { return CurrentState.ToString ().ToLower (); } } public PlayerState LastState { get { return active_engine.LastState; } } string IPlayerEngineService.LastState { get { return LastState.ToString ().ToLower (); } } public ushort Volume { get { return active_engine.Volume; } set { foreach (PlayerEngine engine in engines) { engine.Volume = value; } } } public uint Position { get { return active_engine.Position; } set { active_engine.Position = value; } } public byte Rating { get { return (byte)(CurrentTrack == null ? 0 : CurrentTrack.Rating); } set { if (CurrentTrack != null) { CurrentTrack.Rating = (int)Math.Min (5u, value); CurrentTrack.Save (); foreach (var source in ServiceManager.SourceManager.Sources) { var psource = source as PrimarySource; if (psource != null) { psource.NotifyTracksChanged (BansheeQuery.RatingField); } } } } } public bool CanSeek { get { return active_engine.CanSeek; } } public bool CanPause { get { return CurrentTrack != null && !CurrentTrack.IsLive; } } public bool SupportsEqualizer { get { return ((active_engine is IEqualizer) && active_engine.SupportsEqualizer); } } public int SubtitleCount { get { return active_engine.SubtitleCount; } } public int SubtitleIndex { set { active_engine.SubtitleIndex = value; } } public SafeUri SubtitleUri { set { active_engine.SubtitleUri = value; } get { return active_engine.SubtitleUri; } } public bool InDvdMenu { get { return active_engine.InDvdMenu; } } public VideoDisplayContextType VideoDisplayContextType { get { return active_engine.VideoDisplayContextType; } } public uint Length { get { uint length = active_engine.Length; if (length > 0) { return length; } else if (CurrentTrack == null) { return 0; } return (uint) CurrentTrack.Duration.TotalSeconds; } } public PlayerEngine ActiveEngine { get { return active_engine; } set { pending_engine = value; } } public PlayerEngine DefaultEngine { get { return default_engine; } set { if (engines.Contains (value)) { engines.Remove (value); } engines.Insert (0, value); default_engine = value; EngineSchema.Set (value.Id); } } public IEnumerable<PlayerEngine> Engines { get { return engines; } } #region Player Event System private LinkedList<PlayerEventHandlerSlot> event_handlers = new LinkedList<PlayerEventHandlerSlot> (); private struct PlayerEventHandlerSlot { public PlayerEvent EventMask; public PlayerEventHandler Handler; public PlayerEventHandlerSlot (PlayerEvent mask, PlayerEventHandler handler) { EventMask = mask; Handler = handler; } } private const PlayerEvent event_all_mask = PlayerEvent.Iterate | PlayerEvent.StateChange | PlayerEvent.StartOfStream | PlayerEvent.EndOfStream | PlayerEvent.Buffering | PlayerEvent.Seek | PlayerEvent.Error | PlayerEvent.Volume | PlayerEvent.Metadata | PlayerEvent.TrackInfoUpdated | PlayerEvent.RequestNextTrack | PlayerEvent.PrepareVideoWindow; private const PlayerEvent event_default_mask = event_all_mask & ~PlayerEvent.Iterate; private static void VerifyEventMask (PlayerEvent eventMask) { if (eventMask <= PlayerEvent.None || eventMask > event_all_mask) { throw new ArgumentOutOfRangeException ("eventMask", "A valid event mask must be provided"); } } public void ConnectEvent (PlayerEventHandler handler) { ConnectEvent (handler, event_default_mask, false); } public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask) { ConnectEvent (handler, eventMask, false); } public void ConnectEvent (PlayerEventHandler handler, bool connectAfter) { ConnectEvent (handler, event_default_mask, connectAfter); } public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask, bool connectAfter) { lock (event_handlers) { VerifyEventMask (eventMask); PlayerEventHandlerSlot slot = new PlayerEventHandlerSlot (eventMask, handler); if (connectAfter) { event_handlers.AddLast (slot); } else { event_handlers.AddFirst (slot); } } } private LinkedListNode<PlayerEventHandlerSlot> FindEventNode (PlayerEventHandler handler) { LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First; while (node != null) { if (node.Value.Handler == handler) { return node; } node = node.Next; } return null; } public void DisconnectEvent (PlayerEventHandler handler) { lock (event_handlers) { LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler); if (node != null) { event_handlers.Remove (node); } } } public void ModifyEvent (PlayerEvent eventMask, PlayerEventHandler handler) { lock (event_handlers) { VerifyEventMask (eventMask); LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler); if (node != null) { PlayerEventHandlerSlot slot = node.Value; slot.EventMask = eventMask; node.Value = slot; } } } private void RaiseEvent (PlayerEventArgs args) { lock (event_handlers) { if (args.Event == PlayerEvent.StateChange && args is PlayerEventStateChangeArgs) { HandleStateChange ((PlayerEventStateChangeArgs)args); } LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First; while (node != null) { if ((node.Value.EventMask & args.Event) == args.Event) { try { node.Value.Handler (args); } catch (Exception e) { Log.Error (String.Format ("Error running PlayerEngine handler for {0}", args.Event), e); } } node = node.Next; } } } #endregion string IService.ServiceName { get { return "PlayerEngine"; } } IDBusExportable IDBusExportable.Parent { get { return null; } } public static readonly SchemaEntry<int> VolumeSchema = new SchemaEntry<int> ( "player_engine", "volume", 80, "Volume", "Volume of playback relative to mixer output" ); public static readonly SchemaEntry<string> EngineSchema = new SchemaEntry<string> ( "player_engine", "backend", "helix-remote", "Backend", "Name of media playback engine backend" ); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Timers; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System.Text; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")] public class GroupsModule : ISharedRegionModule, IGroupsModule { /// <summary> /// ; To use this module, you must specify the following in your OpenSim.ini /// [GROUPS] /// Enabled = true /// /// Module = GroupsModule /// NoticesEnabled = true /// DebugEnabled = true /// /// GroupsServicesConnectorModule = XmlRpcGroupsServicesConnector /// XmlRpcServiceURL = http://osflotsam.org/xmlrpc.php /// XmlRpcServiceReadKey = 1234 /// XmlRpcServiceWriteKey = 1234 /// /// MessagingModule = GroupsMessagingModule /// MessagingEnabled = true /// /// ; Disables HTTP Keep-Alive for Groups Module HTTP Requests, work around for /// ; a problem discovered on some Windows based region servers. Only disable /// ; if you see a large number (dozens) of the following Exceptions: /// ; System.Net.WebException: The request was aborted: The request was canceled. /// /// XmlRpcDisableKeepAlive = false /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IMessageTransferModule m_msgTransferModule; private IGroupsMessagingModule m_groupsMessagingModule; private IGroupsServicesConnector m_groupData; // Configuration settings private bool m_groupsEnabled = false; private bool m_groupNoticesEnabled = true; private bool m_debugEnabled = false; private int m_levelGroupCreate = 0; #region Region Module interfaceBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false); if (!m_groupsEnabled) { return; } if (groupsConfig.GetString("Module", "Default") != Name) { m_groupsEnabled = false; return; } m_log.InfoFormat("[GROUPS]: Initializing {0}", this.Name); m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false); m_levelGroupCreate = groupsConfig.GetInt("LevelGroupCreate", 0); } } public void AddRegion(Scene scene) { if (m_groupsEnabled) { scene.RegisterModuleInterface<IGroupsModule>(this); scene.AddCommand( "Debug", this, "debug groups verbose", "debug groups verbose <true|false>", "This setting turns on very verbose groups debugging", HandleDebugGroupsVerbose); } } private void HandleDebugGroupsVerbose(object modules, string[] args) { if (args.Length < 4) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } bool verbose = false; if (!bool.TryParse(args[3], out verbose)) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } m_debugEnabled = verbose; MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled); } public void RegionLoaded(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_groupData == null) { m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); // No Groups Service Connector, then nothing works... if (m_groupData == null) { m_groupsEnabled = false; m_log.Error("[GROUPS]: Could not get IGroupsServicesConnector"); Close(); return; } } if (m_msgTransferModule == null) { m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_msgTransferModule == null) { m_groupsEnabled = false; m_log.Warn("[GROUPS]: Could not get IMessageTransferModule"); } } if (m_groupsMessagingModule == null) { m_groupsMessagingModule = scene.RequestModuleInterface<IGroupsMessagingModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_groupsMessagingModule == null) m_log.Warn("[GROUPS]: Could not get IGroupsMessagingModule"); } lock (m_sceneList) { m_sceneList.Add(scene); } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; // The InstantMessageModule itself doesn't do this, // so lets see if things explode if we don't do it // scene.EventManager.OnClientClosed += OnClientClosed; } public void RemoveRegion(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_sceneList) { m_sceneList.Remove(scene); } } public void Close() { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module."); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "GroupsModule"; } } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region EventHandlers private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnRequestAvatarProperties += OnRequestAvatarProperties; // Used for Notices and Group Invites/Accept/Reject client.OnInstantMessage += OnInstantMessage; // Send client their groups information. SendAgentGroupDataUpdate(client, client.AgentId); } private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); //GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetRequestingAgentID(remoteClient), avatarID).ToArray(); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } /* * This becomes very problematic in a shared module. In a shared module you may have more then one * reference to IClientAPI's, one for 0 or 1 root connections, and 0 or more child connections. * The OnClientClosed event does not provide anything to indicate which one of those should be closed * nor does it provide what scene it was from so that the specific reference can be looked up. * The InstantMessageModule.cs does not currently worry about unregistering the handles, * and it should be an issue, since it's the client that references us not the other way around * , so as long as we don't keep a reference to the client laying around, the client can still be GC'ed private void OnClientClosed(UUID AgentId) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_ActiveClients) { if (m_ActiveClients.ContainsKey(AgentId)) { IClientAPI client = m_ActiveClients[AgentId]; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnDirFindQuery -= OnDirFindQuery; client.OnInstantMessage -= OnInstantMessage; m_ActiveClients.Remove(AgentId); } else { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here."); } } } */ private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID activeGroupID = UUID.Zero; string activeGroupTitle = string.Empty; string activeGroupName = string.Empty; ulong activeGroupPowers = (ulong)GroupPowers.None; GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient), dataForAgentID); if (membership != null) { activeGroupID = membership.GroupID; activeGroupTitle = membership.GroupTitle; activeGroupPowers = membership.GroupPowers; } SendAgentDataUpdate(remoteClient, dataForAgentID, activeGroupID, activeGroupName, activeGroupPowers, activeGroupTitle); SendScenePresenceUpdate(dataForAgentID, activeGroupTitle); } private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null); if (group != null) { GroupName = group.GroupName; } else { GroupName = "Unknown"; } remoteClient.SendGroupNameReply(GroupID, GroupName); } private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: {0} called for {1}, message type {2}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name, (InstantMessageDialog)im.dialog); // Group invitations if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) { UUID inviteID = new UUID(im.imSessionID); GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); if (inviteInfo == null) { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Received an Invite IM for an invite that does not exist {0}.", inviteID); return; } if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID); UUID fromAgentID = new UUID(im.fromAgentID); if ((inviteInfo != null) && (fromAgentID == inviteInfo.AgentID)) { // Accept if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice."); // and the sessionid is the role m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID); GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = UUID.Zero.Guid; msg.toAgentID = inviteInfo.AgentID.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "Groups"; msg.message = string.Format("You have been added to the group."); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, inviteInfo.AgentID); UpdateAllClientsWithGroupInfo(inviteInfo.AgentID); // TODO: If the inviter is still online, they need an agent dataupdate // and maybe group membership updates for the invitee m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); } // Reject if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice."); m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); } } } // Group notices if ((im.dialog == (byte)InstantMessageDialog.GroupNotice)) { if (!m_groupNoticesEnabled) { return; } UUID GroupID = new UUID(im.toAgentID); if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null) != null) { UUID NoticeID = UUID.Random(); string Subject = im.message.Substring(0, im.message.IndexOf('|')); string Message = im.message.Substring(Subject.Length + 1); InventoryItemBase item = null; bool hasAttachment = false; UUID itemID = UUID.Zero; //Assignment to quiet compiler UUID ownerID = UUID.Zero; //Assignment to quiet compiler byte[] bucket; if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0) { string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket); binBucket = binBucket.Remove(0, 14).Trim(); OSDMap binBucketOSD = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket); if (binBucketOSD is OSD) { OSDMap binBucketMap = (OSDMap)binBucketOSD; itemID = binBucketMap["item_id"].AsUUID(); ownerID = binBucketMap["owner_id"].AsUUID(); //Attempt to get the details of the attached item. //If sender doesn't own the attachment, the item //variable will be set to null and attachment will //not be included with the group notice. Scene scene = (Scene)remoteClient.Scene; item = new InventoryItemBase(itemID, ownerID); item = scene.InventoryService.GetItem(item); if (item != null) { //Got item details so include the attachment. hasAttachment = true; } } else { m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType()); } } if (hasAttachment) { //Bucket contains information about attachment. // //Byte offset and description of bucket data: //0: 1 byte indicating if attachment is present //1: 1 byte indicating the type of attachment //2: 16 bytes - Group UUID //18: 16 bytes - UUID of the attachment owner //34: 16 bytes - UUID of the attachment //50: variable - Name of the attachment //??: NUL byte to terminate the attachment name byte[] name = Encoding.UTF8.GetBytes(item.Name); bucket = new byte[51 + name.Length];//3 bytes, 3 UUIDs, and name bucket[0] = 1; //Has attachment flag bucket[1] = (byte)item.InvType; //Type of Attachment GroupID.ToBytes(bucket, 2); ownerID.ToBytes(bucket, 18); itemID.ToBytes(bucket, 34); name.CopyTo(bucket, 50); } else { bucket = new byte[19]; bucket[0] = 0; //Has attachment flag bucket[1] = 0; //Type of attachment GroupID.ToBytes(bucket, 2); bucket[18] = 0; //NUL terminate name of attachment } m_groupData.AddGroupNotice(GetRequestingAgentID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket); if (OnNewGroupNotice != null) { OnNewGroupNotice(GroupID, NoticeID); } if (m_debugEnabled) { foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), GroupID)) { if (m_debugEnabled) { UserAccount targetUser = m_sceneList[0].UserAccountService.GetUserAccount( remoteClient.Scene.RegionInfo.ScopeID, member.AgentID); if (targetUser != null) { m_log.DebugFormat( "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUser.FirstName + " " + targetUser.LastName, member.AcceptNotices); } else { m_log.DebugFormat( "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, member.AgentID, member.AcceptNotices); } } } } GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice); if (m_groupsMessagingModule != null) m_groupsMessagingModule.SendMessageToGroup( msg, GroupID, remoteClient.AgentId, gmd => gmd.AcceptNotices); } } if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted) { //Is bucket large enough to hold UUID of the attachment? if (im.binaryBucket.Length < 16) return; UUID noticeID = new UUID(im.imSessionID); if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Requesting notice {0} for {1}", noticeID, remoteClient.AgentId); GroupNoticeInfo notice = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), noticeID); if (notice != null) { UUID giver = new UUID(notice.BinaryBucket, 18); UUID attachmentUUID = new UUID(notice.BinaryBucket, 34); if (m_debugEnabled) m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId); string message; InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId, giver, attachmentUUID, out message); if (itemCopy == null) { remoteClient.SendAgentAlertMessage(message, false); return; } remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0); } else { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.", noticeID, remoteClient.AgentId); } } // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presence server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue if ((im.dialog == 210)) { // This is sent from the region that the ejectee was ejected from // if it's being delivered here, then the ejectee is here // so we need to send local updates to the agent. UUID ejecteeID = new UUID(im.toAgentID); im.dialog = (byte)InstantMessageDialog.MessageFromAgent; OutgoingInstantMessage(im, ejecteeID); IClientAPI ejectee = GetActiveClient(ejecteeID); if (ejectee != null) { UUID groupID = new UUID(im.imSessionID); ejectee.SendAgentDropGroup(groupID); } } } private void OnGridInstantMessage(GridInstantMessage msg) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Trigger the above event handler OnInstantMessage(null, msg); // If a message from a group arrives here, it may need to be forwarded to a local client if (msg.fromGroup == true) { switch (msg.dialog) { case (byte)InstantMessageDialog.GroupInvitation: case (byte)InstantMessageDialog.GroupNotice: UUID toAgentID = new UUID(msg.toAgentID); IClientAPI localClient = GetActiveClient(toAgentID); if (localClient != null) { localClient.SendInstantMessage(msg); } break; } } } #endregion #region IGroupsModule Members public event NewGroupNotice OnNewGroupNotice; public GroupRecord GetGroupRecord(UUID GroupID) { return m_groupData.GetGroupRecord(UUID.Zero, GroupID, null); } public GroupRecord GetGroupRecord(string name) { return m_groupData.GetGroupRecord(UUID.Zero, UUID.Zero, name); } public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); // Changing active group changes title, active powers, all kinds of things // anyone who is in any region that can see this client, should probably be // updated with new group info. At a minimum, they should get ScenePresence // updated with new title. UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient)); } /// <summary> /// Get the Role Titles for an Agent, for a specific group /// </summary> public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); List<GroupTitlesData> titles = new List<GroupTitlesData>(); foreach (GroupRolesData role in agentRoles) { GroupTitlesData title = new GroupTitlesData(); title.Name = role.Name; if (agentMembership != null) { title.Selected = agentMembership.ActiveRole == role.RoleID; } title.UUID = role.RoleID; titles.Add(title); } return titles; } public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name); List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupMembersData member in data) { m_log.DebugFormat("[GROUPS]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner); } } return data; } public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID); return data; } public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentID(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupRoleMembersData member in data) { m_log.DebugFormat("[GROUPS]: Member({0}) - Role({1})", member.MemberID, member.RoleID); } } return data; } public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupProfileData profile = new GroupProfileData(); GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null); if (groupInfo != null) { profile.AllowPublish = groupInfo.AllowPublish; profile.Charter = groupInfo.Charter; profile.FounderID = groupInfo.FounderID; profile.GroupID = groupID; profile.GroupMembershipCount = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID).Count; profile.GroupRolesCount = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID).Count; profile.InsigniaID = groupInfo.GroupPicture; profile.MaturePublish = groupInfo.MaturePublish; profile.MembershipFee = groupInfo.MembershipFee; profile.Money = 0; // TODO: Get this from the currency server? profile.Name = groupInfo.GroupName; profile.OpenEnrollment = groupInfo.OpenEnrollment; profile.OwnerRole = groupInfo.OwnerRoleID; profile.ShowInList = groupInfo.ShowInList; } GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); if (memberInfo != null) { profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } return profile; } public GroupMembershipData[] GetMembershipData(UUID agentID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); return m_groupData.GetAgentGroupMemberships(UUID.Zero, agentID).ToArray(); } public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: {0} called with groupID={1}, agentID={2}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID); return m_groupData.GetAgentGroupMembership(UUID.Zero, agentID, groupID); } public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Note: Permissions checking for modification rights is handled by the Groups Server/Service m_groupData.UpdateGroup(GetRequestingAgentID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish); } public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) { // Note: Permissions checking for modification rights is handled by the Groups Server/Service if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentGroupInfo(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, acceptNotices, listInProfile); } public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name) != null) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; } // check user level ScenePresence avatar = null; Scene scene = (Scene)remoteClient.Scene; scene.TryGetScenePresence(remoteClient.AgentId, out avatar); if (avatar != null) { if (avatar.UserLevel < m_levelGroupCreate) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got insufficient permissions to create a group."); return UUID.Zero; } } // check funds // is there is a money module present ? IMoneyModule money = scene.RequestModuleInterface<IMoneyModule>(); if (money != null) { // do the transaction, that is if the agent has got sufficient funds if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got insufficient funds to create a group."); return UUID.Zero; } money.ApplyCharge(GetRequestingAgentID(remoteClient), money.GroupCreationCharge, MoneyTransactionType.GroupCreate); } UUID groupID = m_groupData.CreateGroup(GetRequestingAgentID(remoteClient), name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, GetRequestingAgentID(remoteClient)); remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly"); // Update the founder with new group information. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); return groupID; } public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // ToDo: check if agent is a member of group and is allowed to see notices? return m_groupData.GetGroupNotices(GetRequestingAgentID(remoteClient), groupID).ToArray(); } /// <summary> /// Get the title of the agent's current role. /// </summary> public string GetGroupTitle(UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero, avatarID); if (membership != null) { return membership.GroupTitle; } return string.Empty; } /// <summary> /// Change the current Active Group Role for Agent /// </summary> public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroupRole(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, titleRoleID); // TODO: Not sure what all is needed here, but if the active group role change is for the group // the client currently has set active, then we need to do a scene presence update too // if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID) UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient)); } public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Security Checks are handled in the Groups Service. switch ((OpenMetaverse.GroupRoleUpdate)updateType) { case OpenMetaverse.GroupRoleUpdate.Create: m_groupData.AddGroupRole(GetRequestingAgentID(remoteClient), groupID, UUID.Random(), name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.Delete: m_groupData.RemoveGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID); break; case OpenMetaverse.GroupRoleUpdate.UpdateAll: case OpenMetaverse.GroupRoleUpdate.UpdateData: case OpenMetaverse.GroupRoleUpdate.UpdatePowers: if (m_debugEnabled) { GroupPowers gp = (GroupPowers)powers; m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString()); } m_groupData.UpdateGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID, name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.NoUpdate: default: // No Op break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check switch (changes) { case 0: // Add m_groupData.AddAgentToGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID); break; case 1: // Remove m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID); break; default: m_log.ErrorFormat("[GROUPS]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupNoticeInfo data = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), groupNoticeID); if (data != null) { GridInstantMessage msg = CreateGroupNoticeIM(remoteClient.AgentId, groupNoticeID, (byte)InstantMessageDialog.GroupNoticeRequested); OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient)); } } public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GridInstantMessage msg = new GridInstantMessage(); byte[] bucket; msg.imSessionID = groupNoticeID.Guid; msg.toAgentID = agentID.Guid; msg.dialog = dialog; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID, groupNoticeID); if (info != null) { msg.fromAgentID = info.GroupID.Guid; msg.timestamp = info.noticeData.Timestamp; msg.fromAgentName = info.noticeData.FromName; msg.message = info.noticeData.Subject + "|" + info.Message; if (info.BinaryBucket[0] > 0) { //32 is due to not needing space for two of the UUIDs. //(Don't need UUID of attachment or its owner in IM) //50 offset gets us to start of attachment name. //We are skipping the attachment flag, type, and //the three UUID fields at the start of the bucket. bucket = new byte[info.BinaryBucket.Length-32]; bucket[0] = 1; //Has attachment bucket[1] = info.BinaryBucket[1]; Array.Copy(info.BinaryBucket, 50, bucket, 18, info.BinaryBucket.Length-50); } else { bucket = new byte[19]; bucket[0] = 0; //No attachment bucket[1] = 0; //Attachment type bucket[18] = 0; //NUL terminate name } info.GroupID.ToBytes(bucket, 2); msg.binaryBucket = bucket; } else { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Group Notice {0} not found, composing empty message.", groupNoticeID); msg.fromAgentID = UUID.Zero.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = string.Empty; msg.message = string.Empty; msg.binaryBucket = new byte[0]; } return msg; } public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Send agent information about his groups SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Should check to see if OpenEnrollment, or if there's an outstanding invitation m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, UUID.Zero); remoteClient.SendJoinGroupReply(groupID, true); // Should this send updates to everyone in the group? SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); remoteClient.SendLeaveGroupReply(groupID, true); remoteClient.SendAgentDropGroup(groupID); // SL sends out notifcations to the group messaging session that the person has left // Should this also update everyone who is in the group? SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) { EjectGroupMember(remoteClient, GetRequestingAgentID(remoteClient), groupID, ejecteeID); } public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID ejecteeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check? m_groupData.RemoveAgentFromGroup(agentID, ejecteeID, groupID); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; remoteClient.SendEjectGroupMemberReply(agentID, groupID, true); } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; client.SendEjectGroupMemberReply(agentID, groupID, true); } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount acc = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (acc != null) { agentName = acc.FirstName + " " + acc.LastName; } else { agentName = "Unknown member"; } } } GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null); UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID); if ((groupInfo == null) || (account == null)) { return; } // Send Message to Ejectee GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; // msg.fromAgentID = info.GroupID; msg.toAgentID = ejecteeID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, ejecteeID); // Message to ejector // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presence server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; msg.toAgentID = agentID.Guid; msg.timestamp = 0; msg.fromAgentName = agentName; if (account != null) { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, account.FirstName + " " + account.LastName); } else { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, "Unknown member"); } msg.dialog = (byte)210; //interop msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, agentID); // SL sends out messages to everyone in the group // Who all should receive updates and what should they be updated with? UpdateAllClientsWithGroupInfo(ejecteeID); } public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID) { InviteGroup(remoteClient, GetRequestingAgentID(remoteClient), groupID, invitedAgentID, roleID); } public void InviteGroup(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID invitedAgentID, UUID roleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (account != null) { agentName = account.FirstName + " " + account.LastName; } else { agentName = "Unknown member"; } } } // Todo: Security check, probably also want to send some kind of notification UUID InviteID = UUID.Random(); m_groupData.AddAgentToGroupInvite(agentID, InviteID, groupID, roleID, invitedAgentID); // Check to see if the invite went through, if it did not then it's possible // the remoteClient did not validate or did not have permission to invite. GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(agentID, InviteID); if (inviteInfo != null) { if (m_msgTransferModule != null) { Guid inviteUUID = InviteID.Guid; GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = inviteUUID; // msg.fromAgentID = agentID.Guid; msg.fromAgentID = groupID.Guid; msg.toAgentID = invitedAgentID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("{0} has invited you to join a group. There is no cost to join this group.", agentName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[20]; OutgoingInstantMessage(msg, invitedAgentID); } } } public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query) { return m_groupData.FindGroups(GetRequestingAgentID(remoteClient), query); } #endregion #region Client/Update Tools /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null) { if (!sp.IsChildAgent) { return sp.ControllingClient; } else { child = sp.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none return child; } /// <summary> /// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'. /// </summary> private void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, UUID dataForAgentID, GroupMembershipData[] data) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDArray AgentData = new OSDArray(1); OSDMap AgentDataMap = new OSDMap(1); AgentDataMap.Add("AgentID", OSD.FromUUID(dataForAgentID)); AgentData.Add(AgentDataMap); OSDArray GroupData = new OSDArray(data.Length); OSDArray NewGroupData = new OSDArray(data.Length); foreach (GroupMembershipData membership in data) { if (GetRequestingAgentID(remoteClient) != dataForAgentID) { if (!membership.ListInProfile) { // If we're sending group info to remoteclient about another agent, // filter out groups the other agent doesn't want to share. continue; } } OSDMap GroupDataMap = new OSDMap(6); OSDMap NewGroupDataMap = new OSDMap(1); GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID)); GroupDataMap.Add("GroupPowers", OSD.FromULong(membership.GroupPowers)); GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices)); GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture)); GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution)); GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName)); NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile)); GroupData.Add(GroupDataMap); NewGroupData.Add(NewGroupDataMap); } OSDMap llDataStruct = new OSDMap(3); llDataStruct.Add("AgentData", AgentData); llDataStruct.Add("GroupData", GroupData); llDataStruct.Add("NewGroupData", NewGroupData); if (m_debugEnabled) { m_log.InfoFormat("[GROUPS]: {0}", OSDParser.SerializeJsonString(llDataStruct)); } IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); if (queue != null) { queue.Enqueue(queue.BuildEvent("AgentGroupDataUpdate", llDataStruct), GetRequestingAgentID(remoteClient)); } } private void SendScenePresenceUpdate(UUID AgentID, string Title) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Updating scene title for {0} with title: {1}", AgentID, Title); ScenePresence presence = null; foreach (Scene scene in m_sceneList) { presence = scene.GetScenePresence(AgentID); if (presence != null) { if (presence.Grouptitle != Title) { presence.Grouptitle = Title; if (! presence.IsChildAgent) presence.SendAvatarDataToAllClients(); } } } } /// <summary> /// Send updates to all clients who might be interested in groups data for dataForClientID /// </summary> private void UpdateAllClientsWithGroupInfo(UUID dataForClientID) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Probably isn't nessesary to update every client in every scene. // Need to examine client updates and do only what's nessesary. lock (m_sceneList) { foreach (Scene scene in m_sceneList) { scene.ForEachClient(delegate(IClientAPI client) { SendAgentGroupDataUpdate(client, dataForClientID); }); } } } /// <summary> /// Update remoteClient with group information about dataForAgentID /// </summary> private void SendAgentGroupDataUpdate(IClientAPI remoteClient, UUID dataForAgentID) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff OnAgentDataUpdateRequest(remoteClient, dataForAgentID, UUID.Zero); // Need to send a group membership update to the client // UDP version doesn't seem to behave nicely. But we're going to send it out here // with an empty group membership to hopefully remove groups being displayed due // to the core Groups Stub remoteClient.SendGroupMembership(new GroupMembershipData[0]); GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, dataForAgentID); SendGroupMembershipInfoViaCaps(remoteClient, dataForAgentID, membershipArray); remoteClient.SendAvatarGroupsReply(dataForAgentID, membershipArray); if (remoteClient.AgentId == dataForAgentID) remoteClient.RefreshGroupMembership(); } /// <summary> /// Get a list of groups memberships for the agent that are marked "ListInProfile" /// (unless that agent has a godLike aspect, in which case get all groups) /// </summary> /// <param name="dataForAgentID"></param> /// <returns></returns> private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID) { List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId, dataForAgentID); GroupMembershipData[] membershipArray; // cScene and property accessor 'isGod' are in support of the opertions to bypass 'hidden' group attributes for // those with a GodLike aspect. Scene cScene = (Scene)requestingClient.Scene; bool isGod = cScene.Permissions.IsGod(requestingClient.AgentId); if (isGod) { membershipArray = membershipData.ToArray(); } else { if (requestingClient.AgentId != dataForAgentID) { Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership) { return membership.ListInProfile; }; membershipArray = membershipData.FindAll(showInProfile).ToArray(); } else { membershipArray = membershipData.ToArray(); } } if (m_debugEnabled) { m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); foreach (GroupMembershipData membership in membershipArray) { m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers); } } return membershipArray; } private void SendAgentDataUpdate(IClientAPI remoteClient, UUID dataForAgentID, UUID activeGroupID, string activeGroupName, ulong activeGroupPowers, string activeGroupTitle) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, dataForAgentID); string firstname, lastname; if (account != null) { firstname = account.FirstName; lastname = account.LastName; } else { firstname = "Unknown"; lastname = "Unknown"; } remoteClient.SendAgentDataUpdate(dataForAgentID, activeGroupID, firstname, lastname, activeGroupPowers, activeGroupName, activeGroupTitle); } #endregion #region IM Backed Processes private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); IClientAPI localClient = GetActiveClient(msgTo); if (localClient != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is local, delivering directly", localClient.Name); localClient.SendInstantMessage(msg); } else if (m_msgTransferModule != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Message Sent: {0}", success?"Succeeded":"Failed"); }); } } public void NotifyChange(UUID groupID) { // Notify all group members of a chnge in group roles and/or // permissions // } #endregion private UUID GetRequestingAgentID(IClientAPI client) { UUID requestingAgentID = UUID.Zero; if (client != null) { requestingAgentID = client.AgentId; } return requestingAgentID; } } public class GroupNoticeInfo { public GroupNoticeData noticeData = new GroupNoticeData(); public UUID GroupID = UUID.Zero; public string Message = string.Empty; public byte[] BinaryBucket = new byte[0]; } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.IO; using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.TestProtos; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; namespace Google.ProtocolBuffers { [TestClass] public class CodedInputStreamTest { /// <summary> /// Helper to construct a byte array from a bunch of bytes. The inputs are /// actually ints so that I can use hex notation and not get stupid errors /// about precision. /// </summary> private static byte[] Bytes(params int[] bytesAsInts) { byte[] bytes = new byte[bytesAsInts.Length]; for (int i = 0; i < bytesAsInts.Length; i++) { bytes[i] = (byte) bytesAsInts[i]; } return bytes; } /// <summary> /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and /// </summary> private static void AssertReadVarint(byte[] data, ulong value) { CodedInputStream input = CodedInputStream.CreateInstance(data); Assert.AreEqual((uint) value, input.ReadRawVarint32()); input = CodedInputStream.CreateInstance(data); Assert.AreEqual(value, input.ReadRawVarint64()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize)); Assert.AreEqual((uint) value, input.ReadRawVarint32()); input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize)); Assert.AreEqual(value, input.ReadRawVarint64()); Assert.IsTrue(input.IsAtEnd); } // Try reading directly from a MemoryStream. We want to verify that it // doesn't read past the end of the input, so write an extra byte - this // lets us test the position at the end. MemoryStream memoryStream = new MemoryStream(); memoryStream.Write(data, 0, data.Length); memoryStream.WriteByte(0); memoryStream.Position = 0; Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream)); Assert.AreEqual(data.Length, memoryStream.Position); } /// <summary> /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and /// expects them to fail with an InvalidProtocolBufferException whose /// description matches the given one. /// </summary> private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) { CodedInputStream input = CodedInputStream.CreateInstance(data); try { input.ReadRawVarint32(); Assert.Fail("Should have thrown an exception."); } catch (InvalidProtocolBufferException e) { Assert.AreEqual(expected.Message, e.Message); } input = CodedInputStream.CreateInstance(data); try { input.ReadRawVarint64(); Assert.Fail("Should have thrown an exception."); } catch (InvalidProtocolBufferException e) { Assert.AreEqual(expected.Message, e.Message); } // Make sure we get the same error when reading directly from a Stream. try { CodedInputStream.ReadRawVarint32(new MemoryStream(data)); Assert.Fail("Should have thrown an exception."); } catch (InvalidProtocolBufferException e) { Assert.AreEqual(expected.Message, e.Message); } } [TestMethod] public void ReadVarint() { AssertReadVarint(Bytes(0x00), 0); AssertReadVarint(Bytes(0x01), 1); AssertReadVarint(Bytes(0x7f), 127); // 14882 AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); // 2961488830 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x0bL << 28)); // 64-bit // 7256456126 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x1bL << 28)); // 41256202580718336 AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); // 11964378330978735131 AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); // Failures AssertReadVarintFailure( InvalidProtocolBufferException.MalformedVarint(), Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00)); AssertReadVarintFailure( InvalidProtocolBufferException.TruncatedMessage(), Bytes(0x80)); } /// <summary> /// Parses the given bytes using ReadRawLittleEndian32() and checks /// that the result matches the given value. /// </summary> private static void AssertReadLittleEndian32(byte[] data, uint value) { CodedInputStream input = CodedInputStream.CreateInstance(data); Assert.AreEqual(value, input.ReadRawLittleEndian32()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { input = CodedInputStream.CreateInstance( new SmallBlockInputStream(data, blockSize)); Assert.AreEqual(value, input.ReadRawLittleEndian32()); Assert.IsTrue(input.IsAtEnd); } } /// <summary> /// Parses the given bytes using ReadRawLittleEndian64() and checks /// that the result matches the given value. /// </summary> private static void AssertReadLittleEndian64(byte[] data, ulong value) { CodedInputStream input = CodedInputStream.CreateInstance(data); Assert.AreEqual(value, input.ReadRawLittleEndian64()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { input = CodedInputStream.CreateInstance( new SmallBlockInputStream(data, blockSize)); Assert.AreEqual(value, input.ReadRawLittleEndian64()); Assert.IsTrue(input.IsAtEnd); } } [TestMethod] public void ReadLittleEndian() { AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), 0x123456789abcdef0L); AssertReadLittleEndian64( Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); } [TestMethod] public void DecodeZigZag32() { Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0)); Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1)); Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2)); Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3)); Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE)); Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF)); Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE)); Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF)); } [TestMethod] public void DecodeZigZag64() { Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0)); Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1)); Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2)); Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3)); Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL)); Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL)); Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL)); Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL)); Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL)); Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL)); } [TestMethod] public void ReadWholeMessage() { TestAllTypes message = TestUtil.GetAllSet(); byte[] rawBytes = message.ToByteArray(); Assert.AreEqual(rawBytes.Length, message.SerializedSize); TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); TestUtil.AssertAllFieldsSet(message2); // Try different block sizes. for (int blockSize = 1; blockSize < 256; blockSize *= 2) { message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); TestUtil.AssertAllFieldsSet(message2); } } [TestMethod] public void SkipWholeMessage() { TestAllTypes message = TestUtil.GetAllSet(); byte[] rawBytes = message.ToByteArray(); // Create two parallel inputs. Parse one as unknown fields while using // skipField() to skip each field on the other. Expect the same tags. CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes); CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes); UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder(); uint tag; string name; while (input1.ReadTag(out tag, out name)) { uint tag2; Assert.IsTrue(input2.ReadTag(out tag2, out name)); Assert.AreEqual(tag, tag2); unknownFields.MergeFieldFrom(tag, input1); input2.SkipField(); } } /// <summary> /// Test that a bug in SkipRawBytes has been fixed: if the skip /// skips exactly up to a limit, this should bnot break things /// </summary> [TestMethod] public void SkipRawBytesBug() { byte[] rawBytes = new byte[] {1, 2}; CodedInputStream input = CodedInputStream.CreateInstance(rawBytes); int limit = input.PushLimit(1); input.SkipRawBytes(1); input.PopLimit(limit); Assert.AreEqual(2, input.ReadRawByte()); } public void ReadHugeBlob() { // Allocate and initialize a 1MB blob. byte[] blob = new byte[1 << 20]; for (int i = 0; i < blob.Length; i++) { blob[i] = (byte) i; } // Make a message containing it. TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TestUtil.SetAllFields(builder); builder.SetOptionalBytes(ByteString.CopyFrom(blob)); TestAllTypes message = builder.Build(); // Serialize and parse it. Make sure to parse from an InputStream, not // directly from a ByteString, so that CodedInputStream uses buffered // reading. TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput()); Assert.AreEqual(message.OptionalBytes, message2.OptionalBytes); // Make sure all the other fields were parsed correctly. TestAllTypes message3 = TestAllTypes.CreateBuilder(message2) .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes) .Build(); TestUtil.AssertAllFieldsSet(message3); } [TestMethod] public void ReadMaliciouslyLargeBlob() { MemoryStream ms = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(ms); uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); output.WriteRawVarint32(tag); output.WriteRawVarint32(0x7FFFFFFF); output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. output.Flush(); ms.Position = 0; CodedInputStream input = CodedInputStream.CreateInstance(ms); uint testtag; string ignore; Assert.IsTrue(input.ReadTag(out testtag, out ignore)); Assert.AreEqual(tag, testtag); try { ByteString bytes = null; input.ReadBytes(ref bytes); Assert.Fail("Should have thrown an exception!"); } catch (InvalidProtocolBufferException) { // success. } } private static TestRecursiveMessage MakeRecursiveMessage(int depth) { if (depth == 0) { return TestRecursiveMessage.CreateBuilder().SetI(5).Build(); } else { return TestRecursiveMessage.CreateBuilder() .SetA(MakeRecursiveMessage(depth - 1)).Build(); } } private static void AssertMessageDepth(TestRecursiveMessage message, int depth) { if (depth == 0) { Assert.IsFalse(message.HasA); Assert.AreEqual(5, message.I); } else { Assert.IsTrue(message.HasA); AssertMessageDepth(message.A, depth - 1); } } [TestMethod] public void MaliciousRecursion() { ByteString data64 = MakeRecursiveMessage(64).ToByteString(); ByteString data65 = MakeRecursiveMessage(65).ToByteString(); AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64); try { TestRecursiveMessage.ParseFrom(data65); Assert.Fail("Should have thrown an exception!"); } catch (InvalidProtocolBufferException) { // success. } CodedInputStream input = data64.CreateCodedInput(); input.SetRecursionLimit(8); try { TestRecursiveMessage.ParseFrom(input); Assert.Fail("Should have thrown an exception!"); } catch (InvalidProtocolBufferException) { // success. } } [TestMethod] public void SizeLimit() { // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't // apply to the latter case. MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray()); CodedInputStream input = CodedInputStream.CreateInstance(ms); input.SetSizeLimit(16); try { TestAllTypes.ParseFrom(input); Assert.Fail("Should have thrown an exception!"); } catch (InvalidProtocolBufferException) { // success. } } [TestMethod] public void ResetSizeCounter() { CodedInputStream input = CodedInputStream.CreateInstance( new SmallBlockInputStream(new byte[256], 8)); input.SetSizeLimit(16); input.ReadRawBytes(16); try { input.ReadRawByte(); Assert.Fail("Should have thrown an exception!"); } catch (InvalidProtocolBufferException) { // Success. } input.ResetSizeCounter(); input.ReadRawByte(); // No exception thrown. try { input.ReadRawBytes(16); // Hits limit again. Assert.Fail("Should have thrown an exception!"); } catch (InvalidProtocolBufferException) { // Success. } } /// <summary> /// Tests that if we read an string that contains invalid UTF-8, no exception /// is thrown. Instead, the invalid bytes are replaced with the Unicode /// "replacement character" U+FFFD. /// </summary> [TestMethod] public void ReadInvalidUtf8() { MemoryStream ms = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(ms); uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); output.WriteRawVarint32(tag); output.WriteRawVarint32(1); output.WriteRawBytes(new byte[] {0x80}); output.Flush(); ms.Position = 0; CodedInputStream input = CodedInputStream.CreateInstance(ms); uint testtag; string ignored; Assert.IsTrue(input.ReadTag(out testtag, out ignored)); Assert.AreEqual(tag, testtag); string text = null; input.ReadString(ref text); Assert.AreEqual('\ufffd', text[0]); } /// <summary> /// A stream which limits the number of bytes it reads at a time. /// We use this to make sure that CodedInputStream doesn't screw up when /// reading in small blocks. /// </summary> private sealed class SmallBlockInputStream : MemoryStream { private readonly int blockSize; public SmallBlockInputStream(byte[] data, int blockSize) : base(data) { this.blockSize = blockSize; } public override int Read(byte[] buffer, int offset, int count) { return base.Read(buffer, offset, Math.Min(count, blockSize)); } } enum TestNegEnum { None = 0, Value = -2 } [TestMethod] public void TestNegativeEnum() { byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; CodedInputStream input = CodedInputStream.CreateInstance(bytes); object unk; TestNegEnum val = TestNegEnum.None; Assert.IsTrue(input.ReadEnum(ref val, out unk)); Assert.IsTrue(input.IsAtEnd); Assert.AreEqual(TestNegEnum.Value, val); } [TestMethod] public void TestNegativeEnumPackedArray() { int arraySize = 1 + (10 * 5); int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); output.WritePackedInt32Array(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); uint tag; string name; Assert.IsTrue(input.ReadTag(out tag, out name)); List<TestNegEnum> values = new List<TestNegEnum>(); ICollection<object> unk; input.ReadEnumArray(tag, name, values, out unk); Assert.AreEqual(2, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); Assert.AreEqual(TestNegEnum.Value, values[1]); Assert.IsNotNull(unk); Assert.AreEqual(4, unk.Count); } [TestMethod] public void TestNegativeEnumArray() { int arraySize = 1 + 1 + (11 * 5); int msgSize = arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); uint tag; string name; Assert.IsTrue(input.ReadTag(out tag, out name)); List<TestNegEnum> values = new List<TestNegEnum>(); ICollection<object> unk; input.ReadEnumArray(tag, name, values, out unk); Assert.AreEqual(2, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); Assert.AreEqual(TestNegEnum.Value, values[1]); Assert.IsNotNull(unk); Assert.AreEqual(4, unk.Count); } //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily [TestMethod] public void TestSlowPathAvoidance() { using (var ms = new MemoryStream()) { CodedOutputStream output = CodedOutputStream.CreateInstance(ms); output.WriteField(FieldType.Bytes, 1, "bytes", ByteString.CopyFrom(new byte[100])); output.WriteField(FieldType.Bytes, 2, "bytes", ByteString.CopyFrom(new byte[100])); output.Flush(); ms.Position = 0; CodedInputStream input = CodedInputStream.CreateInstance(ms, new byte[ms.Length / 2]); uint tag; string ignore; ByteString value; Assert.IsTrue(input.ReadTag(out tag, out ignore)); Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); value = ByteString.Empty; Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100); Assert.IsTrue(input.ReadTag(out tag, out ignore)); Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); value = ByteString.Empty; Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100); } } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// CreditCardInformation /// </summary> [DataContract] public partial class CreditCardInformation : IEquatable<CreditCardInformation>, IValidatableObject { public CreditCardInformation() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="CreditCardInformation" /> class. /// </summary> /// <param name="Address">Address.</param> /// <param name="CardNumber">The number on the credit card..</param> /// <param name="CardType">The credit card type. Valid values are: visa, mastercard, or amex..</param> /// <param name="ExpirationMonth">The month that the credit card expires (1-12)..</param> /// <param name="ExpirationYear">The year 4 digit year in which the credit card expires..</param> /// <param name="NameOnCard">The exact name printed on the credit card..</param> public CreditCardInformation(AddressInformation Address = default(AddressInformation), string CardNumber = default(string), string CardType = default(string), string ExpirationMonth = default(string), string ExpirationYear = default(string), string NameOnCard = default(string)) { this.Address = Address; this.CardNumber = CardNumber; this.CardType = CardType; this.ExpirationMonth = ExpirationMonth; this.ExpirationYear = ExpirationYear; this.NameOnCard = NameOnCard; } /// <summary> /// Gets or Sets Address /// </summary> [DataMember(Name="address", EmitDefaultValue=false)] public AddressInformation Address { get; set; } /// <summary> /// The number on the credit card. /// </summary> /// <value>The number on the credit card.</value> [DataMember(Name="cardNumber", EmitDefaultValue=false)] public string CardNumber { get; set; } /// <summary> /// The credit card type. Valid values are: visa, mastercard, or amex. /// </summary> /// <value>The credit card type. Valid values are: visa, mastercard, or amex.</value> [DataMember(Name="cardType", EmitDefaultValue=false)] public string CardType { get; set; } /// <summary> /// The month that the credit card expires (1-12). /// </summary> /// <value>The month that the credit card expires (1-12).</value> [DataMember(Name="expirationMonth", EmitDefaultValue=false)] public string ExpirationMonth { get; set; } /// <summary> /// The year 4 digit year in which the credit card expires. /// </summary> /// <value>The year 4 digit year in which the credit card expires.</value> [DataMember(Name="expirationYear", EmitDefaultValue=false)] public string ExpirationYear { get; set; } /// <summary> /// The exact name printed on the credit card. /// </summary> /// <value>The exact name printed on the credit card.</value> [DataMember(Name="nameOnCard", EmitDefaultValue=false)] public string NameOnCard { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CreditCardInformation {\n"); sb.Append(" Address: ").Append(Address).Append("\n"); sb.Append(" CardNumber: ").Append(CardNumber).Append("\n"); sb.Append(" CardType: ").Append(CardType).Append("\n"); sb.Append(" ExpirationMonth: ").Append(ExpirationMonth).Append("\n"); sb.Append(" ExpirationYear: ").Append(ExpirationYear).Append("\n"); sb.Append(" NameOnCard: ").Append(NameOnCard).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as CreditCardInformation); } /// <summary> /// Returns true if CreditCardInformation instances are equal /// </summary> /// <param name="other">Instance of CreditCardInformation to be compared</param> /// <returns>Boolean</returns> public bool Equals(CreditCardInformation other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Address == other.Address || this.Address != null && this.Address.Equals(other.Address) ) && ( this.CardNumber == other.CardNumber || this.CardNumber != null && this.CardNumber.Equals(other.CardNumber) ) && ( this.CardType == other.CardType || this.CardType != null && this.CardType.Equals(other.CardType) ) && ( this.ExpirationMonth == other.ExpirationMonth || this.ExpirationMonth != null && this.ExpirationMonth.Equals(other.ExpirationMonth) ) && ( this.ExpirationYear == other.ExpirationYear || this.ExpirationYear != null && this.ExpirationYear.Equals(other.ExpirationYear) ) && ( this.NameOnCard == other.NameOnCard || this.NameOnCard != null && this.NameOnCard.Equals(other.NameOnCard) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Address != null) hash = hash * 59 + this.Address.GetHashCode(); if (this.CardNumber != null) hash = hash * 59 + this.CardNumber.GetHashCode(); if (this.CardType != null) hash = hash * 59 + this.CardType.GetHashCode(); if (this.ExpirationMonth != null) hash = hash * 59 + this.ExpirationMonth.GetHashCode(); if (this.ExpirationYear != null) hash = hash * 59 + this.ExpirationYear.GetHashCode(); if (this.NameOnCard != null) hash = hash * 59 + this.NameOnCard.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Linq; using UnityEngine; namespace TiltBrush { // TODO: Allow light count to be reduced. Having to deal with inactive // lights is a burden for the rest of the codebase, and can be error prone // (e.g. component enabled vs. game object active). public class SceneScript : MonoBehaviour { public delegate void PoseChangedEventHandler( TrTransform prev, TrTransform current); public delegate void ActiveCanvasChangedEventHandler( CanvasScript prev, CanvasScript current); [SerializeField] private CanvasScript m_MainCanvas; [SerializeField] private CanvasScript m_SelectionCanvas; private bool m_bInitialized; private Light [] m_Lights; private CanvasScript m_ActiveCanvas; private List<CanvasScript> m_LayerCanvases; public event PoseChangedEventHandler PoseChanged; public event ActiveCanvasChangedEventHandler ActiveCanvasChanged; /// Helper for getting and setting transforms on Transform components. /// Transform natively allows you to access parent-relative ("local") /// and root-relative ("global") views of position, rotation, and scale. /// /// This helper gives you a scene-relative view of the transform. /// The syntax is a slight abuse of C#: /// /// TrTranform xf_SS = App.Scene.AsScene[gameobj.transform]; /// App.Scene.AsScene[gameobj.transform] = xf_SS; /// /// Safe to use during Awake() /// public TransformExtensions.RelativeAccessor AsScene; /// The global pose of this scene. All scene modifications must go through this. /// On assignment, range of local scale is limited (log10) to +/-4. /// Emits SceneScript.PoseChanged, CanvasScript.PoseChanged. public TrTransform Pose { get { return Coords.AsGlobal[transform]; } set { var prevScene = Coords.AsGlobal[transform]; value = SketchControlsScript.MakeValidScenePose(value, SceneSettings.m_Instance.HardBoundsRadiusMeters_SS); // Clamp scale, and prevent tilt. These are last-ditch sanity checks // and are not the proper way to impose UX constraints. { value.scale = Mathf.Clamp(Mathf.Abs(value.scale), 1e-4f, 1e4f); var qRestoreUp = Quaternion.FromToRotation( value.rotation * Vector3.up, Vector3.up); value = TrTransform.R(qRestoreUp) * value; } Coords.AsGlobal[transform] = value; // hasChanged is used in development builds to detect unsanctioned // changes to the transform. Set to false so we don't trip the detection! transform.hasChanged = false; if (PoseChanged != null) { PoseChanged(prevScene, value); } using (var canvases = AllCanvases.GetEnumerator()) { while (canvases.MoveNext()) { canvases.Current.OnScenePoseChanged(prevScene, value); } } } } /// Safe to use any time after initialization public CanvasScript ActiveCanvas { get { Debug.Assert(m_bInitialized); return m_ActiveCanvas; } set { Debug.Assert(m_bInitialized); if (value != m_ActiveCanvas) { var prev = m_ActiveCanvas; m_ActiveCanvas = value; if (ActiveCanvasChanged != null) { ActiveCanvasChanged(prev, m_ActiveCanvas); // This will be incredibly irritating, but until we have some other feedback... OutputWindowScript.m_Instance.CreateInfoCardAtController( InputManager.ControllerName.Brush, string.Format("Canvas is now {0}", ActiveCanvas.gameObject.name), fPopScalar: 0.5f, false); } } } } /// The initial start-up canvas; guaranteed to always exist public CanvasScript MainCanvas { get { return m_MainCanvas; } } public CanvasScript SelectionCanvas { get { return m_SelectionCanvas; } } public IEnumerable<CanvasScript> AllCanvases { get { yield return MainCanvas; if (SelectionCanvas != null) { yield return SelectionCanvas; } if (m_LayerCanvases != null) { for (int i = 0; i < m_LayerCanvases.Count; ++i) { yield return m_LayerCanvases[i]; } } } } // Init unless already initialized. Safe to call zero or multiple times. public void Init() { if (m_bInitialized) { return; } m_bInitialized = true; m_LayerCanvases = new List<CanvasScript>(); AsScene = new TransformExtensions.RelativeAccessor(transform); m_ActiveCanvas = m_MainCanvas; foreach (var c in AllCanvases) { c.Init(); } } void Awake() { Init(); m_Lights = new Light[(int)LightMode.NumLights]; for (int i = 0; i < m_Lights.Length; ++i) { GameObject go = new GameObject(string.Format("SceneLight {0}", i)); Transform t = go.transform; t.parent = App.Instance.m_EnvironmentTransform; t.localPosition = Vector3.zero; t.localRotation = Quaternion.identity; t.localScale = Vector3.one; Light newLight = go.AddComponent<Light>(); m_Lights[i] = newLight; } m_Lights[(int)LightMode.Shadow].shadows = LightShadows.Hard; m_Lights[(int)LightMode.Shadow].renderMode = LightRenderMode.ForcePixel; m_Lights[(int)LightMode.NoShadow].shadows = LightShadows.None; m_Lights[(int)LightMode.NoShadow].renderMode = LightRenderMode.ForceVertex; } public CanvasScript Test_AddLayer() { #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) if (Config.IsExperimental) { var go = new GameObject(string.Format("Layer {0}", m_LayerCanvases.Count)); go.transform.parent = transform; Coords.AsLocal[go.transform] = TrTransform.identity; go.transform.hasChanged = false; var layer = go.AddComponent<CanvasScript>(); m_LayerCanvases.Add(layer); App.Scene.ActiveCanvas = layer; return layer; } #endif return null; } public void Test_SquashCurrentLayer() { #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) if (Config.IsExperimental) { var layer = ActiveCanvas; if (layer == m_MainCanvas) { return; } // TODO: this should defer updates to the batches until the end foreach (var stroke in SketchMemoryScript.AllStrokes()) { if (stroke.Canvas == layer) { stroke.SetParentKeepWorldPosition(m_MainCanvas); } } // Hm. remove after squashing? OutputWindowScript.m_Instance.CreateInfoCardAtController( InputManager.ControllerName.Brush, string.Format("Squashed {0}", layer.gameObject.name)); ActiveCanvas = m_MainCanvas; } #endif } public void Test_CycleCanvas() { #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) if (Config.IsExperimental) { // Klunky! Find the next canvas in the list (assumes AllCanvases has deterministic order) // Skip over the selection canvas; it's internal. var all = AllCanvases.ToList(); int next = (all.IndexOf(ActiveCanvas) + 1) % all.Count; if (all[next] == m_SelectionCanvas) { next = (next + 1) % all.Count; } ActiveCanvas = all[next]; } #endif } public int GetNumLights() { return m_Lights.Length; } public Light GetLight(int index) { return m_Lights[index]; } } } // namespace TiltBrush
using System; using System.Collections.Generic; using System.Linq.Expressions; using Shouldly; using Xunit; using System.Linq; using AutoMapper.QueryableExtensions.Impl; using AutoMapper.Internal; using AutoMapper.QueryableExtensions; namespace AutoMapper.UnitTests { public static class ExpressionBuilderExtensions { public static Expression<Func<TSource, TDestination>> GetMapExpression<TSource, TDestination>(this IProjectionBuilder expressionBuilder) => (Expression<Func<TSource, TDestination>>)expressionBuilder.GetProjection(typeof(TSource), typeof(TDestination), null, Array.Empty<MemberPath>()).Projection; } public class SimpleProductDto { public string Name { set; get; } public string ProductSubcategoryName { set; get; } public string CategoryName { set; get; } } public class ExtendedProductDto { public string Name { set; get; } public string ProductSubcategoryName { set; get; } public string CategoryName { set; get; } public List<BillOfMaterialsDto> BOM { set; get; } } public class ComplexProductDto { public string Name { get; set; } public ProductSubcategoryDto ProductSubcategory { get; set; } } public class ProductSubcategoryDto { public string Name { get; set; } public ProductCategoryDto ProductCategory { get; set; } } public class ProductCategoryDto { public string Name { get; set; } } public class AbstractProductDto { public string Name { set; get; } public string ProductSubcategoryName { set; get; } public string CategoryName { set; get; } public List<ProductTypeDto> Types { get; set; } } public abstract class ProductTypeDto { } public class ProdTypeA : ProductTypeDto {} public class ProdTypeB : ProductTypeDto {} public class ProductTypeConverter : ITypeConverter<ProductType, ProductTypeDto> { public ProductTypeDto Convert(ProductType source, ProductTypeDto destination, ResolutionContext context) { if (source.Name == "A") return new ProdTypeA(); if (source.Name == "B") return new ProdTypeB(); throw new ArgumentException(); } } public class ProductType { public string Name { get; set; } } public class BillOfMaterialsDto { public int BillOfMaterialsID { set; get; } } public class Product { public string Name { get; set; } public ProductSubcategory ProductSubcategory { get; set; } public List<BillOfMaterials> BillOfMaterials { set; get; } public List<ProductType> Types { get; set; } } public class ProductSubcategory { public string Name { get; set; } public ProductCategory ProductCategory { get; set; } } public class ProductCategory { public string Name { get; set; } } public class BillOfMaterials { public int BillOfMaterialsID { set; get; } } public class When_mapping_using_expressions : SpecBase { private List<Product> _products; private Expression<Func<Product, SimpleProductDto>> _simpleProductConversionLinq; private Expression<Func<Product, ExtendedProductDto>> _extendedProductConversionLinq; private Expression<Func<Product, AbstractProductDto>> _abstractProductConversionLinq; private List<SimpleProductDto> _simpleProducts; private List<ExtendedProductDto> _extendedProducts; private MapperConfiguration _config; protected override void Establish_context() { _config = new MapperConfiguration(cfg => { cfg.CreateProjection<Product, SimpleProductDto>() .ForMember(m => m.CategoryName, dst => dst.MapFrom(p => p.ProductSubcategory.ProductCategory.Name)); cfg.CreateProjection<Product, ExtendedProductDto>() .ForMember(m => m.CategoryName, dst => dst.MapFrom(p => p.ProductSubcategory.ProductCategory.Name)) .ForMember(m => m.BOM, dst => dst.MapFrom(p => p.BillOfMaterials)); cfg.CreateProjection<BillOfMaterials, BillOfMaterialsDto>(); cfg.CreateProjection<Product, ComplexProductDto>(); cfg.CreateProjection<ProductSubcategory, ProductSubcategoryDto>(); cfg.CreateProjection<ProductCategory, ProductCategoryDto>(); cfg.CreateProjection<Product, AbstractProductDto>(); cfg.CreateMap<ProductType, ProductTypeDto>() //.ConvertUsing(x => ProductTypeDto.GetProdType(x)); .ConvertUsing<ProductTypeConverter>(); }); _simpleProductConversionLinq = _config.Internal().ProjectionBuilder.GetMapExpression<Product, SimpleProductDto>(); _extendedProductConversionLinq = _config.Internal().ProjectionBuilder.GetMapExpression<Product, ExtendedProductDto>(); _abstractProductConversionLinq = _config.Internal().ProjectionBuilder.GetMapExpression<Product, AbstractProductDto>(); _products = new List<Product>() { new Product { Name = "Foo", ProductSubcategory = new ProductSubcategory { Name = "Bar", ProductCategory = new ProductCategory { Name = "Baz" } }, BillOfMaterials = new List<BillOfMaterials> { new BillOfMaterials { BillOfMaterialsID = 5 } } , Types = new List<ProductType> { new ProductType() { Name = "A" }, new ProductType() { Name = "B" }, new ProductType() { Name = "A" } } } }; } protected override void Because_of() { var queryable = _products.AsQueryable(); _simpleProducts = queryable.Select(_simpleProductConversionLinq).ToList(); _extendedProducts = queryable.Select(_extendedProductConversionLinq).ToList(); } [Fact] public void Should_map_and_flatten() { _simpleProducts.Count.ShouldBe(1); _simpleProducts[0].Name.ShouldBe("Foo"); _simpleProducts[0].ProductSubcategoryName.ShouldBe("Bar"); _simpleProducts[0].CategoryName.ShouldBe("Baz"); _extendedProducts.Count.ShouldBe(1); _extendedProducts[0].Name.ShouldBe("Foo"); _extendedProducts[0].ProductSubcategoryName.ShouldBe("Bar"); _extendedProducts[0].CategoryName.ShouldBe("Baz"); _extendedProducts[0].BOM.Count.ShouldBe(1); _extendedProducts[0].BOM[0].BillOfMaterialsID.ShouldBe(5); } [Fact] public void Should_use_extension_methods() { var queryable = _products.AsQueryable(); var simpleProducts = queryable.ProjectTo<SimpleProductDto>(_config).ToList(); simpleProducts.Count.ShouldBe(1); simpleProducts[0].Name.ShouldBe("Foo"); simpleProducts[0].ProductSubcategoryName.ShouldBe("Bar"); simpleProducts[0].CategoryName.ShouldBe("Baz"); var extendedProducts = queryable.ProjectTo<ExtendedProductDto>(_config).ToList(); extendedProducts.Count.ShouldBe(1); extendedProducts[0].Name.ShouldBe("Foo"); extendedProducts[0].ProductSubcategoryName.ShouldBe("Bar"); extendedProducts[0].CategoryName.ShouldBe("Baz"); extendedProducts[0].BOM.Count.ShouldBe(1); extendedProducts[0].BOM[0].BillOfMaterialsID.ShouldBe(5); var complexProducts = queryable.ProjectTo<ComplexProductDto>(_config).ToList(); complexProducts.Count.ShouldBe(1); complexProducts[0].Name.ShouldBe("Foo"); complexProducts[0].ProductSubcategory.Name.ShouldBe("Bar"); complexProducts[0].ProductSubcategory.ProductCategory.Name.ShouldBe("Baz"); } } namespace CircularReferences { public class A { public int AP1 { get; set; } public string AP2 { get; set; } public virtual B B { get; set; } } public class B { public B() { BP2 = new HashSet<A>(); } public int BP1 { get; set; } public virtual ICollection<A> BP2 { get; set; } } public class AEntity { public int AP1 { get; set; } public string AP2 { get; set; } public virtual BEntity B { get; set; } } public class BEntity { public BEntity() { BP2 = new HashSet<AEntity>(); } public int BP1 { get; set; } public virtual ICollection<AEntity> BP2 { get; set; } } public class C { public C Value { get; set; } } public class When_mapping_circular_references : AutoMapperSpecBase { private IQueryable<BEntity> _bei; protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateProjection<BEntity, B>().MaxDepth(3); cfg.CreateProjection<AEntity, A>().MaxDepth(3); }); protected override void Because_of() { var be = new BEntity(); be.BP1 = 3; be.BP2.Add(new AEntity() { AP1 = 1, AP2 = "hello", B = be }); be.BP2.Add(new AEntity() { AP1 = 2, AP2 = "two", B = be }); var belist = new List<BEntity>(); belist.Add(be); _bei = belist.AsQueryable(); } [Fact] public void Should_not_throw_exception() { typeof(Exception).ShouldNotBeThrownBy(() => _bei.ProjectTo<B>(Configuration)); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See license.txt file in the project root for full license information. using EnvDTE; using Microsoft.VisualStudio.ConnectedServices; using Microsoft.Win32; using NuGet.VisualStudio; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace AzureIoTHubConnectedService { /// <summary> /// NuGet package utilities. /// </summary> internal static class NuGetUtilities { private const string RepositoryRegistryKeyPath = @"SOFTWARE\NuGet\Repository"; /// <summary> /// Get local repository folder path from registory: HKLM\Software\NuGet\Repository /// </summary> public static string GetPackageRepositoryPath(string repositoryName) { Debug.Assert(!string.IsNullOrEmpty(repositoryName)); using (RegistryKey key = Registry.LocalMachine.OpenSubKey(NuGetUtilities.RepositoryRegistryKeyPath)) { return key?.GetValue(repositoryName) as string; } } /// <summary> /// Ensures the appropriate version of the specified packages are installed. If an existing version of the package /// already exists the following will happen: /// If a semantically compatible version already exists, no change is made to the package. /// If an older major version exists, a warning is logged and the package is upgraded. /// If an older minor/build version exists, an information message is logged and the package is upgraded. /// If a newer major version exists, a warning is logged and no change is made to the package. /// </summary> public static async Task InstallPackagesAsync( Dictionary<string, string> packages, string extensionId, ConnectedServiceLogger logger, Project project, IVsPackageInstallerServices packageInstallerServices, IVsPackageInstaller packageInstaller) { Dictionary<string, string> packagesToInstall = new Dictionary<string, string>(); await NuGetUtilities.InstallPackagesAsync( project, packages, (packageId, packageVersion) => { packagesToInstall.Add(packageId, packageVersion); return Task.FromResult<object>(null); }, logger, packageInstallerServices); if (packagesToInstall.Any()) { packageInstaller.InstallPackagesFromVSExtensionRepository(extensionId, false, false, project, packagesToInstall); } } /// <summary> /// Uninstall the packages that exist in the project. /// </summary> public static async Task UninstallPackagesAsync( Project targetProject, ISet<string> packages, Func<string, Task> uninstallPackage, ConnectedServiceLogger logger, IVsPackageInstallerServices packageInstallerServices) { IEnumerable<IVsPackageMetadata> installedPackages = packageInstallerServices.GetInstalledPackages(targetProject); foreach (string packageId in packages) { IVsPackageMetadata installedPackage = installedPackages.FirstOrDefault(p => p.Id == packageId); if (installedPackage != null) { await logger.WriteMessageAsync( LoggerMessageCategory.Information, Resource.LogMessage_RemovingNuGetPackage, packageId, installedPackage.VersionString); await uninstallPackage(packageId); } } } /// <summary> /// Ensures the appropriate version of the specified packages are installed. If an existing version of the package /// already exists the following will happen: /// If a semantically compatible version already exists, no change is made to the package. /// If an older major version exists, a warning is logged and the package is upgraded. /// If an older minor/build version exists, an information message is logged and the package is upgraded. /// If a newer major version exists, a warning is logged and no change is made to the package. /// </summary> public static async Task InstallPackagesAsync( Project targetProject, Dictionary<string, string> packages, Func<string, string, Task> installPackage, ConnectedServiceLogger logger, IVsPackageInstallerServices packageInstallerServices) { IEnumerable<IVsPackageMetadata> installedPackages; try { installedPackages = packageInstallerServices.GetInstalledPackages(targetProject); } catch (ArgumentException) { // This happens for C++ projects installedPackages = new List<IVsPackageMetadata>(); } foreach (KeyValuePair<string, string> requiredPackage in packages) { IVsPackageMetadata installedPackage = installedPackages.FirstOrDefault(p => p.Id == requiredPackage.Key); if (installedPackage == null) { // The package does not exist - notify and install the package. await logger.WriteMessageAsync( LoggerMessageCategory.Information, Resource.LogMessage_AddingNuGetPackage, requiredPackage.Key, requiredPackage.Value); } else { Version installedVersion = NuGetUtilities.GetVersion(installedPackage.VersionString); Version requiredVersion = NuGetUtilities.GetVersion(requiredPackage.Value); if (installedVersion == null || requiredVersion == null) { // Unable to parse the version - continue. continue; } else if (installedVersion.Major < requiredVersion.Major) { // An older potentially non-compatible version of the package already exists - warn and upgrade the package. await logger.WriteMessageAsync( LoggerMessageCategory.Warning, Resource.LogMessage_OlderMajorVersionNuGetPackageExists, requiredPackage.Key, installedPackage.VersionString, requiredPackage.Value); } else if (installedVersion.Major > requiredVersion.Major) { // A newer potentially non-compatible version of the package already exists - warn and continue. await logger.WriteMessageAsync( LoggerMessageCategory.Warning, Resource.LogMessage_NewerMajorVersionNuGetPackageExists, requiredPackage.Key, requiredPackage.Value, installedPackage.VersionString); continue; } else if (installedVersion >= requiredVersion) { // A semantically compatible version of the package already exists - continue. continue; } else { // An older semantically compatible version of the package exists - notify and upgrade the package. await logger.WriteMessageAsync( LoggerMessageCategory.Information, Resource.LogMessage_UpgradingNuGetPackage, requiredPackage.Key, installedPackage.VersionString, requiredPackage.Value); } } await installPackage(requiredPackage.Key, requiredPackage.Value); } } private static Version GetVersion(string versionString) { Version version; int index = versionString.IndexOfAny(new char[] { '-', '+' }); if (index != -1) { // Ignore any pre-release/build versions - they are not taken into account when comparing versions. versionString = versionString.Substring(0, index); } if (!Version.TryParse(versionString, out version)) { Debug.Fail("Unable to parse the NuGet package version " + versionString); } return version; } } }
//------------------------------------------------------------------------------ // <copyright file="UpWmlMobileTextWriter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Web.Mobile; using System.Web.UI.MobileControls; using System.Security.Permissions; using SR=System.Web.UI.MobileControls.Adapters.SR; #if COMPILING_FOR_SHIPPED_SOURCE using Adapters=System.Web.UI.MobileControls.ShippedAdapterSource; namespace System.Web.UI.MobileControls.ShippedAdapterSource #else using Adapters=System.Web.UI.MobileControls.Adapters; namespace System.Web.UI.MobileControls.Adapters #endif { /* * UpWmlMobileTextWriter class. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class UpWmlMobileTextWriter : WmlMobileTextWriter { private int _screenWidth; private int _screenHeight; private bool _inHyperlink = false; private bool _inPostBack = false; private bool _inSoftkey = false; private Alignment _lastAlignment = Alignment.Left; private Wrapping _lastWrapping = Wrapping.Wrap; private int _currentCardIndex = -1; private ArrayList _cards = new ArrayList(); private int _currentCardAnchorCount = 0; private int _currentCardPostBacks = 0; private int _currentCardSubmits = 0; private bool _canRenderMixedSelects = false; private bool _requiresOptionSubmitCard = false; private int _optionSubmitCardIndex = 0; private String _optionMenuName = null; private String _linkText = null; private String _targetUrl = null; private String _softkeyLabel = null; private bool _encodeUrl = false; private bool _useMenuOptionTitle = false; /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.UpWmlMobileTextWriter"]/*' /> public UpWmlMobileTextWriter(TextWriter writer, MobileCapabilities device, MobilePage page) : base(writer, device, page) { _screenWidth = device.ScreenCharactersWidth; _screenHeight = device.ScreenCharactersHeight; _canRenderMixedSelects = device.CanRenderMixedSelects; } private UpCard CurrentCard { get { return (UpCard)_cards[_currentCardIndex]; } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.BeginForm"]/*' /> public override void BeginForm(Form form) { ResetState(); if (AnalyzeMode) { AllocateNewCard(); base.BeginForm(form); } else { if (form == form.MobilePage.ActiveForm) { PreRenderActiveForm(); } base.BeginForm(form); RenderCardOpening(0); } } private static readonly int _filePathSuffixLength = Constants.UniqueFilePathSuffixVariableWithoutEqual.Length + 1; private int _sessionCount = -1; private int SessionCount { get { if (_sessionCount == -1) { _sessionCount = 0; String filePathSuffix = Page.Request.QueryString[Constants.UniqueFilePathSuffixVariableWithoutEqual]; if (filePathSuffix != null && filePathSuffix.Length == _filePathSuffixLength) { Char c = filePathSuffix[_filePathSuffixLength - 1]; if (Char.IsDigit(c)) { _sessionCount = (int)Char.GetNumericValue(c); } } } return _sessionCount; } } private bool RequiresLoopDetectionCard { get { IDictionary dictionary = Page.Adapter.CookielessDataDictionary; if((dictionary != null) && (dictionary.Count > 0)) { return true; } return SessionCount == 9; } } private void PreRenderActiveForm() { if (Device.RequiresUniqueFilePathSuffix && RequiresLoopDetectionCard) { Debug.Assert(!AnalyzeMode); Write(String.Format(CultureInfo.InvariantCulture, _loopDetectionCard, Page.ActiveForm.ClientID)); } } private String _cachedFormQueryString; /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.CalculateFormQueryString"]/*' /> protected override String CalculateFormQueryString() { if(_cachedFormQueryString != null) { return _cachedFormQueryString; } String queryString = null; if (CurrentForm.Method != FormMethod.Get) { queryString = Page.QueryStringText; } if (Device.RequiresUniqueFilePathSuffix) { String ufps = Page.UniqueFilePathSuffix; if(this.HasFormVariables) { if (SessionCount == 9) { ufps += '0'; } else { ufps += (SessionCount + 1).ToString(CultureInfo.InvariantCulture); } } if (queryString != null && queryString.Length > 0) { queryString = String.Concat(ufps, "&", queryString); } else { queryString = ufps; } } _cachedFormQueryString = queryString; return queryString; } private const String _loopDetectionCard = "<card ontimer=\"#{0}\"><onevent type=\"onenterbackward\"><prev /></onevent><timer value=\"1\" /></card>"; internal override bool ShouldWriteFormID(Form form) { if (RequiresLoopDetectionCard) { return true; } return base.ShouldWriteFormID(form); } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.EndForm"]/*' /> public override void EndForm() { if (AnalyzeMode) { CheckRawOutput(); CurrentCard.AnchorCount = _currentCardAnchorCount; base.EndForm(); } else { RenderCardClosing(_currentCardIndex); base.EndForm(); } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderEndForm"]/*' /> protected override void RenderEndForm() { base.RenderEndForm(); if (_requiresOptionSubmitCard) { Write("<card id=\""); Write(_postBackCardPrefix); Write("0"); Write(_optionSubmitCardIndex++); WriteLine("\">"); Write("<onevent type=\"onenterforward\">"); RenderGoAction(null, _postBackEventArgumentVarName, WmlPostFieldType.Variable, true); WriteLine("</onevent>"); WriteLine("<onevent type=\"onenterbackward\"><prev /></onevent>"); WriteLine("</card>"); } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderText"]/*' /> public override void RenderText(String text, bool breakAfter, bool encodeText) { if (AnalyzeMode) { if (CurrentCard.HasInputElements && !Device.CanRenderAfterInputOrSelectElement) { BeginNextCard(); } CheckRawOutput(); if (_inHyperlink || _inPostBack) { // When analyzing, accumulate link text for use in figuring // out softkey. if (_inSoftkey) { _linkText += text; } } else { // Text cannot come after a menu. if (CurrentCard.RenderAsMenu) { CurrentCard.RenderAsMenu = false; CurrentCard.MenuCandidate = false; } else if (CurrentCard.MenuCandidate) { // Calculate weight of static items before a menu. // This is used to check for screens that scroll past their // initial content. int weight = text != null ? text.Length : 0; if (breakAfter) { weight = ((weight - 1) / _screenWidth + 1) * _screenWidth; } CurrentCard.StaticItemsWeight += weight; } } } else { bool willRenderText = false; if (_inHyperlink || _inPostBack) { // If rendering in menu, simply accumulate text. if (CurrentCard.RenderAsMenu) { _linkText += text; } else if (!CurrentCard.UsesDefaultSubmit) { willRenderText = true; } } else { willRenderText = true; } if (willRenderText) { // Some browsers that // RendersBreakBeforeWmlSelectAndInput have the odd behavior // of *not* rendering a break if there is nothing on the // card before it, and entering an explicit <br> creates two // breaks. Therefore, we just render a &nbsp; in this // situation. if (!CurrentCard.RenderedTextElementYet && Device.RendersBreakBeforeWmlSelectAndInput && !((WmlPageAdapter)Page.Adapter).IsKDDIPhone()) { CurrentCard.RenderedTextElementYet = true; if (breakAfter && (text != null && text.Length == 0)) { base.RenderText("&nbsp;", false, false); } } base.RenderText(text, breakAfter, encodeText); } } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderBeginHyperlink"]/*' /> public override void RenderBeginHyperlink(String targetUrl, bool encodeUrl, String softkeyLabel, bool implicitSoftkeyLabel, bool mapToSoftkey) { if (_inHyperlink || _inPostBack) { throw new Exception(); } // AUI 4137 if (targetUrl != null && targetUrl.Length > 0 && targetUrl[0] != '#') { targetUrl = Page.MakePathAbsolute(targetUrl); } if (AnalyzeMode) { if (CurrentCard.HasInputElements && !Device.CanRenderAfterInputOrSelectElement) { BeginNextCard(); } CheckRawOutput(); // Try to map to softkey if possible. if (mapToSoftkey && CurrentCard.SoftkeysUsed < NumberOfSoftkeys) { _inSoftkey = true; _targetUrl = targetUrl; _softkeyLabel = softkeyLabel; _encodeUrl = encodeUrl; _linkText = String.Empty; } } else { if (CurrentCard.RenderAsMenu) { if (!CurrentCard.MenuOpened) { OpenMenu(); } // In menu mode, actual rendering is done on RenderEndHyperlink, // when we have all available info. _targetUrl = targetUrl; _softkeyLabel = softkeyLabel; _useMenuOptionTitle = mapToSoftkey && !implicitSoftkeyLabel; _encodeUrl = encodeUrl; _linkText = String.Empty; } else if (!CurrentCard.UsesDefaultSubmit) { base.RenderBeginHyperlink(targetUrl, encodeUrl, softkeyLabel, implicitSoftkeyLabel, mapToSoftkey); } } _inHyperlink = true; } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderEndHyperlink"]/*' /> public override void RenderEndHyperlink(bool breakAfter) { if (!_inHyperlink) { throw new Exception(); } _inHyperlink = false; if (AnalyzeMode) { CheckRawOutput(); if (CurrentCard.MenuCandidate) { CurrentCard.RenderAsMenu = true; } CurrentCard.HasNonStaticElements = true; if (_inSoftkey) { // Add a softkey if possible. _inSoftkey = false; UpHyperlinkSoftkey softkey = new UpHyperlinkSoftkey(); softkey.TargetUrl = _targetUrl; softkey.EncodeUrl = _encodeUrl; if (_softkeyLabel == null || _softkeyLabel.Length == 0) { _softkeyLabel = _linkText; } softkey.Label = _softkeyLabel; CurrentCard.Softkeys[CurrentCard.SoftkeysUsed++] = softkey; } } else { if (CurrentCard.RenderAsMenu) { Write("<option onpick=\""); if (_targetUrl.StartsWith(Constants.FormIDPrefix, StringComparison.Ordinal)) { // no encoding needed if pointing to another form id Write(_targetUrl); } else if (!_encodeUrl) { Write(EscapeAmpersand(_targetUrl)); } else { WriteEncodedUrl(_targetUrl); } Write("\""); if (_useMenuOptionTitle && IsValidSoftkeyLabel(_softkeyLabel)) { WriteTextEncodedAttribute("title", _softkeyLabel); } Write(">"); WriteEncodedText(_linkText); WriteEndTag("option"); } else if (!CurrentCard.UsesDefaultSubmit) { base.RenderEndHyperlink(breakAfter); } } _currentCardAnchorCount++; if (!AnalyzeMode && _currentCardAnchorCount == CurrentCard.AnchorCount && _currentCardIndex < _cards.Count - 1) { BeginNextCard(); } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderTextBox"]/*' /> public override void RenderTextBox(String id, String value, String format, String title, bool password, int size, int maxLength, bool generateRandomID, bool breakAfter) { if (AnalyzeMode) { CheckRawOutput(); // If an anchor precedes this control, then break to the // next card. if (_currentCardAnchorCount > 0) { BeginNextCard(); } else if (CurrentCard.HasInputElements && (!Device.CanRenderInputAndSelectElementsTogether || !Device.CanRenderAfterInputOrSelectElement)) { BeginNextCard(); } CurrentCard.RenderAsMenu = false; CurrentCard.MenuCandidate = false; CurrentCard.HasNonStaticElements = true; CurrentCard.HasInputElements = true; } else { // Don't write breaks after textboxes on UP. base.RenderTextBox(id, value, format, title, password, size, maxLength, generateRandomID, false); // If we can't render more than one input element on this card, and // there are no anchors left to render, break here. if (!Device.CanRenderAfterInputOrSelectElement && _currentCardIndex < _cards.Count - 1) { CurrentCard.NoOKLink = true; BeginNextCard(); } else if (CurrentCard.AnchorCount == 0 && _currentCardIndex < _cards.Count - 1 && !Device.CanRenderInputAndSelectElementsTogether) { CurrentCard.NoOKLink = true; BeginNextCard(); } } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderImage"]/*' /> public override void RenderImage(String source, String localSource, String alternateText, bool breakAfter) { if (AnalyzeMode) { if (CurrentCard.HasInputElements && !Device.CanRenderAfterInputOrSelectElement) { BeginNextCard(); } CheckRawOutput(); if (_inHyperlink || _inPostBack) { CurrentCard.RenderAsMenu = false; CurrentCard.MenuCandidate = false; } else { if (CurrentCard.RenderAsMenu) { // Images cannot come after a menu on a card. CurrentCard.RenderAsMenu = false; CurrentCard.MenuCandidate = false; } else if (CurrentCard.MenuCandidate) { CurrentCard.StaticItemsWeight += _screenWidth; } } } else { // AUI 4137 if (source != null) { source = Page.MakePathAbsolute(source); } if (_inHyperlink || _inPostBack) { if (CurrentCard.RenderAsMenu) { _linkText += alternateText; } else if (!CurrentCard.UsesDefaultSubmit) { base.RenderImage(source, localSource, alternateText, breakAfter); } } else { base.RenderImage(source, localSource, alternateText, breakAfter); } } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderBeginPostBack"]/*' /> public override void RenderBeginPostBack(String softkeyLabel, bool implicitSoftkeyLabel, bool mapToSoftkey) { if (_inHyperlink || _inPostBack) { throw new Exception(); } if (AnalyzeMode) { if (CurrentCard.HasInputElements && !Device.CanRenderAfterInputOrSelectElement) { BeginNextCard(); } CheckRawOutput(); // Try to map to softkey if possible. if (mapToSoftkey && CurrentCard.SoftkeysUsed < NumberOfSoftkeys) { _inSoftkey = true; _softkeyLabel = softkeyLabel; _linkText = String.Empty; } } else { if (CurrentCard.RenderAsMenu) { if (!CurrentCard.MenuOpened) { OpenMenu(); } // In menu mode, actual rendering is done on RenderEndPostBack, // when we have all available info. _softkeyLabel = softkeyLabel; _useMenuOptionTitle = mapToSoftkey && !implicitSoftkeyLabel; _linkText = String.Empty; } else if (!CurrentCard.UsesDefaultSubmit) { base.RenderBeginPostBack(softkeyLabel, implicitSoftkeyLabel, mapToSoftkey); } } _inPostBack = true; } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderEndPostBack"]/*' /> public override void RenderEndPostBack(String target, String argument, WmlPostFieldType postBackType, bool includeVariables, bool breakAfter) { if (!_inPostBack) { throw new Exception(); } _inPostBack = false; if (AnalyzeMode) { CheckRawOutput(); if (CurrentCard.MenuCandidate) { // If all postback menu items go to one target, we can write the do // to hit that target. Otherwise, we must post back to the form. if (CurrentCard.RenderAsMenu) { if (CurrentCard.MenuTarget != target) { CurrentCard.MenuTarget = null; } } else { CurrentCard.MenuTarget = target; CurrentCard.RenderAsMenu = true; } } CurrentCard.HasNonStaticElements = true; if (_inSoftkey) { // Map to softkey. _inSoftkey = false; UpPostBackSoftkey softkey = new UpPostBackSoftkey(); softkey.Target = target; softkey.Argument = argument; softkey.PostBackType = postBackType; softkey.IncludeVariables = includeVariables; if (_softkeyLabel == null || _softkeyLabel.Length == 0) { _softkeyLabel = _linkText; } softkey.Label = _softkeyLabel; CurrentCard.Softkeys[CurrentCard.SoftkeysUsed++] = softkey; } AnalyzePostBack(includeVariables, postBackType); } else { if (CurrentCard.RenderAsMenu) { // Render as a menu item. WriteBeginTag("option"); if (!_canRenderMixedSelects) { if (_useMenuOptionTitle && IsValidSoftkeyLabel(_softkeyLabel)) { WriteTextEncodedAttribute("title", _softkeyLabel); } _requiresOptionSubmitCard = true; Write("><onevent type=\"onpick\"><go href=\"#"); Write(_postBackCardPrefix); Write("0"); Write(_optionSubmitCardIndex); Write("\">"); Write("<setvar name=\""); Write(_postBackEventTargetVarName); Write("\" value=\""); if (_optionMenuName != null) { Write(_optionMenuName); } Write("\" />"); Write("<setvar name=\""); Write(_postBackEventArgumentVarName); Write("\" value=\""); } else { Write(" value=\""); } if (CurrentCard.MenuTarget != null) { if (argument != null) { WriteEncodedText(argument); } } else { WriteEncodedText(target); if (argument != null) { Write(","); WriteEncodedText(argument); } } if (!_canRenderMixedSelects) { Write("\" /></go></onevent>"); } else { Write("\""); if (_useMenuOptionTitle && IsValidSoftkeyLabel(_softkeyLabel)) { WriteTextEncodedAttribute("title", _softkeyLabel); } Write(">"); } WriteEncodedText(_linkText); WriteEndTag("option"); } else if (!CurrentCard.UsesDefaultSubmit) { base.RenderEndPostBack(target, argument, postBackType, includeVariables, breakAfter); } } _currentCardAnchorCount++; if (!AnalyzeMode && _currentCardAnchorCount == CurrentCard.AnchorCount && _currentCardIndex < _cards.Count - 1) { BeginNextCard(); } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.BeginCustomMarkup"]/*' /> public override void BeginCustomMarkup() { if (!AnalyzeMode && !CurrentCard.MenuOpened) { EnsureLayout(); } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.AnalyzePostBack"]/*' /> protected override void AnalyzePostBack(bool includeVariables, WmlPostFieldType postBackType) { base.AnalyzePostBack(includeVariables, postBackType); if (CurrentForm.Action.Length > 0) { if (postBackType == WmlPostFieldType.Submit) { _currentCardSubmits++; CurrentCard.ExternalSubmitMenu = true; } else { _currentCardPostBacks++; } if (_currentCardPostBacks > 0 && _currentCardSubmits > 0) { // Posts to more than one target, so we can't use a menu card. CurrentCard.RenderAsMenu = false; CurrentCard.MenuCandidate = false; } } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderBeginSelect"]/*' /> public override void RenderBeginSelect(String name, String iname, String ivalue, String title, bool multiSelect) { if (AnalyzeMode) { CheckRawOutput(); if (_currentCardAnchorCount > 0) { // If an anchor precedes this control, then break to the // next card. BeginNextCard(); } else if (CurrentCard.HasInputElements && (!Device.CanRenderInputAndSelectElementsTogether || !Device.CanRenderAfterInputOrSelectElement)) { BeginNextCard(); } CurrentCard.RenderAsMenu = false; CurrentCard.MenuCandidate = false; CurrentCard.HasNonStaticElements = true; CurrentCard.HasInputElements = true; } else { base.RenderBeginSelect(name, iname, ivalue, title, multiSelect); } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderEndSelect"]/*' /> public override void RenderEndSelect(bool breakAfter) { if (AnalyzeMode) { CheckRawOutput(); } else { // Don't write breaks after selects on UP. base.RenderEndSelect(false); // If we can't render more than one input element on this card, and // there are no anchors left to render, break here. if (!Device.CanRenderAfterInputOrSelectElement && _currentCardIndex < _cards.Count - 1) { CurrentCard.NoOKLink = true; BeginNextCard(); } else if (CurrentCard.AnchorCount == 0 && _currentCardIndex < _cards.Count - 1 && !Device.CanRenderInputAndSelectElementsTogether) { CurrentCard.NoOKLink = true; BeginNextCard(); } } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderSelectOption"]/*' /> public override void RenderSelectOption(String text) { if (AnalyzeMode) { CheckRawOutput(); } else { base.RenderSelectOption(text); } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.RenderSelectOption1"]/*' /> public override void RenderSelectOption(String text, String value) { if (AnalyzeMode) { CheckRawOutput(); } else { base.RenderSelectOption(text, value); } } private void OpenMenu() { // Close any character formatting tags before starting a <do>. CloseCharacterFormat(); String menuTarget; String menuTargetClientID; WmlPostFieldType postFieldType; if (CurrentCard.ExternalSubmitMenu) { menuTarget = null; menuTargetClientID = null; postFieldType = WmlPostFieldType.Submit; } else { if (CurrentCard.MenuTarget != null) { menuTarget = CurrentCard.MenuTarget; if (menuTarget.IndexOf(":", StringComparison.Ordinal) >= 0) { menuTargetClientID = menuTarget.Replace(":", "_"); } else { menuTargetClientID = menuTarget; } } else { menuTarget = CurrentForm.UniqueID; menuTargetClientID = CurrentForm.ClientID; } postFieldType = WmlPostFieldType.Variable; } if (!_canRenderMixedSelects) { _optionMenuName = menuTarget; menuTargetClientID = null; } else { String GoLabel = SR.GetString(SR.WmlMobileTextWriterGoLabel); RenderDoEvent("accept", menuTarget, menuTargetClientID != null ? MapClientIDToShortName(menuTargetClientID, false) : null, postFieldType, GoLabel, true); } base.RenderBeginSelect(menuTargetClientID, null, null, null, false); CurrentCard.MenuOpened = true; } private void CloseMenu() { base.RenderEndSelect(false); CurrentCard.MenuOpened = false; } // Overriden to convert relative file paths to absolute file paths, // due to a redirection issue on UP phones. /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.CalculateFormPostBackUrl"]/*' /> protected override String CalculateFormPostBackUrl(bool externalSubmit, ref bool encode) { String url = CurrentForm.Action; if (externalSubmit && url.Length > 0) { // Not only do we need to resolve the URL, but we need to make it absolute. url = Page.MakePathAbsolute(CurrentForm.ResolveUrl(url)); encode = false; } else { url = Page.AbsoluteFilePath; encode = true; } return url; } // Captures raw output written to the writers during analyze mode. private void CheckRawOutput() { Debug.Assert(AnalyzeMode); EmptyTextWriter innerWriter = (EmptyTextWriter)InnerWriter; if (innerWriter.NonWhiteSpaceWritten) { CurrentCard.RenderAsMenu = false; CurrentCard.MenuCandidate = false; } innerWriter.Reset(); } // Overriden to always write the "align" or "wrap" attributes when // they are changing, even if they are set to defaults. /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.OpenParagraph"]/*' /> protected override void OpenParagraph(WmlLayout layout, bool writeAlignment, bool writeWrapping) { base.OpenParagraph(layout, writeAlignment || layout.Align != _lastAlignment, writeWrapping || layout.Wrap != _lastWrapping); _lastAlignment = layout.Align; _lastWrapping = layout.Wrap; } // Resets writer state between forms. private void ResetState() { if (AnalyzeMode) { _currentCardPostBacks = 0; _currentCardSubmits = 0; _inHyperlink = false; _inPostBack = false; _inSoftkey = false; if (_cards.Count > 0) { _cards.Clear(); } } _currentCardAnchorCount = 0; _currentCardIndex = 0; _currentCardPostBacks = 0; _currentCardSubmits = 0; _requiresOptionSubmitCard = false; } private UpCard AllocateNewCard() { UpCard card = new UpCard(); card.Softkeys = new UpSoftkey[NumberOfSoftkeys]; _cards.Add(card); return card; } // Analyze an individual card. private void PostAnalyzeCard(int cardIndex) { UpCard card = (UpCard)_cards[cardIndex]; if (card.RenderAsMenu) { // If the card is the last card, and has only // one anchor that can be mapped to a softkey, // ignore the if (card.AnchorCount == 1 && cardIndex == _cards.Count - 1 && card.SoftkeysUsed == 1) { card.RenderAsMenu = false; } // If the card has a lot of static content followed by // a number of links, don't render it as a menu card, // because the card would scroll off the static content // to get to the menu. else if (card.StaticItemsWeight >= 3 * _screenWidth) { card.RenderAsMenu = false; } } } /// <include file='doc\UpWmlMobileTextWriter.uex' path='docs/doc[@for="UpWmlMobileTextWriter.PostAnalyzeForm"]/*' /> protected override void PostAnalyzeForm() { base.PostAnalyzeForm(); for(int i = 0; i < _cards.Count; i++) { PostAnalyzeCard(i); } // If the last card ends with an input element and an anchor // then use the anchor as a do tag to submit the form, and // don't render as a separate anchor (otherwise, the user would // see an extra screen at the end with a single anchor) UpCard lastCard = CurrentCard; if (lastCard.HasInputElements && _currentCardAnchorCount >= 1 && _currentCardAnchorCount <= Device.DefaultSubmitButtonLimit) { lastCard.UsesDefaultSubmit = true; } } private void RenderCardOpening(int cardIndex) { UpCard card = (UpCard)_cards[cardIndex]; if (card.RenderAsMenu) { } else { // Render softkeys if (card.HasNonStaticElements) { for (int i = 0; i < card.SoftkeysUsed; i++) { RenderSoftkey(i == 0 ? "accept" : "options", card.Softkeys[i]); } } else if (cardIndex == _cards.Count - 1) { // Render the last card with an extra <do>, so that // it overrides the default function of the OK button, // which is to go back a screen. //EnsureLayout(); Write("<do type=\"accept\"><noop /></do>"); } } } private void RenderCardClosing(int cardIndex) { UpCard card = (UpCard)_cards[cardIndex]; if (cardIndex < _cards.Count - 1 && !card.NoOKLink) { // Add a link to go to the next card. UpCard nextCard = (UpCard)_cards[cardIndex + 1]; String OkLabel = SR.GetString(SR.WmlMobileTextWriterOKLabel); RenderBeginHyperlink("#" + nextCard.Id, false, OkLabel, true, true); RenderText(OkLabel); RenderEndHyperlink(true); } if (card.RenderAsMenu) { CloseMenu(); } } private void BeginNextCard() { if (AnalyzeMode) { // Add a softkey on the current card, to go to the new card. String nextCardId = "card" + (_currentCardIndex + 1).ToString(CultureInfo.InvariantCulture); UpHyperlinkSoftkey softkey = new UpHyperlinkSoftkey(); softkey.TargetUrl = "#" + nextCardId; softkey.EncodeUrl = false; softkey.Label = "OK"; SetPrimarySoftkey(softkey); CurrentCard.AnchorCount = _currentCardAnchorCount; UpCard card = AllocateNewCard(); card.Id = nextCardId; _currentCardIndex++; } else { RenderCardClosing(_currentCardIndex); CloseParagraph(); WriteEndTag("card"); WriteLine(); _currentCardIndex++; _lastAlignment = Alignment.Left; _lastWrapping = Wrapping.NoWrap; WriteBeginTag("card"); WriteAttribute("id", CurrentCard.Id); String formTitle = CurrentForm.Title; if (formTitle != null && formTitle.Length > 0) { WriteTextEncodedAttribute("title", formTitle); } WriteLine(">"); RenderCardOpening(_currentCardIndex); } _currentCardAnchorCount = 0; _currentCardPostBacks = 0; _currentCardSubmits = 0; } private void SetPrimarySoftkey(UpSoftkey softkey) { for (int i = NumberOfSoftkeys - 1; i > 0; i--) { CurrentCard.Softkeys[i] = CurrentCard.Softkeys[i - 1]; } CurrentCard.Softkeys[0] = softkey; if (CurrentCard.SoftkeysUsed < NumberOfSoftkeys) { CurrentCard.SoftkeysUsed++; } } private void RenderSoftkey(String doType, UpSoftkey softkey) { UpHyperlinkSoftkey linkSoftkey = softkey as UpHyperlinkSoftkey; if (linkSoftkey != null) { WriteBeginTag("do"); WriteAttribute("type", doType); WriteTextEncodedAttribute("label", linkSoftkey.Label); Write(">"); WriteBeginTag("go"); Write(" href=\""); if (linkSoftkey.EncodeUrl) { WriteEncodedUrl(linkSoftkey.TargetUrl); } else { Write(EscapeAmpersand(linkSoftkey.TargetUrl)); } Write("\" />"); WriteEndTag("do"); return; } UpPostBackSoftkey postBackSoftkey = softkey as UpPostBackSoftkey; if (postBackSoftkey != null) { RenderDoEvent(doType, postBackSoftkey.Target, postBackSoftkey.Argument, postBackSoftkey.PostBackType, postBackSoftkey.Label, postBackSoftkey.IncludeVariables); return; } } private class UpSoftkey { public String Label; } private class UpHyperlinkSoftkey : UpSoftkey { public String TargetUrl; public bool EncodeUrl; } private class UpPostBackSoftkey : UpSoftkey { public String Target; public String Argument; public WmlPostFieldType PostBackType; public bool IncludeVariables; } private class UpCard { public String Id; public bool MenuCandidate = true; public bool RenderAsMenu = false; public int StaticItemsWeight = 0; public bool HasNonStaticElements = false; public bool MenuOpened = false; public bool HasInputElements = false; public bool UsesDefaultSubmit = false; public int SoftkeysUsed = 0; public UpSoftkey[] Softkeys = null; public int AnchorCount = 0; public String MenuTarget = null; public bool ExternalSubmitMenu = false; public bool NoOKLink = false; public bool RenderedTextElementYet = false; } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileXMLBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileXMLNamespaceMapping))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileXMLProfileXMLStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileXMLProfileNamespaceMappingSequence))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStringArray))] public partial class LocalLBProfileXML : iControlInterface { public LocalLBProfileXML() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_namespace_mappings //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void add_namespace_mappings( string [] profile_names, LocalLBProfileXMLNamespaceMapping [] [] namespace_mappings ) { this.Invoke("add_namespace_mappings", new object [] { profile_names, namespace_mappings}); } public System.IAsyncResult Beginadd_namespace_mappings(string [] profile_names,LocalLBProfileXMLNamespaceMapping [] [] namespace_mappings, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_namespace_mappings", new object[] { profile_names, namespace_mappings}, callback, asyncState); } public void Endadd_namespace_mappings(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_xpath_queries //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void add_xpath_queries( string [] profile_names, string [] [] xpath_queries ) { this.Invoke("add_xpath_queries", new object [] { profile_names, xpath_queries}); } public System.IAsyncResult Beginadd_xpath_queries(string [] profile_names,string [] [] xpath_queries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_xpath_queries", new object[] { profile_names, xpath_queries}, callback, asyncState); } public void Endadd_xpath_queries(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void create( string [] profile_names ) { this.Invoke("create", new object [] { profile_names}); } public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_abort_on_error_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_abort_on_error_state( string [] profile_names ) { object [] results = this.Invoke("get_abort_on_error_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_abort_on_error_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_abort_on_error_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_abort_on_error_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileXMLProfileXMLStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBProfileXMLProfileXMLStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBProfileXMLProfileXMLStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileXMLProfileXMLStatistics)(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_maximum_buffer_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_maximum_buffer_size( string [] profile_names ) { object [] results = this.Invoke("get_maximum_buffer_size", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_maximum_buffer_size(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_maximum_buffer_size", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_maximum_buffer_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_multiple_query_matches_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_multiple_query_matches_state( string [] profile_names ) { object [] results = this.Invoke("get_multiple_query_matches_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_multiple_query_matches_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_multiple_query_matches_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_multiple_query_matches_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_namespace_mappings //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileXMLProfileNamespaceMappingSequence [] get_namespace_mappings( string [] profile_names ) { object [] results = this.Invoke("get_namespace_mappings", new object [] { profile_names}); return ((LocalLBProfileXMLProfileNamespaceMappingSequence [])(results[0])); } public System.IAsyncResult Beginget_namespace_mappings(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_namespace_mappings", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileXMLProfileNamespaceMappingSequence [] Endget_namespace_mappings(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileXMLProfileNamespaceMappingSequence [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileXMLProfileXMLStatistics get_statistics( string [] profile_names ) { object [] results = this.Invoke("get_statistics", new object [] { profile_names}); return ((LocalLBProfileXMLProfileXMLStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileXMLProfileXMLStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileXMLProfileXMLStatistics)(results[0])); } //----------------------------------------------------------------------- // get_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { object [] results = this.Invoke("get_statistics_by_virtual", new object [] { profile_names, virtual_names}); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_xpath_queries //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStringArray [] get_xpath_queries( string [] profile_names ) { object [] results = this.Invoke("get_xpath_queries", new object [] { profile_names}); return ((LocalLBProfileStringArray [])(results[0])); } public System.IAsyncResult Beginget_xpath_queries(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_xpath_queries", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileStringArray [] Endget_xpath_queries(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStringArray [])(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // remove_all_namespace_mappings //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void remove_all_namespace_mappings( string [] profile_names ) { this.Invoke("remove_all_namespace_mappings", new object [] { profile_names}); } public System.IAsyncResult Beginremove_all_namespace_mappings(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_namespace_mappings", new object[] { profile_names}, callback, asyncState); } public void Endremove_all_namespace_mappings(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_all_xpath_queries //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void remove_all_xpath_queries( string [] profile_names ) { this.Invoke("remove_all_xpath_queries", new object [] { profile_names}); } public System.IAsyncResult Beginremove_all_xpath_queries(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_xpath_queries", new object[] { profile_names}, callback, asyncState); } public void Endremove_all_xpath_queries(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_namespace_mappings //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void remove_namespace_mappings( string [] profile_names, LocalLBProfileXMLNamespaceMapping [] [] namespace_mappings ) { this.Invoke("remove_namespace_mappings", new object [] { profile_names, namespace_mappings}); } public System.IAsyncResult Beginremove_namespace_mappings(string [] profile_names,LocalLBProfileXMLNamespaceMapping [] [] namespace_mappings, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_namespace_mappings", new object[] { profile_names, namespace_mappings}, callback, asyncState); } public void Endremove_namespace_mappings(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_xpath_queries //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void remove_xpath_queries( string [] profile_names, string [] [] xpath_queries ) { this.Invoke("remove_xpath_queries", new object [] { profile_names, xpath_queries}); } public System.IAsyncResult Beginremove_xpath_queries(string [] profile_names,string [] [] xpath_queries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_xpath_queries", new object[] { profile_names, xpath_queries}, callback, asyncState); } public void Endremove_xpath_queries(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void reset_statistics( string [] profile_names ) { this.Invoke("reset_statistics", new object [] { profile_names}); } public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { profile_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void reset_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { this.Invoke("reset_statistics_by_virtual", new object [] { profile_names, virtual_names}); } public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_abort_on_error_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void set_abort_on_error_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_abort_on_error_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_abort_on_error_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_abort_on_error_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_abort_on_error_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_maximum_buffer_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void set_maximum_buffer_size( string [] profile_names, LocalLBProfileULong [] sizes ) { this.Invoke("set_maximum_buffer_size", new object [] { profile_names, sizes}); } public System.IAsyncResult Beginset_maximum_buffer_size(string [] profile_names,LocalLBProfileULong [] sizes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_maximum_buffer_size", new object[] { profile_names, sizes}, callback, asyncState); } public void Endset_maximum_buffer_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_multiple_query_matches_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileXML", RequestNamespace="urn:iControl:LocalLB/ProfileXML", ResponseNamespace="urn:iControl:LocalLB/ProfileXML")] public void set_multiple_query_matches_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_multiple_query_matches_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_multiple_query_matches_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_multiple_query_matches_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_multiple_query_matches_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileXML.NamespaceMapping", Namespace = "urn:iControl")] public partial class LocalLBProfileXMLNamespaceMapping { private string mapping_prefixField; public string mapping_prefix { get { return this.mapping_prefixField; } set { this.mapping_prefixField = value; } } private string mapping_namespaceField; public string mapping_namespace { get { return this.mapping_namespaceField; } set { this.mapping_namespaceField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileXML.ProfileNamespaceMappingSequence", Namespace = "urn:iControl")] public partial class LocalLBProfileXMLProfileNamespaceMappingSequence { private LocalLBProfileXMLNamespaceMapping [] valuesField; public LocalLBProfileXMLNamespaceMapping [] values { get { return this.valuesField; } set { this.valuesField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileXML.ProfileXMLStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBProfileXMLProfileXMLStatisticEntry { private string profile_nameField; public string profile_name { get { return this.profile_nameField; } set { this.profile_nameField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileXML.ProfileXMLStatistics", Namespace = "urn:iControl")] public partial class LocalLBProfileXMLProfileXMLStatistics { private LocalLBProfileXMLProfileXMLStatisticEntry [] statisticsField; public LocalLBProfileXMLProfileXMLStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeX509ChainHandle : System.Runtime.InteropServices.SafeHandle { internal SafeX509ChainHandle() : base(default(System.IntPtr), default(bool)) { } protected override bool ReleaseHandle() { return default(bool); } } } namespace System.Security.Cryptography.X509Certificates { public static partial class ECDsaCertificateExtensions { public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.ECDsa); } public static System.Security.Cryptography.ECDsa GetECDsaPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.ECDsa); } } [System.FlagsAttribute] public enum OpenFlags { IncludeArchived = 8, MaxAllowed = 2, OpenExistingOnly = 4, ReadOnly = 0, ReadWrite = 1, } public sealed partial class PublicKey { public PublicKey(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedData parameters, System.Security.Cryptography.AsnEncodedData keyValue) { } public System.Security.Cryptography.AsnEncodedData EncodedKeyValue { get { return default(System.Security.Cryptography.AsnEncodedData); } } public System.Security.Cryptography.AsnEncodedData EncodedParameters { get { return default(System.Security.Cryptography.AsnEncodedData); } } public System.Security.Cryptography.Oid Oid { get { return default(System.Security.Cryptography.Oid); } } } public static partial class RSACertificateExtensions { public static System.Security.Cryptography.RSA GetRSAPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.RSA); } public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(System.Security.Cryptography.RSA); } } public enum StoreLocation { CurrentUser = 1, LocalMachine = 2, } public enum StoreName { AddressBook = 1, AuthRoot = 2, CertificateAuthority = 3, Disallowed = 4, My = 5, Root = 6, TrustedPeople = 7, TrustedPublisher = 8, } public sealed partial class X500DistinguishedName : System.Security.Cryptography.AsnEncodedData { public X500DistinguishedName(byte[] encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.AsnEncodedData encodedDistinguishedName) { } public X500DistinguishedName(System.Security.Cryptography.X509Certificates.X500DistinguishedName distinguishedName) { } public X500DistinguishedName(string distinguishedName) { } public X500DistinguishedName(string distinguishedName, System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { } public string Name { get { return default(string); } } public string Decode(System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags flag) { return default(string); } public override string Format(bool multiLine) { return default(string); } } [System.FlagsAttribute] public enum X500DistinguishedNameFlags { DoNotUsePlusSign = 32, DoNotUseQuotes = 64, ForceUTF8Encoding = 16384, None = 0, Reversed = 1, UseCommas = 128, UseNewLines = 256, UseSemicolons = 16, UseT61Encoding = 8192, UseUTF8Encoding = 4096, } public sealed partial class X509BasicConstraintsExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509BasicConstraintsExtension() { } public X509BasicConstraintsExtension(bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) { } public X509BasicConstraintsExtension(System.Security.Cryptography.AsnEncodedData encodedBasicConstraints, bool critical) { } public bool CertificateAuthority { get { return default(bool); } } public bool HasPathLengthConstraint { get { return default(bool); } } public int PathLengthConstraint { get { return default(int); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Certificate : System.IDisposable { public X509Certificate() { } public X509Certificate(byte[] data) { } public X509Certificate(byte[] rawData, string password) { } public X509Certificate(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } [System.Security.SecurityCriticalAttribute] public X509Certificate(System.IntPtr handle) { } public X509Certificate(string fileName) { } public X509Certificate(string fileName, string password) { } public X509Certificate(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public System.IntPtr Handle {[System.Security.SecurityCriticalAttribute]get { return default(System.IntPtr); } } public string Issuer { get { return default(string); } } public string Subject { get { return default(string); } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public override bool Equals(object obj) { return default(bool); } public virtual bool Equals(System.Security.Cryptography.X509Certificates.X509Certificate other) { return default(bool); } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { return default(byte[]); } public virtual byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { return default(byte[]); } public virtual byte[] GetCertHash() { return default(byte[]); } public virtual string GetFormat() { return default(string); } public override int GetHashCode() { return default(int); } public virtual string GetKeyAlgorithm() { return default(string); } public virtual byte[] GetKeyAlgorithmParameters() { return default(byte[]); } public virtual string GetKeyAlgorithmParametersString() { return default(string); } public virtual byte[] GetPublicKey() { return default(byte[]); } public virtual byte[] GetSerialNumber() { return default(byte[]); } public override string ToString() { return default(string); } public virtual string ToString(bool fVerbose) { return default(string); } } public partial class X509Certificate2 : System.Security.Cryptography.X509Certificates.X509Certificate { public X509Certificate2() { } public X509Certificate2(byte[] rawData) { } public X509Certificate2(byte[] rawData, string password) { } public X509Certificate2(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(System.IntPtr handle) { } public X509Certificate2(string fileName) { } public X509Certificate2(string fileName, string password) { } public X509Certificate2(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public bool Archived { get { return default(bool); } set { } } public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get { return default(System.Security.Cryptography.X509Certificates.X509ExtensionCollection); } } public string FriendlyName { get { return default(string); } set { } } public bool HasPrivateKey { get { return default(bool); } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName IssuerName { get { return default(System.Security.Cryptography.X509Certificates.X500DistinguishedName); } } public System.DateTime NotAfter { get { return default(System.DateTime); } } public System.DateTime NotBefore { get { return default(System.DateTime); } } public System.Security.Cryptography.X509Certificates.PublicKey PublicKey { get { return default(System.Security.Cryptography.X509Certificates.PublicKey); } } public byte[] RawData { get { return default(byte[]); } } public string SerialNumber { get { return default(string); } } public System.Security.Cryptography.Oid SignatureAlgorithm { get { return default(System.Security.Cryptography.Oid); } } public System.Security.Cryptography.X509Certificates.X500DistinguishedName SubjectName { get { return default(System.Security.Cryptography.X509Certificates.X500DistinguishedName); } } public string Thumbprint { get { return default(string); } } public int Version { get { return default(int); } } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(byte[] rawData) { return default(System.Security.Cryptography.X509Certificates.X509ContentType); } public static System.Security.Cryptography.X509Certificates.X509ContentType GetCertContentType(string fileName) { return default(System.Security.Cryptography.X509Certificates.X509ContentType); } public string GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType nameType, bool forIssuer) { return default(string); } public override string ToString() { return default(string); } public override string ToString(bool verbose) { return default(string); } } public partial class X509Certificate2Collection : System.Security.Cryptography.X509Certificates.X509CertificateCollection { public X509Certificate2Collection() { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public new System.Security.Cryptography.X509Certificates.X509Certificate2 this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(int); } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(bool); } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType) { return default(byte[]); } public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password) { return default(byte[]); } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Find(System.Security.Cryptography.X509Certificates.X509FindType findType, object findValue, bool validOnly) { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } public new System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator); } public void Import(byte[] rawData) { } public void Import(byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Import(string fileName) { } public void Import(string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags) { } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2[] certificates) { } public void RemoveRange(System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates) { } } public sealed partial class X509Certificate2Enumerator : System.Collections.IEnumerator { internal X509Certificate2Enumerator() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Current { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } public partial class X509CertificateCollection { public X509CertificateCollection() { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public X509CertificateCollection(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public System.Security.Cryptography.X509Certificates.X509Certificate this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate); } set { } } public int Add(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(int); } public void AddRange(System.Security.Cryptography.X509Certificates.X509Certificate[] value) { } public void AddRange(System.Security.Cryptography.X509Certificates.X509CertificateCollection value) { } public bool Contains(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(bool); } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Certificate[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509CertificateCollection.X509CertificateEnumerator); } public override int GetHashCode() { return default(int); } public int IndexOf(System.Security.Cryptography.X509Certificates.X509Certificate value) { return default(int); } public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate value) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate value) { } public partial class X509CertificateEnumerator : System.Collections.IEnumerator { public X509CertificateEnumerator(System.Security.Cryptography.X509Certificates.X509CertificateCollection mappings) { } public System.Security.Cryptography.X509Certificates.X509Certificate Current { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } bool System.Collections.IEnumerator.MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } public partial class X509Chain : System.IDisposable { public X509Chain() { } public System.Security.Cryptography.X509Certificates.X509ChainElementCollection ChainElements { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElementCollection); } } public System.Security.Cryptography.X509Certificates.X509ChainPolicy ChainPolicy { get { return default(System.Security.Cryptography.X509Certificates.X509ChainPolicy); } set { } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainStatus { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatus[]); } } public Microsoft.Win32.SafeHandles.SafeX509ChainHandle SafeHandle { get { return default(Microsoft.Win32.SafeHandles.SafeX509ChainHandle); } } public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { return default(bool); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } } public partial class X509ChainElement { internal X509ChainElement() { } public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2); } } public System.Security.Cryptography.X509Certificates.X509ChainStatus[] ChainElementStatus { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatus[]); } } public string Information { get { return default(string); } } } public sealed partial class X509ChainElementCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal X509ChainElementCollection() { } public int Count { get { return default(int); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } public System.Security.Cryptography.X509Certificates.X509ChainElement this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElement); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(System.Security.Cryptography.X509Certificates.X509ChainElement[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public sealed partial class X509ChainElementEnumerator : System.Collections.IEnumerator { internal X509ChainElementEnumerator() { } public System.Security.Cryptography.X509Certificates.X509ChainElement Current { get { return default(System.Security.Cryptography.X509Certificates.X509ChainElement); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } } public sealed partial class X509ChainPolicy { public X509ChainPolicy() { } public System.Security.Cryptography.OidCollection ApplicationPolicy { get { return default(System.Security.Cryptography.OidCollection); } } public System.Security.Cryptography.OidCollection CertificatePolicy { get { return default(System.Security.Cryptography.OidCollection); } } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection ExtraStore { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } } public System.Security.Cryptography.X509Certificates.X509RevocationFlag RevocationFlag { get { return default(System.Security.Cryptography.X509Certificates.X509RevocationFlag); } set { } } public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get { return default(System.Security.Cryptography.X509Certificates.X509RevocationMode); } set { } } public System.TimeSpan UrlRetrievalTimeout { get { return default(System.TimeSpan); } set { } } public System.Security.Cryptography.X509Certificates.X509VerificationFlags VerificationFlags { get { return default(System.Security.Cryptography.X509Certificates.X509VerificationFlags); } set { } } public System.DateTime VerificationTime { get { return default(System.DateTime); } set { } } public void Reset() { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct X509ChainStatus { public System.Security.Cryptography.X509Certificates.X509ChainStatusFlags Status { get { return default(System.Security.Cryptography.X509Certificates.X509ChainStatusFlags); } set { } } public string StatusInformation { get { return default(string); } set { } } } [System.FlagsAttribute] public enum X509ChainStatusFlags { CtlNotSignatureValid = 262144, CtlNotTimeValid = 131072, CtlNotValidForUsage = 524288, Cyclic = 128, ExplicitDistrust = 67108864, HasExcludedNameConstraint = 32768, HasNotDefinedNameConstraint = 8192, HasNotPermittedNameConstraint = 16384, HasNotSupportedCriticalExtension = 134217728, HasNotSupportedNameConstraint = 4096, HasWeakSignature = 1048576, InvalidBasicConstraints = 1024, InvalidExtension = 256, InvalidNameConstraints = 2048, InvalidPolicyConstraints = 512, NoError = 0, NoIssuanceChainPolicy = 33554432, NotSignatureValid = 8, NotTimeNested = 2, NotTimeValid = 1, NotValidForUsage = 16, OfflineRevocation = 16777216, PartialChain = 65536, RevocationStatusUnknown = 64, Revoked = 4, UntrustedRoot = 32, } public enum X509ContentType { Authenticode = 6, Cert = 1, Pfx = 3, Pkcs12 = 3, Pkcs7 = 5, SerializedCert = 2, SerializedStore = 4, Unknown = 0, } public sealed partial class X509EnhancedKeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509EnhancedKeyUsageExtension() { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedEnhancedKeyUsages, bool critical) { } public X509EnhancedKeyUsageExtension(System.Security.Cryptography.OidCollection enhancedKeyUsages, bool critical) { } public System.Security.Cryptography.OidCollection EnhancedKeyUsages { get { return default(System.Security.Cryptography.OidCollection); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public partial class X509Extension : System.Security.Cryptography.AsnEncodedData { protected X509Extension() { } public X509Extension(System.Security.Cryptography.AsnEncodedData encodedExtension, bool critical) { } public X509Extension(System.Security.Cryptography.Oid oid, byte[] rawData, bool critical) { } public X509Extension(string oid, byte[] rawData, bool critical) { } public bool Critical { get { return default(bool); } set { } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public sealed partial class X509ExtensionCollection : System.Collections.ICollection, System.Collections.IEnumerable { public X509ExtensionCollection() { } public int Count { get { return default(int); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } public System.Security.Cryptography.X509Certificates.X509Extension this[int index] { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } } public System.Security.Cryptography.X509Certificates.X509Extension this[string oid] { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public int Add(System.Security.Cryptography.X509Certificates.X509Extension extension) { return default(int); } public void CopyTo(System.Security.Cryptography.X509Certificates.X509Extension[] array, int index) { } public System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator GetEnumerator() { return default(System.Security.Cryptography.X509Certificates.X509ExtensionEnumerator); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public sealed partial class X509ExtensionEnumerator : System.Collections.IEnumerator { internal X509ExtensionEnumerator() { } public System.Security.Cryptography.X509Certificates.X509Extension Current { get { return default(System.Security.Cryptography.X509Certificates.X509Extension); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public bool MoveNext() { return default(bool); } public void Reset() { } } public enum X509FindType { FindByApplicationPolicy = 10, FindByCertificatePolicy = 11, FindByExtension = 12, FindByIssuerDistinguishedName = 4, FindByIssuerName = 3, FindByKeyUsage = 13, FindBySerialNumber = 5, FindBySubjectDistinguishedName = 2, FindBySubjectKeyIdentifier = 14, FindBySubjectName = 1, FindByTemplateName = 9, FindByThumbprint = 0, FindByTimeExpired = 8, FindByTimeNotYetValid = 7, FindByTimeValid = 6, } [System.FlagsAttribute] public enum X509KeyStorageFlags { DefaultKeySet = 0, Exportable = 4, MachineKeySet = 2, PersistKeySet = 16, UserKeySet = 1, UserProtected = 8, } public sealed partial class X509KeyUsageExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509KeyUsageExtension() { } public X509KeyUsageExtension(System.Security.Cryptography.AsnEncodedData encodedKeyUsage, bool critical) { } public X509KeyUsageExtension(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags keyUsages, bool critical) { } public System.Security.Cryptography.X509Certificates.X509KeyUsageFlags KeyUsages { get { return default(System.Security.Cryptography.X509Certificates.X509KeyUsageFlags); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } [System.FlagsAttribute] public enum X509KeyUsageFlags { CrlSign = 2, DataEncipherment = 16, DecipherOnly = 32768, DigitalSignature = 128, EncipherOnly = 1, KeyAgreement = 8, KeyCertSign = 4, KeyEncipherment = 32, None = 0, NonRepudiation = 64, } public enum X509NameType { DnsFromAlternativeName = 4, DnsName = 3, EmailName = 1, SimpleName = 0, UpnName = 2, UrlName = 5, } public enum X509RevocationFlag { EndCertificateOnly = 0, EntireChain = 1, ExcludeRoot = 2, } public enum X509RevocationMode { NoCheck = 0, Offline = 2, Online = 1, } public sealed partial class X509Store : System.IDisposable { public X509Store() { } public X509Store(System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public X509Store(string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation) { } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { return default(System.Security.Cryptography.X509Certificates.X509Certificate2Collection); } } public System.Security.Cryptography.X509Certificates.StoreLocation Location { get { return default(System.Security.Cryptography.X509Certificates.StoreLocation); } } public string Name { get { return default(string); } } public void Add(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public void Dispose() { } public void Open(System.Security.Cryptography.X509Certificates.OpenFlags flags) { } public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } } public sealed partial class X509SubjectKeyIdentifierExtension : System.Security.Cryptography.X509Certificates.X509Extension { public X509SubjectKeyIdentifierExtension() { } public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.AsnEncodedData encodedSubjectKeyIdentifier, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, bool critical) { } public X509SubjectKeyIdentifierExtension(System.Security.Cryptography.X509Certificates.PublicKey key, System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { } public X509SubjectKeyIdentifierExtension(string subjectKeyIdentifier, bool critical) { } public string SubjectKeyIdentifier { get { return default(string); } } public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { } } public enum X509SubjectKeyIdentifierHashAlgorithm { CapiSha1 = 2, Sha1 = 0, ShortSha1 = 1, } [System.FlagsAttribute] public enum X509VerificationFlags { AllFlags = 4095, AllowUnknownCertificateAuthority = 16, IgnoreCertificateAuthorityRevocationUnknown = 1024, IgnoreCtlNotTimeValid = 2, IgnoreCtlSignerRevocationUnknown = 512, IgnoreEndRevocationUnknown = 256, IgnoreInvalidBasicConstraints = 8, IgnoreInvalidName = 64, IgnoreInvalidPolicy = 128, IgnoreNotTimeNested = 4, IgnoreNotTimeValid = 1, IgnoreRootRevocationUnknown = 2048, IgnoreWrongUsage = 32, NoFlag = 0, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // ---------------------------------------------------------------------------- // This is the interface for the BindingContext, which is // consumed by the StatementBinder. // ---------------------------------------------------------------------------- internal sealed class OutputContext { public LocalVariableSymbol m_pThisPointer; public MethodSymbol m_pCurrentMethodSymbol; public bool m_bUnsafeErrorGiven; }; internal enum UNSAFESTATES { UNSAFESTATES_Unsafe, UNSAFESTATES_Safe, UNSAFESTATES_Unknown, }; internal class BindingContext { public static BindingContext CreateInstance( CSemanticChecker pSemanticChecker, ExprFactory exprFactory, OutputContext outputContext, bool bflushLocalVariableTypesForEachStatement, bool bAllowUnsafeBlocks, bool bIsOptimizingSwitchAndArrayInit, bool bShowReachability, bool bWrapNonExceptionThrows, bool bInRefactoring, KAID aidLookupContext ) { return new BindingContext( pSemanticChecker, exprFactory, outputContext, bflushLocalVariableTypesForEachStatement, bAllowUnsafeBlocks, bIsOptimizingSwitchAndArrayInit, bShowReachability, bWrapNonExceptionThrows, bInRefactoring, aidLookupContext); } private BindingContext( CSemanticChecker pSemanticChecker, ExprFactory exprFactory, OutputContext outputContext, bool bflushLocalVariableTypesForEachStatement, bool bAllowUnsafeBlocks, bool bIsOptimizingSwitchAndArrayInit, bool bShowReachability, bool bWrapNonExceptionThrows, bool bInRefactoring, KAID aidLookupContext ) { m_ExprFactory = exprFactory; m_outputContext = outputContext; m_pInputFile = null; m_pParentDecl = null; m_pContainingAgg = null; m_pCurrentSwitchType = null; m_pOriginalConstantField = null; m_pCurrentFieldSymbol = null; m_pImplicitlyTypedLocal = null; m_pOuterScope = null; m_pFinallyScope = null; m_pTryScope = null; m_pCatchScope = null; m_pCurrentScope = null; m_pSwitchScope = null; m_pCurrentBlock = null; m_UnsafeState = UNSAFESTATES.UNSAFESTATES_Unknown; m_FinallyNestingCount = 0; m_bInsideTryOfCatch = false; m_bInFieldInitializer = false; m_bInBaseConstructorCall = false; m_bAllowUnsafeBlocks = bAllowUnsafeBlocks; m_bIsOptimizingSwitchAndArrayInit = bIsOptimizingSwitchAndArrayInit; m_bShowReachability = bShowReachability; m_bWrapNonExceptionThrows = bWrapNonExceptionThrows; m_bInRefactoring = bInRefactoring; m_bInAttribute = false; m_bRespectSemanticsAndReportErrors = true; m_bflushLocalVariableTypesForEachStatement = bflushLocalVariableTypesForEachStatement; m_ppamis = null; m_pamiCurrent = null; m_pInitType = null; m_returnErrorSink = null; Debug.Assert(pSemanticChecker != null); this.SemanticChecker = pSemanticChecker; this.SymbolLoader = SemanticChecker.GetSymbolLoader(); m_outputContext.m_pThisPointer = null; m_outputContext.m_pCurrentMethodSymbol = null; m_aidExternAliasLookupContext = aidLookupContext; CheckedNormal = false; CheckedConstant = false; } protected BindingContext(BindingContext parent) { m_ExprFactory = parent.m_ExprFactory; m_outputContext = parent.m_outputContext; m_pInputFile = parent.m_pInputFile; m_pParentDecl = parent.m_pParentDecl; m_pContainingAgg = parent.m_pContainingAgg; m_pCurrentSwitchType = parent.m_pCurrentSwitchType; m_pOriginalConstantField = parent.m_pOriginalConstantField; m_pCurrentFieldSymbol = parent.m_pCurrentFieldSymbol; m_pImplicitlyTypedLocal = parent.m_pImplicitlyTypedLocal; m_pOuterScope = parent.m_pOuterScope; m_pFinallyScope = parent.m_pFinallyScope; m_pTryScope = parent.m_pTryScope; m_pCatchScope = parent.m_pCatchScope; m_pCurrentScope = parent.m_pCurrentScope; m_pSwitchScope = parent.m_pSwitchScope; m_pCurrentBlock = parent.m_pCurrentBlock; m_ppamis = parent.m_ppamis; m_pamiCurrent = parent.m_pamiCurrent; m_UnsafeState = parent.m_UnsafeState; m_FinallyNestingCount = parent.m_FinallyNestingCount; m_bInsideTryOfCatch = parent.m_bInsideTryOfCatch; m_bInFieldInitializer = parent.m_bInFieldInitializer; m_bInBaseConstructorCall = parent.m_bInBaseConstructorCall; CheckedNormal = parent.CheckedNormal; CheckedConstant = parent.CheckedConstant; m_aidExternAliasLookupContext = parent.m_aidExternAliasLookupContext; m_bAllowUnsafeBlocks = parent.m_bAllowUnsafeBlocks; m_bIsOptimizingSwitchAndArrayInit = parent.m_bIsOptimizingSwitchAndArrayInit; m_bShowReachability = parent.m_bShowReachability; m_bWrapNonExceptionThrows = parent.m_bWrapNonExceptionThrows; m_bflushLocalVariableTypesForEachStatement = parent.m_bflushLocalVariableTypesForEachStatement; m_bInRefactoring = parent.m_bInRefactoring; m_bInAttribute = parent.m_bInAttribute; m_bRespectSemanticsAndReportErrors = parent.m_bRespectSemanticsAndReportErrors; m_pInitType = parent.m_pInitType; m_returnErrorSink = parent.m_returnErrorSink; Debug.Assert(parent.SemanticChecker != null); this.SemanticChecker = parent.SemanticChecker; this.SymbolLoader = SemanticChecker.GetSymbolLoader(); } //The SymbolLoader can be retrieved from m_pSemanticChecker, //but that is a virtual call that is showing up on the profiler. Retrieve //the SymbolLoader once at ruction and return a cached copy. // PERFORMANCE: Is this cache still necessary? public SymbolLoader SymbolLoader { get; private set; } public Declaration m_pParentDecl; public Declaration ContextForMemberLookup() { return m_pParentDecl; } public OutputContext GetOutputContext() { return m_outputContext; } // Virtual Dispose method - this should only be called by FNCBRECCS's StatePusher. // It is used to clean up state in the output context for each overridden context. public virtual void Dispose() { } // State boolean questions. public bool InMethod() { return m_outputContext.m_pCurrentMethodSymbol != null; } public bool InStaticMethod() { return m_outputContext.m_pCurrentMethodSymbol != null && m_outputContext.m_pCurrentMethodSymbol.isStatic; } public bool InConstructor() { return m_outputContext.m_pCurrentMethodSymbol != null && m_outputContext.m_pCurrentMethodSymbol.IsConstructor(); } public bool InAnonymousMethod() { return null != m_pamiCurrent; } public bool InFieldInitializer() { return m_bInFieldInitializer; } public bool IsThisPointer(EXPR expr) { bool localThis = expr.isANYLOCAL() && expr.asANYLOCAL().local == m_outputContext.m_pThisPointer; bool baseThis = false; return localThis || baseThis; } public bool RespectReadonly() { return m_bRespectSemanticsAndReportErrors; } public bool IsUnsafeContext() { return m_UnsafeState == UNSAFESTATES.UNSAFESTATES_Unsafe; } public bool ReportUnsafeErrors() { return !m_outputContext.m_bUnsafeErrorGiven && m_bRespectSemanticsAndReportErrors; } public AggregateSymbol ContainingAgg() { return m_pContainingAgg; } public LocalVariableSymbol GetThisPointer() { return m_outputContext.m_pThisPointer; } // Unsafe. public UNSAFESTATES GetUnsafeState() { return m_UnsafeState; } private KAID m_aidExternAliasLookupContext { get; } // Members. private ExprFactory m_ExprFactory; private OutputContext m_outputContext; // Methods. private InputFile m_pInputFile; // symbols. // The parent declaration, for various name binding uses. This is either an // AggregateDeclaration (if parentAgg is non-null), or an NamespaceDeclaration (if parentAgg // is null). // Note that parentAgg isn't enough for name binding if partial classes // are used, because the using clauses in effect may be different and // unsafe state may be different. private AggregateSymbol m_pContainingAgg; private CType m_pCurrentSwitchType; private FieldSymbol m_pOriginalConstantField; private FieldSymbol m_pCurrentFieldSymbol; // If we are in a context where we are binding the right hand side of a declaration // like var y = (y=5), we need to keep track of what local we are attempting to // infer the type of, so that we can give an error if that local is used on the // right hand side. private LocalVariableSymbol m_pImplicitlyTypedLocal; // Scopes. private Scope m_pOuterScope; private Scope m_pFinallyScope; // innermost finally, or pOuterScope if none... private Scope m_pTryScope; // innermost try, or pOuterScope if none... private Scope m_pCatchScope; // innermost catch, or null if none private Scope m_pCurrentScope; // current scope private Scope m_pSwitchScope; // innermost switch, or null if none private EXPRBLOCK m_pCurrentBlock; // m_ppamis points to the list of child anonymous methods of the current context. // That is, m_ppamis is where we will add an anonymous method should we find a // new one while binding. If we are presently binding a nominal method then // m_ppamis points to the methinfo.pamis. If we are presently binding an // anonymous method then it points to m_pamiCurrent.pamis. If we are presently // in a context in which anonymous methods cannot occur (eg, binding an attribute) // then it is null. private List<EXPRBOUNDLAMBDA> m_ppamis; // If we are presently binding an anonymous method body then m_pamiCurrent points // to the anon meth info. If we are binding either a method body or some other // statement context (eg, binding an attribute, etc) then m_pamiCurrent is null. private EXPRBOUNDLAMBDA m_pamiCurrent; // Unsafe states. private UNSAFESTATES m_UnsafeState; // Variable Counters. private int m_FinallyNestingCount; // The rest of the members. private bool m_bInsideTryOfCatch; private bool m_bInFieldInitializer; private bool m_bInBaseConstructorCall; private bool m_bAllowUnsafeBlocks; private bool m_bIsOptimizingSwitchAndArrayInit; private bool m_bShowReachability; private bool m_bWrapNonExceptionThrows; private bool m_bInRefactoring; private bool m_bInAttribute; private bool m_bflushLocalVariableTypesForEachStatement; private bool m_bRespectSemanticsAndReportErrors; // False if we're in the EE. private CType m_pInitType; private IErrorSink m_returnErrorSink; public CSemanticChecker SemanticChecker { get; } public ExprFactory GetExprFactory() { return m_ExprFactory; } public bool CheckedNormal { get; set; } public bool CheckedConstant { get; set; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // // <OWNER>[....]</OWNER> /*============================================================ ** ** Class: SynchronizationContext ** ** ** Purpose: Capture synchronization semantics for asynchronous callbacks ** ** ===========================================================*/ namespace System.Threading { #if !MONO using Microsoft.Win32.SafeHandles; #endif using System.Security.Permissions; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; #if FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ExceptionServices; #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Security; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [Flags] enum SynchronizationContextProperties { None = 0, RequireWaitNotification = 0x1 }; #endif #if FEATURE_COMINTEROP && FEATURE_APPX // // This is implemented in System.Runtime.WindowsRuntime, allowing us to ask that assembly for a WinRT-specific SyncCtx. // I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed. // [FriendAccessAllowed] [SecurityCritical] internal class WinRTSynchronizationContextFactoryBase { [SecurityCritical] public virtual SynchronizationContext Create(object coreDispatcher) {return null;} } #endif //FEATURE_COMINTEROP #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags =SecurityPermissionFlag.ControlPolicy|SecurityPermissionFlag.ControlEvidence)] #endif public class SynchronizationContext { #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT SynchronizationContextProperties _props = SynchronizationContextProperties.None; #endif public SynchronizationContext() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT static Type s_cachedPreparedType1; static Type s_cachedPreparedType2; static Type s_cachedPreparedType3; static Type s_cachedPreparedType4; static Type s_cachedPreparedType5; // protected so that only the derived [....] context class can enable these flags [System.Security.SecuritySafeCritical] // auto-generated [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")] protected void SetWaitNotificationRequired() { // // Prepare the method so that it can be called in a reliable fashion when a wait is needed. // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing // preparing the method here does is to ensure there is no failure point before the method execution begins. // // Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain. // So we keep track of a few types we've already prepared in this AD. It is uncommon to have more than // a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets // our cache be much faster than a more general cache might be. This is important, because this // is a *very* hot code path for many WPF and [....] apps. // Type type = this.GetType(); if (s_cachedPreparedType1 != type && s_cachedPreparedType2 != type && s_cachedPreparedType3 != type && s_cachedPreparedType4 != type && s_cachedPreparedType5 != type) { RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait)); if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; } _props |= SynchronizationContextProperties.RequireWaitNotification; } public bool IsWaitNotificationRequired() { return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } #endif public virtual void Send(SendOrPostCallback d, Object state) { d(state); } public virtual void Post(SendOrPostCallback d, Object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } /// <summary> /// Optional override for subclasses, for responding to notification that operation is starting. /// </summary> public virtual void OperationStarted() { } /// <summary> /// Optional override for subclasses, for responding to notification that operation has completed. /// </summary> public virtual void OperationCompleted() { } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT // Method called when the CLR does a wait operation [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles"); } Contract.EndContractBlock(); return WaitHelper(waitHandles, waitAll, millisecondsTimeout); } // Static helper to which the above method can delegate to in order to get the default // COM behavior. [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false)] [PrePrepareMethod] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #if MONO protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { throw new NotImplementedException (); } #else [MethodImplAttribute(MethodImplOptions.InternalCall)] protected static extern int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); #endif #endif #if FEATURE_CORECLR [ThreadStatic] private static SynchronizationContext s_threadStaticContext; #if FEATURE_LEGACYNETCF // // NetCF had a bug where SynchronizationContext.SetThreadStaticContext would set the SyncContext for every thread in the process. // This was because they stored the value in a regular static field (NetCF has no support for ThreadStatic fields). This was fixed in // Mango, but some apps built against pre-Mango WP7 do depend on the broken behavior. So for those apps we need an AppDomain-wide static // to hold whatever context was last set on any thread. // // NetCF had a bug where SynchronizationContext.SetThreadStaticContext would set the SyncContext for every thread in the process. // This was because they stored the value in a regular static field (NetCF has no support for ThreadStatic fields). This was fixed in // Mango, but some apps built against pre-Mango WP7 do depend on the broken behavior. So for those apps we need an AppDomain-wide static // to hold whatever context was last set on any thread. // private static SynchronizationContext s_appDomainStaticContext; #endif [System.Security.SecurityCritical] public static void SetSynchronizationContext(SynchronizationContext syncContext) { s_threadStaticContext = syncContext; } [System.Security.SecurityCritical] public static void SetThreadStaticContext(SynchronizationContext syncContext) #else internal static void SetThreadStaticContext(SynchronizationContext syncContext) #endif { #if FEATURE_LEGACYNETCF // // If this is a pre-Mango Windows Phone app, we need to set the SC for *all* threads to match the old NetCF behavior. // if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango) s_appDomainStaticContext = syncContext; else #endif s_threadStaticContext = syncContext; } #endif return context; } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Current; // SC never flows } } #else //FEATURE_CORECLR // set SynchronizationContext on the current thread [System.Security.SecurityCritical] // auto-generated_required public static void SetSynchronizationContext(SynchronizationContext syncContext) { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); ec.SynchronizationContext = syncContext; ec.SynchronizationContextNoFlow = syncContext; } #if MOBILE_LEGACY [Obsolete("The method is not supported and will be removed")] public static void SetThreadStaticContext(SynchronizationContext syncContext) { throw new NotSupportedException (); } #endif // Get the current SynchronizationContext on the current thread public static SynchronizationContext Current { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext(); } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContextNoFlow ?? GetThreadLocalContext(); } } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif private static SynchronizationContext GetThreadLocalContext() { SynchronizationContext context = null; #if FEATURE_CORECLR #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhoneMango) context = s_appDomainStaticContext; else #endif //FEATURE_LEGACYNETCF context = s_threadStaticContext; #endif //FEATURE_CORECLR #if FEATURE_APPX if (context == null && Environment.IsWinRTSupported) context = GetWinRTContext(); #endif #if MONODROID if (context == null) context = AndroidPlatform.GetDefaultSyncContext (); #endif return context; } #if FEATURE_APPX [SecuritySafeCritical] private static SynchronizationContext GetWinRTContext() { Contract.Assert(Environment.IsWinRTSupported); // Temporary hack to avoid loading a bunch of DLLs in every managed process. // This disables this feature for non-AppX processes that happen to use CoreWindow/CoreDispatcher, // which is not what we want. if (!AppDomain.IsAppXModel()) return null; // // We call into the VM to get the dispatcher. This is because: // // a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here. // b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly // into processes that don't need it (for performance reasons). // // So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to // System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext. // object dispatcher = GetWinRTDispatcherForCurrentThread(); if (dispatcher != null) return GetWinRTSynchronizationContextFactory().Create(dispatcher); return null; } [SecurityCritical] static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; [SecurityCritical] private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory() { // // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection. // It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because // we can do very little with WinRT stuff in mscorlib. // WinRTSynchronizationContextFactoryBase factory = s_winRTContextFactory; if (factory == null) { Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, " + AssemblyRef.SystemRuntimeWindowsRuntime, true); s_winRTContextFactory = factory = (WinRTSynchronizationContextFactoryBase)Activator.CreateInstance(factoryType, true); } return factory; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SecurityCritical] [ResourceExposure(ResourceScope.None)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Interface)] private static extern object GetWinRTDispatcherForCurrentThread(); #endif //FEATURE_APPX // helper to Clone this SynchronizationContext, public virtual SynchronizationContext CreateCopy() { // the CLR dummy has an empty clone function - no member data return new SynchronizationContext(); } #if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT [System.Security.SecurityCritical] // auto-generated private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout); } #endif } }
//------------------------------------------------------------------------------ // <copyright file="ProfileSection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { using System; using System.Xml; using System.Configuration; using System.Collections.Specialized; using System.Collections; using System.IO; using System.Text; using System.Web.Util; using System.Security.Permissions; /* <!-- Configuration for profile: enabled="[true|false]" Feature is enabled? defaultProvider="string" Name of provider to use by default <providers> Providers (class must inherit from ProfileProvider) <add Add a provider name="string" Name to identify this provider instance by type="string" Class that implements ProfileProvider provider-specific-configuration /> <remove Remove a provider name="string" /> Name of provider to remove <clear/> Remove all providers <properties> Optional element. List of properties in the Profile system <property Properties in the profile name="string" Name of the property type="string" Optional. Type of the property. Default: string. readOnly="[true|false]" Optional. Is Value read-only. Default: false. defaultValue="string" Optional. Default Value. Default: Empty string. allowAnonymous="[true|false]" Optional. Allow storing values for anonymous users. Default: false. provider="string Optional. Name of provider. Default: Default provider. serializeAs=["String|Xml|Binary|ProviderSpecific"] Optional. How to serialize the type. Default: ProviderSpecific. /> <group Optional element. Group of properties: Note: groups can not nested name="string" Name of the group <property Property in the group name="string" Name of the property type="type-name" Optional. Type of the property. Default: "string". readOnly="[true|false]" Optional. Is Value read-only. Default: false. defaultValue="string" Optional. Default Value. Default: Empty string. allowAnonymous="[true|false]" Optional. Allow storing values for anonymous users. Default: false. provider="string Optional. Name of provider. Default: Default provider. serializeAs=["String|Xml|Binary|ProviderSpecific"] Optional. How to serialize the type. Default: ProviderSpecific. /> </group> </properties> Configuration for SqlProfileProvider: connectionStringName="string" Name corresponding to the entry in <connectionStrings> section where the connection string for the provider is specified description="string" Description of what the provider does commandTimeout="int" Command timeout value for SQL command --> <profile enabled="true" defaultProvider="AspNetSqlProfileProvider" inherits="System.Web.Profile.ProfileBase, System.Web, Version=%ASSEMBLY_VERSION%, Culture=neutral, PublicKeyToken=%MICROSOFT_PUBLICKEY%" > <providers> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=%ASSEMBLY_VERSION%, Culture=neutral, PublicKeyToken=%MICROSOFT_PUBLICKEY%" connectionStringName="LocalSqlServer" applicationName="/" description="Stores and retrieves profile data from the local Microsoft SQL Server database" /> </providers> <properties> <!-- Add profile properties here. Example: <property name="FriendlyName" type="string" /> <property name="Height" type="int" /> <property name="Weight" type="int" /> --> </properties> </profile> */ public sealed class ProfileSection : ConfigurationSection { private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propEnabled = new ConfigurationProperty("enabled", typeof(bool), true, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propDefaultProvider = new ConfigurationProperty("defaultProvider", typeof(string), "AspNetSqlProfileProvider", null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propProviders = new ConfigurationProperty("providers", typeof(ProviderSettingsCollection), null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propProfile = new ConfigurationProperty("properties", typeof(RootProfilePropertySettingsCollection), null, ConfigurationPropertyOptions.IsDefaultCollection); private static readonly ConfigurationProperty _propInherits = new ConfigurationProperty("inherits", typeof(string), String.Empty, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propAutomaticSaveEnabled = new ConfigurationProperty("automaticSaveEnabled", typeof(bool), true, ConfigurationPropertyOptions.None); static ProfileSection() { // Property initialization _properties = new ConfigurationPropertyCollection(); _properties.Add(_propEnabled); _properties.Add(_propDefaultProvider); _properties.Add(_propProviders); _properties.Add(_propProfile); _properties.Add(_propInherits); _properties.Add(_propAutomaticSaveEnabled); } private long _recompilationHash; private bool _recompilationHashCached; internal long RecompilationHash { get { if (!_recompilationHashCached) { _recompilationHash = CalculateHash(); _recompilationHashCached = true; } return _recompilationHash; } } private long CalculateHash() { HashCodeCombiner hashCombiner = new HashCodeCombiner(); CalculateProfilePropertySettingsHash(PropertySettings, hashCombiner); if (PropertySettings != null) { foreach (ProfileGroupSettings pgs in PropertySettings.GroupSettings) { hashCombiner.AddObject(pgs.Name); CalculateProfilePropertySettingsHash(pgs.PropertySettings, hashCombiner); } } return hashCombiner.CombinedHash; } private void CalculateProfilePropertySettingsHash( ProfilePropertySettingsCollection settings, HashCodeCombiner hashCombiner) { foreach (ProfilePropertySettings pps in settings) { hashCombiner.AddObject(pps.Name); hashCombiner.AddObject(pps.Type); } } public ProfileSection() { } protected override ConfigurationPropertyCollection Properties { get { return _properties; } } [ConfigurationProperty("automaticSaveEnabled", DefaultValue = true)] public bool AutomaticSaveEnabled { get { return (bool)base[_propAutomaticSaveEnabled]; } set { base[_propAutomaticSaveEnabled] = value; } } [ConfigurationProperty("enabled", DefaultValue = true)] public bool Enabled { get { return (bool)base[_propEnabled]; } set { base[_propEnabled] = value; } } [ConfigurationProperty("defaultProvider", DefaultValue = "AspNetSqlProfileProvider")] [StringValidator(MinLength = 1)] public string DefaultProvider { get { return (string)base[_propDefaultProvider]; } set { base[_propDefaultProvider] = value; } } [ConfigurationProperty("inherits", DefaultValue = "")] public string Inherits { get { return (string)base[_propInherits]; } set { base[_propInherits] = value; } } [ConfigurationProperty("providers")] public ProviderSettingsCollection Providers { get { return (ProviderSettingsCollection)base[_propProviders]; } } // not exposed to the API [ConfigurationProperty("properties")] public RootProfilePropertySettingsCollection PropertySettings { get { return (RootProfilePropertySettingsCollection)base[_propProfile]; } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; using System.Collections.Generic; using Vevo.Domain.DataInterfaces; using Vevo.Domain; using Vevo.WebUI.Ajax; using Vevo.Domain.Shipping; using Vevo.Shared.Utilities; using System.Text.RegularExpressions; using Vevo.Base.Domain; public partial class Admin_MainControls_ShippingZoneItemList : AdminAdvancedBaseUserControl { private bool _emptyRow = false; private bool IsContainingOnlyEmptyRow { get { return _emptyRow; } set { _emptyRow = value; } } private string ZoneGroupID { get { if (!String.IsNullOrEmpty( MainContext.QueryString["ZoneGroupID"] )) return MainContext.QueryString["ZoneGroupID"]; else return String.Empty; } } private GridViewHelper GridHelper { get { if (ViewState["GridHelper"] == null) ViewState["GridHelper"] = new GridViewHelper( uxGrid, "" ); return (GridViewHelper) ViewState["GridHelper"]; } } private void SetUpSearchFilter() { IList<TableSchemaItem> list = DataAccessContext.ShippingZoneGroupRepository.GetShippingZoneItemTableSchemas(); uxSearchFilter.SetUpSchema( list, "ZoneItemID" ); } private void SetFooterRowFocus() { Control countryList = uxGrid.FooterRow.FindControl( "uxCountryList" ); AjaxUtilities.GetScriptManager( this ).SetFocus( countryList ); } private void CreateDummyRow( IList<ShippingZoneItem> list ) { ShippingZoneItem item = new ShippingZoneItem(); item.ZoneItemID = "-1"; item.ZoneGroupID = ""; list.Add( item ); } private void DeleteVisible( bool value ) { uxDeleteButton.Visible = value; if (value) { if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxDeleteConfirmButton.TargetControlID = "uxDeleteButton"; uxConfirmModalPopup.TargetControlID = "uxDeleteButton"; } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } private void PopulateControls() { if (!MainContext.IsPostBack) { RefreshGrid(); } if (uxGrid.Rows.Count > 0) { DeleteVisible( true ); uxPagingControl.Visible = true; } else { DeleteVisible( false ); uxPagingControl.Visible = false; } if (!IsAdminModifiable()) { uxAddButton.Visible = false; DeleteVisible( false ); } } private void RefreshGrid() { int totalItems; IList<ShippingZoneItem> list = DataAccessContext.ShippingZoneGroupRepository.SearchShippingZoneItems( ZoneGroupID, GridHelper.GetFullSortText(), uxSearchFilter.SearchFilterObj, (uxPagingControl.CurrentPage - 1) * uxPagingControl.ItemsPerPages, (uxPagingControl.CurrentPage * uxPagingControl.ItemsPerPages) - 1, out totalItems ); if (list == null || list.Count == 0) { IsContainingOnlyEmptyRow = true; list = new List<ShippingZoneItem>(); CreateDummyRow( list ); } else { IsContainingOnlyEmptyRow = false; } uxGrid.DataSource = list; uxGrid.DataBind(); uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); RefreshDeleteButton(); ((AdminAdvanced_Components_CountryList) uxGrid.FooterRow.FindControl( "uxCountryList" )).Refresh(); ResetCountryState(); } private void RefreshDeleteButton() { if (IsContainingOnlyEmptyRow) uxDeleteButton.Visible = false; else uxDeleteButton.Visible = true; } private void ResetCountryState() { if (uxGrid.ShowFooter) { ((AdminAdvanced_Components_StateList) uxGrid.FooterRow.FindControl( "uxStateList" )).CountryCode = ""; ((AdminAdvanced_Components_CountryList) uxGrid.FooterRow.FindControl( "uxCountryList" )).CurrentSelected = ""; ((AdminAdvanced_Components_StateList) uxGrid.FooterRow.FindControl( "uxStateList" )).CurrentSelected = ""; } } protected void uxScarchChange( object sender, EventArgs e ) { RefreshGrid(); } protected void uxChangePage( object sender, EventArgs e ) { RefreshGrid(); } protected void uxGrid_DataBound( object sender, EventArgs e ) { if (IsContainingOnlyEmptyRow) { uxGrid.Rows[0].Visible = false; } } private ShippingZoneGroup RemoveItem( ShippingZoneGroup group, string itemID ) { for (int i = 0; i < group.ZoneItem.Count; i++) { if (group.ZoneItem[i].ZoneItemID == itemID) { group.ZoneItem.RemoveAt( i ); return group; } } return group; } protected void uxDeleteButton_Click( object sender, EventArgs e ) { bool deleted = false; foreach (GridViewRow row in uxGrid.Rows) { CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" ); if (deleteCheck != null && deleteCheck.Checked) { string id = uxGrid.DataKeys[row.RowIndex]["ZoneItemID"].ToString(); ShippingZoneGroup zoneGroup = DataAccessContext.ShippingZoneGroupRepository.GetOne( ZoneGroupID ); zoneGroup = RemoveItem( zoneGroup, id ); DataAccessContext.ShippingZoneGroupRepository.Save( zoneGroup ); deleted = true; } } uxGrid.EditIndex = -1; if (deleted) { uxMessage.DisplayMessage( Resources.ShippingZoneMessages.DeleteSuccess ); } RefreshGrid(); } protected void Page_Load( object sender, EventArgs e ) { if (String.IsNullOrEmpty( ZoneGroupID )) MainContext.RedirectMainControl( "ShippingZoneGroupList.ascx" ); uxSearchFilter.BubbleEvent += new EventHandler( uxScarchChange ); uxPagingControl.BubbleEvent += new EventHandler( uxChangePage ); if (!MainContext.IsPostBack) SetUpSearchFilter(); } protected void Page_PreRender( object sender, EventArgs e ) { PopulateControls(); } protected void uxAddButton_Click( object sender, EventArgs e ) { uxGrid.EditIndex = -1; uxGrid.ShowFooter = true; uxGrid.ShowHeader = true; RefreshGrid(); uxAddButton.Visible = false; AdminAdvanced_Components_CountryList myCountry = ((AdminAdvanced_Components_CountryList) uxGrid.FooterRow.FindControl( "uxCountryList" )); myCountry.CurrentSelected = ""; SetFooterRowFocus(); } protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e ) { GridHelper.SelectSorting( e.SortExpression ); RefreshGrid(); } protected void uxGrid_RowEditing( object sender, GridViewEditEventArgs e ) { uxGrid.EditIndex = e.NewEditIndex; RefreshGrid(); } protected void uxGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e ) { uxGrid.EditIndex = -1; RefreshGrid(); } private ShippingZoneItem SetupShippingZoneItemDetails() { ShippingZoneItem item = new ShippingZoneItem(); item.CountryCode = ((AdminAdvanced_Components_CountryList) uxGrid.FooterRow.FindControl( "uxCountryList" )).CurrentSelected; item.StateCode = ((AdminAdvanced_Components_StateList) uxGrid.FooterRow.FindControl( "uxStateList" )).CurrentSelected; item.ZipCode = ((TextBox) uxGrid.FooterRow.FindControl( "uxZipCodeText" )).Text.Trim(); item.ZoneGroupID = ZoneGroupID; return item; } private bool IsExistItem( ShippingZoneItem item ) { ShippingZoneGroup zoneGroup = DataAccessContext.ShippingZoneGroupRepository.GetOne( ZoneGroupID ); foreach (ShippingZoneItem zoneItem in zoneGroup.ZoneItem) { if (zoneItem.CountryCode == item.CountryCode && zoneItem.StateCode == item.StateCode && zoneItem.ZipCode == item.ZipCode) { if (zoneItem.ZoneItemID != item.ZoneItemID) return true; } } return false; } private bool IsZipcodeFormatCorrect( string zipCode ) { if (!String.IsNullOrEmpty( zipCode )) { Regex r = new Regex( "^[^*]+\\*{0,1}$" ); return r.IsMatch( zipCode ); } else return true; } protected void uxGrid_RowCommand( object sender, GridViewCommandEventArgs e ) { try { if (e.CommandName == "Add") { ShippingZoneGroup zoneGroup = DataAccessContext.ShippingZoneGroupRepository.GetOne( ZoneGroupID ); ShippingZoneItem item = SetupShippingZoneItemDetails(); if (IsZipcodeFormatCorrect( item.ZipCode )) { if (String.IsNullOrEmpty( item.CountryCode )) { uxMessage.DisplayError( Resources.ShippingZoneMessages.AddErrorSelectCountry ); return; } if (!IsExistItem( item )) { zoneGroup.ZoneItem.Add( item ); DataAccessContext.ShippingZoneGroupRepository.Save( zoneGroup ); uxMessage.DisplayMessage( Resources.ShippingZoneMessages.AddZoneItemSuccess ); RefreshGrid(); } else uxMessage.DisplayError( Resources.ShippingZoneMessages.AddErrorDuplicatedItem ); ((TextBox) uxGrid.FooterRow.FindControl( "uxZipCodeText" )).Text = ""; } else { uxMessage.DisplayError( Resources.ShippingZoneMessages.ZipCodeFormatIncorrect ); } } if (e.CommandName == "Edit") { uxGrid.ShowFooter = false; uxAddButton.Visible = true; } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } protected void uxGrid_RowUpdating( object sender, GridViewUpdateEventArgs e ) { try { string id = ((Label) uxGrid.Rows[e.RowIndex].FindControl( "uxZoneItemIDLabel" )).Text.Trim(); string countryCode = ((AdminAdvanced_Components_CountryList) uxGrid.Rows[e.RowIndex].FindControl( "uxCountryList" )).CurrentSelected; string stateCode = ((AdminAdvanced_Components_StateList) uxGrid.Rows[e.RowIndex].FindControl( "uxStateList" )).CurrentSelected; string zipCode = ((TextBox) uxGrid.Rows[e.RowIndex].FindControl( "uxZipCodeEditText" )).Text.Trim(); if (!String.IsNullOrEmpty( id )) { if (IsZipcodeFormatCorrect( zipCode )) { ShippingZoneItem currentItem = new ShippingZoneItem(); ShippingZoneGroup zoneGroup = DataAccessContext.ShippingZoneGroupRepository.GetOne( ZoneGroupID ); foreach (ShippingZoneItem item in zoneGroup.ZoneItem) { if (item.ZoneItemID == id) { currentItem.ZoneItemID = id; currentItem.CountryCode = countryCode; currentItem.StateCode = stateCode; currentItem.ZipCode = zipCode; if (!IsExistItem( currentItem )) { item.CountryCode = countryCode; item.StateCode = stateCode; item.ZipCode = zipCode; DataAccessContext.ShippingZoneGroupRepository.Save( zoneGroup ); uxMessage.DisplayMessage( Resources.ShippingZoneMessages.UpdateZoneItemSuccess ); } else uxMessage.DisplayError( Resources.ShippingZoneMessages.AddErrorDuplicatedItem ); } } } else { uxMessage.DisplayError( Resources.ShippingZoneMessages.ZipCodeFormatIncorrect ); } } // End editing uxGrid.EditIndex = -1; RefreshGrid(); } catch (Exception ex) { uxMessage.DisplayException( ex ); } finally { // Avoid calling Update() automatically by GridView e.Cancel = true; } } protected void uxState_RefreshHandler( object sender, EventArgs e ) { int index = uxGrid.EditIndex; AdminAdvanced_Components_StateList stateList = (AdminAdvanced_Components_StateList) uxGrid.Rows[index].FindControl( "uxStateList" ); AdminAdvanced_Components_CountryList countryList = (AdminAdvanced_Components_CountryList) uxGrid.Rows[index].FindControl( "uxCountryList" ); stateList.CountryCode = countryList.CurrentSelected; stateList.Refresh(); } protected void uxStateFooter_RefreshHandler( object sender, EventArgs e ) { AdminAdvanced_Components_StateList stateList = (AdminAdvanced_Components_StateList) uxGrid.FooterRow.FindControl( "uxStateList" ); AdminAdvanced_Components_CountryList countryList = (AdminAdvanced_Components_CountryList) uxGrid.FooterRow.FindControl( "uxCountryList" ); stateList.CountryCode = countryList.CurrentSelected; stateList.Refresh(); } }
namespace IndustrialAutomaton.MaintenanceAstromech { using System; using System.Collections.Generic; using System.Linq; using VRage.Game.ModAPI; using VRage.ModAPI; using VRage.Utils; public enum BlockClass { AutoRepairSystem = 1, ShipController, Thruster, Gyroscope, CargoContainer, Conveyor, ControllableGun, Reactor, ProgrammableBlock, Projector, FunctionalBlock, ProductionBlock, Door, ArmorBlock } public class BlockClassState { public BlockClass BlockClass { get; } public bool Enabled { get; set; } public BlockClassState(BlockClass blockClass, bool enabled) { BlockClass = blockClass; Enabled = enabled; } } public class NanobotBuildAndRepairSystemPriorityHandling : List<BlockClassState> { private bool _BlockClassListDirty = true; private List<string> _BlockClassList = new List<string>(); internal BlockClass? Selected { get; set; } //Visual internal NanobotBuildAndRepairSystemPriorityHandling() { foreach (BlockClass blockClass in Enum.GetValues(typeof(BlockClass))) { Add(new BlockClassState(blockClass, true)); } } /// <summary> /// Retrieve the build/repair priority of the block. /// </summary> internal int GetBuildPriority(IMySlimBlock a) { var blockClass = GetBlockClass(a, false); var keyValue = this.FirstOrDefault((kv) => kv.BlockClass == blockClass); return IndexOf(keyValue); } /// <summary> /// Retrieve if the build/repair of this block kind is enabled. /// </summary> internal bool GetEnabled(IMySlimBlock a) { var blockClass = GetBlockClass(a, true); var keyValue = this.FirstOrDefault((kv) => kv.BlockClass == blockClass); return keyValue.Enabled; } /// <summary> /// Get the Block class /// </summary> /// <param name="a"></param> /// <returns></returns> private BlockClass GetBlockClass(IMySlimBlock a, bool real) { var block = a.FatBlock; var functionalBlock = a.FatBlock as Sandbox.ModAPI.IMyFunctionalBlock; if (!real && functionalBlock != null && !functionalBlock.Enabled) return BlockClass.ArmorBlock; //Switched of -> handle as structural block (if logical class is asked) if (block is Sandbox.ModAPI.IMyShipWelder && block.BlockDefinition.SubtypeName.Contains("NanobotBuildAndRepairSystem")) return BlockClass.AutoRepairSystem; if (block is Sandbox.ModAPI.IMyShipController) return BlockClass.ShipController; if (block is Sandbox.ModAPI.IMyThrust) return BlockClass.Thruster; if (block is Sandbox.ModAPI.IMyGyro) return BlockClass.Gyroscope; if (block is Sandbox.ModAPI.IMyCargoContainer) return BlockClass.CargoContainer; if (block is Sandbox.ModAPI.IMyConveyor || a.FatBlock is Sandbox.ModAPI.IMyConveyorSorter || a.FatBlock is Sandbox.ModAPI.IMyConveyorTube) return BlockClass.Conveyor; if (block is Sandbox.ModAPI.IMyUserControllableGun) return BlockClass.ControllableGun; if (block is Sandbox.ModAPI.IMyReactor) return BlockClass.Reactor; if (block is Sandbox.ModAPI.IMyProgrammableBlock) return BlockClass.ProgrammableBlock; if (block is SpaceEngineers.Game.ModAPI.IMyTimerBlock) return BlockClass.ProgrammableBlock; if (block is Sandbox.ModAPI.IMyProjector) return BlockClass.Projector; if (block is Sandbox.ModAPI.IMyDoor) return BlockClass.Door; if (block is Sandbox.ModAPI.IMyProductionBlock) return BlockClass.ProductionBlock; if (block is Sandbox.ModAPI.IMyFunctionalBlock) return BlockClass.FunctionalBlock; return BlockClass.ArmorBlock; } /// <summary> /// /// </summary> /// <param name="items"></param> internal void FillTerminalList(List<MyTerminalControlListBoxItem> items, List<MyTerminalControlListBoxItem> selected) { foreach(var entry in this) { var item = new MyTerminalControlListBoxItem(MyStringId.GetOrCompute(string.Format("{0} ({1})",entry.BlockClass.ToString(), entry.Enabled ? "X" : "-")), MyStringId.NullOrEmpty, entry.BlockClass); items.Add(item); if (entry.BlockClass == Selected) { selected.Add(item); } } } internal void MoveSelectedUp() { if (Selected != null) { var keyValue = this.FirstOrDefault((kv) => kv.BlockClass == Selected); var currentPrio = IndexOf(keyValue); if (currentPrio > 0) { this.Move(currentPrio, currentPrio - 1); _BlockClassListDirty = true; } } } internal void MoveSelectedDown() { if (Selected != null) { var keyValue = this.FirstOrDefault((kv) => kv.BlockClass == Selected); var currentPrio = IndexOf(keyValue); if (currentPrio >=0 && currentPrio < Count-1) { this.Move(currentPrio, currentPrio + 1); _BlockClassListDirty = true; } } } internal void ToggleEnabled() { if (Selected != null) { var keyValue = this.FirstOrDefault((kv) => kv.BlockClass == Selected); if (keyValue != null) { keyValue.Enabled = !keyValue.Enabled; _BlockClassListDirty = true; } } } internal int GetPriority(int blockClass) { var keyValue = this.FirstOrDefault((kv) => (int)kv.BlockClass == blockClass); return IndexOf(keyValue); } internal void SetPriority(int blockClass, int prio) { if (prio >= 0 && prio < Count) { var keyValue = this.FirstOrDefault((kv) => (int)kv.BlockClass == blockClass); var currentPrio = IndexOf(keyValue); if (currentPrio >= 0) { this.Move(currentPrio, prio); _BlockClassListDirty = true; } } } internal bool GetEnabled(int blockClass) { var keyValue = this.FirstOrDefault((kv) => (int)kv.BlockClass == blockClass); return keyValue != null ? keyValue.Enabled : false; } internal void SetEnabled(int blockClass, bool enabled) { var keyValue = this.FirstOrDefault((kv) =>(int)kv.BlockClass == blockClass); var currentPrio = IndexOf(keyValue); if (currentPrio >= 0) { _BlockClassListDirty = keyValue.Enabled != enabled; keyValue.Enabled = enabled; } } internal string GetEntries() { var value = string.Empty; foreach(var entry in this) { value += string.Format("{0};{1}|", (int)entry.BlockClass, entry.Enabled); } return value.Remove(value.Length - 1); } internal void SetEntries(string value) { if (value == null) return; var entries = value.Split('|'); var prio = 0; foreach (var val in entries) { var blockClassValue = 0; var enabled = true; var values = val.Split(';'); if (values.Length >= 2 && int.TryParse(values[0], out blockClassValue) && bool.TryParse(values[1], out enabled)) { var keyValue = this.FirstOrDefault((kv) => kv.BlockClass == (BlockClass)blockClassValue); if (keyValue != null) { keyValue.Enabled = enabled; var currentPrio = IndexOf(keyValue); this.Move(currentPrio, prio); prio++; } } } _BlockClassListDirty = true; } internal List<string> GetList() { lock (_BlockClassList) { if (_BlockClassListDirty) { _BlockClassListDirty = false; _BlockClassList.Clear(); foreach (var item in this) { _BlockClassList.Add(string.Format("{0};{1}", item.BlockClass, item.Enabled)); } } return _BlockClassList; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Ical.Net.DataTypes; using Ical.Net.Evaluation; using Ical.Net.Utility; namespace Ical.Net.CalendarComponents { /// <summary> /// A class that represents an RFC 5545 VEVENT component. /// </summary> /// <note> /// TODO: Add support for the following properties: /// <list type="bullet"> /// <item>Add support for the Organizer and Attendee properties</item> /// <item>Add support for the Class property</item> /// <item>Add support for the Geo property</item> /// <item>Add support for the Priority property</item> /// <item>Add support for the Related property</item> /// <item>Create a TextCollection DataType for 'text' items separated by commas</item> /// </list> /// </note> public class CalendarEvent : RecurringComponent, IAlarmContainer, IComparable<CalendarEvent> { internal const string ComponentName = "VEVENT"; /// <summary> /// The start date/time of the event. /// <note> /// If the duration has not been set, but /// the start/end time of the event is available, /// the duration is automatically determined. /// Likewise, if the end date/time has not been /// set, but a start and duration are available, /// the end date/time will be extrapolated. /// </note> /// </summary> public override IDateTime DtStart { get => base.DtStart; set { base.DtStart = value; ExtrapolateTimes(); } } /// <summary> /// The end date/time of the event. /// <note> /// If the duration has not been set, but /// the start/end time of the event is available, /// the duration is automatically determined. /// Likewise, if an end time and duration are available, /// but a start time has not been set, the start time /// will be extrapolated. /// </note> /// </summary> public virtual IDateTime DtEnd { get => Properties.Get<IDateTime>("DTEND"); set { if (!Equals(DtEnd, value)) { Properties.Set("DTEND", value); ExtrapolateTimes(); } } } /// <summary> /// The duration of the event. /// <note> /// If a start time and duration is available, /// the end time is automatically determined. /// Likewise, if the end time and duration is /// available, but a start time is not determined, /// the start time will be extrapolated from /// available information. /// </note> /// </summary> // NOTE: Duration is not supported by all systems, // (i.e. iPhone) and cannot co-exist with DtEnd. // RFC 5545 states: // // ; either 'dtend' or 'duration' may appear in // ; a 'eventprop', but 'dtend' and 'duration' // ; MUST NOT occur in the same 'eventprop' // // Therefore, Duration is not serialized, as DtEnd // should always be extrapolated from the duration. public virtual TimeSpan Duration { get => Properties.Get<TimeSpan>("DURATION"); set { if (!Equals(Duration, value)) { Properties.Set("DURATION", value); ExtrapolateTimes(); } } } /// <summary> /// An alias to the DtEnd field (i.e. end date/time). /// </summary> public virtual IDateTime End { get => DtEnd; set => DtEnd = value; } /// <summary> /// Returns true if the event is an all-day event. /// </summary> public virtual bool IsAllDay { get => !Start.HasTime; set { // Set whether or not the start date/time // has a time value. if (Start != null) { Start.HasTime = !value; } if (End != null) { End.HasTime = !value; } if (value && Start != null && End != null && Equals(Start.Date, End.Date)) { Duration = default(TimeSpan); End = Start.AddDays(1); } } } /// <summary> /// The geographic location (lat/long) of the event. /// </summary> public GeographicLocation GeographicLocation { get => Properties.Get<GeographicLocation>("GEO"); set => Properties.Set("GEO", value); } /// <summary> /// The location of the event. /// </summary> public string Location { get => Properties.Get<string>("LOCATION"); set => Properties.Set("LOCATION", value); } /// <summary> /// Resources that will be used during the event. /// <example>Conference room #2</example> /// <example>Projector</example> /// </summary> public virtual IList<string> Resources { get => Properties.GetMany<string>("RESOURCES"); set => Properties.Set("RESOURCES", value ?? new List<string>()); } /// <summary> /// The status of the event. /// </summary> public string Status { get => Properties.Get<string>("STATUS"); set => Properties.Set("STATUS", value); } /// <summary> /// The transparency of the event. In other words, /// whether or not the period of time this event /// occupies can contain other events (transparent), /// or if the time cannot be scheduled for anything /// else (opaque). /// </summary> public string Transparency { get => Properties.Get<string>(TransparencyType.Key); set => Properties.Set(TransparencyType.Key, value); } private EventEvaluator _mEvaluator; /// <summary> /// Constructs an Event object, with an iCalObject /// (usually an iCalendar object) as its parent. /// </summary> public CalendarEvent() { Initialize(); } private void Initialize() { Name = EventStatus.Name; _mEvaluator = new EventEvaluator(this); SetService(_mEvaluator); } /// <summary> /// Use this method to determine if an event occurs on a given date. /// <note type="caution"> /// This event should be called only after the Evaluate /// method has calculated the dates for which this event occurs. /// </note> /// </summary> /// <param name="dateTime">The date to test.</param> /// <returns>True if the event occurs on the <paramref name="dateTime"/> provided, False otherwise.</returns> public virtual bool OccursOn(IDateTime dateTime) { return _mEvaluator.Periods.Any(p => p.StartTime.Date == dateTime.Date || // It's the start date OR (p.StartTime.Date <= dateTime.Date && // It's after the start date AND (p.EndTime.HasTime && p.EndTime.Date >= dateTime.Date || // an end time was specified, and it's after the test date (!p.EndTime.HasTime && p.EndTime.Date > dateTime.Date)))); } /// <summary> /// Use this method to determine if an event begins at a given date and time. /// </summary> /// <param name="dateTime">The date and time to test.</param> /// <returns>True if the event begins at the given date and time</returns> public virtual bool OccursAt(IDateTime dateTime) { return _mEvaluator.Periods.Any(p => p.StartTime.Equals(dateTime)); } /// <summary> /// Determines whether or not the <see cref="CalendarEvent"/> is actively displayed /// as an upcoming or occurred event. /// </summary> /// <returns>True if the event has not been cancelled, False otherwise.</returns> public virtual bool IsActive => string.Equals(Status, EventStatus.Cancelled, EventStatus.Comparison); protected override bool EvaluationIncludesReferenceDate => true; protected override void OnDeserializing(StreamingContext context) { base.OnDeserializing(context); Initialize(); } protected override void OnDeserialized(StreamingContext context) { base.OnDeserialized(context); ExtrapolateTimes(); } private void ExtrapolateTimes() { if (DtEnd == null && DtStart != null && Duration != default(TimeSpan)) { DtEnd = DtStart.Add(Duration); } else if (Duration == default(TimeSpan) && DtStart != null && DtEnd != null) { Duration = DtEnd.Subtract(DtStart); } else if (DtStart == null && Duration != default(TimeSpan) && DtEnd != null) { DtStart = DtEnd.Subtract(Duration); } } protected bool Equals(CalendarEvent other) { var resourcesSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); resourcesSet.UnionWith(Resources); var result = Equals(DtStart, other.DtStart) && string.Equals(Summary, other.Summary, StringComparison.OrdinalIgnoreCase) && string.Equals(Description, other.Description, StringComparison.OrdinalIgnoreCase) && Equals(DtEnd, other.DtEnd) && string.Equals(Location, other.Location, StringComparison.OrdinalIgnoreCase) && resourcesSet.SetEquals(other.Resources) && string.Equals(Status, other.Status, StringComparison.Ordinal) && IsActive == other.IsActive && string.Equals(Transparency, other.Transparency, TransparencyType.Comparison) && EvaluationIncludesReferenceDate == other.EvaluationIncludesReferenceDate && Attachments.SequenceEqual(other.Attachments) && CollectionHelpers.Equals(ExceptionRules, other.ExceptionRules) && CollectionHelpers.Equals(RecurrenceRules, other.RecurrenceRules); if (!result) { return false; } //RDATEs and EXDATEs are all List<PeriodList>, because the spec allows for multiple declarations of collections. //Consequently we have to contrive a normalized representation before we can determine whether two events are equal var exDates = PeriodList.GetGroupedPeriods(ExceptionDates); var otherExDates = PeriodList.GetGroupedPeriods(other.ExceptionDates); if (exDates.Keys.Count != otherExDates.Keys.Count || !exDates.Keys.OrderBy(k => k).SequenceEqual(otherExDates.Keys.OrderBy(k => k))) { return false; } if (exDates.Any(exDate => !exDate.Value.OrderBy(d => d).SequenceEqual(otherExDates[exDate.Key].OrderBy(d => d)))) { return false; } var rDates = PeriodList.GetGroupedPeriods(RecurrenceDates); var otherRDates = PeriodList.GetGroupedPeriods(other.RecurrenceDates); if (rDates.Keys.Count != otherRDates.Keys.Count || !rDates.Keys.OrderBy(k => k).SequenceEqual(otherRDates.Keys.OrderBy(k => k))) { return false; } if (rDates.Any(exDate => !exDate.Value.OrderBy(d => d).SequenceEqual(otherRDates[exDate.Key].OrderBy(d => d)))) { return false; } return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((CalendarEvent)obj); } public override int GetHashCode() { unchecked { var hashCode = DtStart?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ (Summary?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Description?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (DtEnd?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Location?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ Status?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ IsActive.GetHashCode(); hashCode = (hashCode * 397) ^ Transparency?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(Attachments); hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(Resources); hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCodeForNestedCollection(ExceptionDates); hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(ExceptionRules); hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCodeForNestedCollection(RecurrenceDates); hashCode = (hashCode * 397) ^ CollectionHelpers.GetHashCode(RecurrenceRules); return hashCode; } } public int CompareTo(CalendarEvent other) { if (DtStart.Equals(other.DtStart)) { return 0; } if (DtStart.LessThan(other.DtStart)) { return -1; } if (DtStart.GreaterThan(other.DtStart)) { return 1; } throw new Exception("An error occurred while comparing two CalDateTimes."); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Latency.Algo File: LatencyManager.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Latency { using System; using System.Collections.Generic; using Ecng.Common; using Ecng.Collections; using Ecng.Serialization; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Orders registration delay calculation manager. /// </summary> public class LatencyManager : ILatencyManager { private readonly SyncObject _syncObject = new SyncObject(); private readonly Dictionary<long, DateTimeOffset> _register = new Dictionary<long, DateTimeOffset>(); private readonly Dictionary<long, DateTimeOffset> _cancel = new Dictionary<long, DateTimeOffset>(); /// <summary> /// Initializes a new instance of the <see cref="LatencyManager"/>. /// </summary> public LatencyManager() { } /// <summary> /// The aggregate value of registration delay by all orders. /// </summary> public virtual TimeSpan LatencyRegistration { get; private set; } /// <summary> /// The aggregate value of cancelling delay by all orders. /// </summary> public virtual TimeSpan LatencyCancellation { get; private set; } /// <summary> /// To process the message for transaction delay calculation. Messages of types <see cref="OrderRegisterMessage"/>, <see cref="OrderReplaceMessage"/>, <see cref="OrderPairReplaceMessage"/>, <see cref="OrderCancelMessage"/> and <see cref="ExecutionMessage"/> are accepted. /// </summary> /// <param name="message">Message.</param> /// <returns>Transaction delay.</returns> public TimeSpan? ProcessMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { Reset(); break; } case MessageTypes.OrderRegister: { var regMsg = (OrderRegisterMessage)message; lock (_syncObject) { AddRegister(regMsg.TransactionId, regMsg.LocalTime); } break; } case MessageTypes.OrderReplace: { var replaceMsg = (OrderReplaceMessage)message; lock (_syncObject) { AddCancel(replaceMsg.TransactionId, replaceMsg.LocalTime); AddRegister(replaceMsg.TransactionId, replaceMsg.LocalTime); } break; } case MessageTypes.OrderPairReplace: { var replaceMsg = (OrderPairReplaceMessage)message; lock (_syncObject) { AddCancel(replaceMsg.Message1.TransactionId, replaceMsg.LocalTime); AddRegister(replaceMsg.Message1.TransactionId, replaceMsg.LocalTime); AddCancel(replaceMsg.Message2.TransactionId, replaceMsg.LocalTime); AddRegister(replaceMsg.Message2.TransactionId, replaceMsg.LocalTime); } break; } case MessageTypes.OrderCancel: { var cancelMsg = (OrderCancelMessage)message; lock (_syncObject) AddCancel(cancelMsg.TransactionId, cancelMsg.LocalTime); break; } case MessageTypes.Execution: { var execMsg = (ExecutionMessage)message; if (execMsg.HasOrderInfo()) { if (execMsg.OrderState == OrderStates.Pending) return null; lock (_syncObject) { var time = _register.TryGetValue2(execMsg.OriginalTransactionId); if (time == null) { time = _cancel.TryGetValue2(execMsg.OriginalTransactionId); if (time != null) { _cancel.Remove(execMsg.OriginalTransactionId); if (execMsg.OrderState == OrderStates.Failed) return null; return execMsg.LocalTime - time; } } else { _register.Remove(execMsg.OriginalTransactionId); if (execMsg.OrderState == OrderStates.Failed) return null; return execMsg.LocalTime - time; } } } break; } } return null; } private void AddRegister(long transactionId, DateTimeOffset localTime) { if (transactionId == 0) throw new ArgumentNullException(nameof(transactionId)); if (localTime.IsDefault()) throw new ArgumentNullException(nameof(localTime)); if (_register.ContainsKey(transactionId)) throw new ArgumentException(LocalizedStrings.Str1106Params.Put(transactionId), nameof(transactionId)); _register.Add(transactionId, localTime); } private void AddCancel(long transactionId, DateTimeOffset localTime) { if (transactionId == 0) throw new ArgumentNullException(nameof(transactionId)); if (localTime.IsDefault()) throw new ArgumentNullException(nameof(localTime)); if (_cancel.ContainsKey(transactionId)) throw new ArgumentException(LocalizedStrings.Str1107Params.Put(transactionId), nameof(transactionId)); _cancel.Add(transactionId, localTime); } /// <summary> /// To zero calculations. /// </summary> public virtual void Reset() { LatencyRegistration = LatencyCancellation = TimeSpan.Zero; } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Storage.</param> public void Load(SettingsStorage storage) { } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Storage.</param> public void Save(SettingsStorage storage) { } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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.Diagnostics; using System.Text; using SharpDX.Collections; namespace SharpDX.Diagnostics { /// <summary> /// Event args for <see cref="ComObject"/> used by <see cref="ObjectTracker"/>. /// </summary> public class ComObjectEventArgs : EventArgs { /// <summary> /// The object being tracked/untracked. /// </summary> public ComObject Object; /// <summary> /// Initializes a new instance of the <see cref="ComObjectEventArgs"/> class. /// </summary> /// <param name="o">The o.</param> public ComObjectEventArgs(ComObject o) { Object = o; } } /// <summary> /// Track all allocated objects. /// </summary> public static class ObjectTracker { private static Dictionary<IntPtr, List<ObjectReference>> processGlobalObjectReferences; [ThreadStatic] private static Dictionary<IntPtr, List<ObjectReference>> threadStaticObjectReferences; /// <summary> /// Occurs when a ComObject is tracked. /// </summary> public static event EventHandler<ComObjectEventArgs> Tracked; /// <summary> /// Occurs when a ComObject is untracked. /// </summary> public static event EventHandler<ComObjectEventArgs> UnTracked; #if !W8CORE /// <summary> /// Initializes the <see cref="ObjectTracker"/> class. /// </summary> static ObjectTracker() { AppDomain.CurrentDomain.DomainUnload += OnProcessExit; AppDomain.CurrentDomain.ProcessExit += OnProcessExit; } /// <summary> /// Called when [process exit]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> static void OnProcessExit(object sender, EventArgs e) { if (Configuration.EnableObjectTracking) { var text = ReportActiveObjects(); if (!string.IsNullOrEmpty(text)) Console.WriteLine(text); } } #endif private static Dictionary<IntPtr, List<ObjectReference>> ObjectReferences { get { Dictionary<IntPtr, List<ObjectReference>> objectReferences; if (Configuration.UseThreadStaticObjectTracking) { if (threadStaticObjectReferences == null) threadStaticObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = threadStaticObjectReferences; } else { if (processGlobalObjectReferences == null) processGlobalObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = processGlobalObjectReferences; } return objectReferences; } } /// <summary> /// Tracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void Track(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (!ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { referenceList = new List<ObjectReference>(); ObjectReferences.Add(comObject.NativePointer, referenceList); } #if W8CORE referenceList.Add(new ObjectReference(DateTime.Now, comObject, "Not Available on this platform")); #else var stackTraceText = new StringBuilder(); var stackTrace = new StackTrace(3, true); foreach (var stackFrame in stackTrace.GetFrames()) { // Skip system/generated frame if (stackFrame.GetFileLineNumber() == 0) continue; stackTraceText.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "\t{0}({1},{2}) : {3}", stackFrame.GetFileName(), stackFrame.GetFileLineNumber(), stackFrame.GetFileColumnNumber(), stackFrame.GetMethod()).AppendLine(); } referenceList.Add(new ObjectReference(DateTime.Now, comObject, stackTraceText.ToString())); #endif // Fire Tracked event. OnTracked(comObject); } } /// <summary> /// Finds a list of object reference from a specified COM object pointer. /// </summary> /// <param name="comObjectPtr">The COM object pointer.</param> /// <returns>A list of object reference</returns> public static List<ObjectReference> Find(IntPtr comObjectPtr) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObjectPtr, out referenceList)) return new List<ObjectReference>(referenceList); } return new List<ObjectReference>(); } /// <summary> /// Finds the object reference for a specific COM object. /// </summary> /// <param name="comObject">The COM object.</param> /// <returns>An object reference</returns> public static ObjectReference Find(ComObject comObject) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { foreach (var objectReference in referenceList) { if (ReferenceEquals(objectReference.Object.Target, comObject)) return objectReference; } } } return null; } /// <summary> /// Untracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void UnTrack(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { for (int i = referenceList.Count-1; i >=0; i--) { var objectReference = referenceList[i]; if (ReferenceEquals(objectReference.Object.Target, comObject)) referenceList.RemoveAt(i); else if (!objectReference.IsAlive) referenceList.RemoveAt(i); } // Remove empty list if (referenceList.Count == 0) ObjectReferences.Remove(comObject.NativePointer); // Fire UnTracked event OnUnTracked(comObject); } } } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static List<ObjectReference> FindActiveObjects() { var activeObjects = new List<ObjectReference>(); lock (ObjectReferences) { foreach (var referenceList in ObjectReferences.Values) { foreach (var objectReference in referenceList) { if (objectReference.IsAlive) activeObjects.Add(objectReference); } } } return activeObjects; } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static string ReportActiveObjects() { var text = new StringBuilder(); int count = 0; var countPerType = new Dictionary<string, int>(); foreach (var findActiveObject in FindActiveObjects()) { var findActiveObjectStr = findActiveObject.ToString(); if (!string.IsNullOrEmpty(findActiveObjectStr)) { text.AppendFormat("[{0}]: {1}", count, findActiveObjectStr); var target = findActiveObject.Object.Target; if (target != null) { int typeCount; var targetType = target.GetType().Name; if (!countPerType.TryGetValue(targetType, out typeCount)) { countPerType[targetType] = 0; } countPerType[targetType] = typeCount + 1; } } count++; } var keys = new List<string>(countPerType.Keys); keys.Sort(); text.AppendLine(); text.AppendLine("Count per Type:"); foreach (var key in keys) { text.AppendFormat("{0} : {1}", key, countPerType[key]); text.AppendLine(); } return text.ToString(); } private static void OnTracked(ComObject obj) { var handler = Tracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } private static void OnUnTracked(ComObject obj) { var handler = UnTracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; namespace ZXing.QrCode.Internal { /// <summary> /// <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square /// markers at three corners of a QR Code.</p> /// /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object. /// </summary> /// <author>Sean Owen</author> public class FinderPatternFinder { private const int CENTER_QUORUM = 2; /// <summary> /// 1 pixel/module times 3 modules/center /// </summary> protected internal const int MIN_SKIP = 3; /// <summary> /// support up to version 10 for mobile clients /// </summary> protected internal const int MAX_MODULES = 57; private const int INTEGER_MATH_SHIFT = 8; private readonly BitMatrix image; private List<FinderPattern> possibleCenters; private bool hasSkipped; private readonly int[] crossCheckStateCount; private readonly ResultPointCallback resultPointCallback; /// <summary> /// <p>Creates a finder that will search the image for three finder patterns.</p> /// </summary> /// <param name="image">image to search</param> public FinderPatternFinder(BitMatrix image) : this(image, null) { } /// <summary> /// Initializes a new instance of the <see cref="FinderPatternFinder"/> class. /// </summary> /// <param name="image">The image.</param> /// <param name="resultPointCallback">The result point callback.</param> public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) { this.image = image; this.possibleCenters = new List<FinderPattern>(); this.crossCheckStateCount = new int[5]; this.resultPointCallback = resultPointCallback; } /// <summary> /// Gets the image. /// </summary> virtual protected internal BitMatrix Image { get { return image; } } /// <summary> /// Gets the possible centers. /// </summary> virtual protected internal List<FinderPattern> PossibleCenters { get { return possibleCenters; } } internal virtual FinderPatternInfo find(IDictionary<DecodeHintType, object> hints) { bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); int maxI = image.Height; int maxJ = image.Width; // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (3 * maxI) / (4 * MAX_MODULES); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } bool done = false; int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; int currentState = 0; for (int j = 0; j < maxJ; j++) { if (image[j, i]) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes bool confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. iSkip = 2; if (hasSkipped) { done = haveMultiplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; continue; } // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (foundPatternCross(stateCount)) { bool confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped) { // Found a third one done = haveMultiplyConfirmedCenters(); } } } } FinderPattern[] patternInfo = selectBestPatterns(); if (patternInfo == null) return null; ResultPoint.orderBestPatterns(patternInfo); return new FinderPatternInfo(patternInfo); } /// <summary> Given a count of black/white/black/white/black pixels just seen and an end position, /// figures the location of the center of this run. /// </summary> private static float? centerFromEnd(int[] stateCount, int end) { var result = (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; if (Single.IsNaN(result)) return null; return result; } /// <param name="stateCount">count of black/white/black/white/black pixels just read /// </param> /// <returns> true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios /// used by finder patterns to be considered a match /// </returns> protected internal static bool foundPatternCross(int[] stateCount) { int totalModuleSize = 0; for (int i = 0; i < 5; i++) { int count = stateCount[i]; if (count == 0) { return false; } totalModuleSize += count; } if (totalModuleSize < 7) { return false; } int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; int maxVariance = moduleSize / 2; // Allow less than 50% variance from 1-1-3-1-1 proportions return Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; } private int[] CrossCheckStateCount { get { crossCheckStateCount[0] = 0; crossCheckStateCount[1] = 0; crossCheckStateCount[2] = 0; crossCheckStateCount[3] = 0; crossCheckStateCount[4] = 0; return crossCheckStateCount; } } /// <summary> /// <p>After a horizontal scan finds a potential finder pattern, this method /// "cross-checks" by scanning down vertically through the center of the possible /// finder pattern to see if the same proportion is detected.</p> /// </summary> /// <param name="startI">row where a finder pattern was detected</param> /// <param name="centerJ">center of the section that appears to cross a finder pattern</param> /// <param name="maxCount">maximum reasonable number of modules that should be /// observed in any reading state, based on the results of the horizontal scan</param> /// <param name="originalStateCountTotal">The original state count total.</param> /// <returns> /// vertical center of finder pattern, or null if not found /// </returns> private float? crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { int maxI = image.Height; int[] stateCount = CrossCheckStateCount; // Start counting up from center int i = startI; while (i >= 0 && image[centerJ, i]) { stateCount[2]++; i--; } if (i < 0) { return null; } while (i >= 0 && !image[centerJ, i] && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return null; } while (i >= 0 && image[centerJ, i] && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return null; } // Now also count down from center i = startI + 1; while (i < maxI && image[centerJ, i]) { stateCount[2]++; i++; } if (i == maxI) { return null; } while (i < maxI && !image[centerJ, i] && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i == maxI || stateCount[3] >= maxCount) { return null; } while (i < maxI && image[centerJ, i] && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return null; } // If we found a finder-pattern-like section, but its size is more than 40% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return null; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : null; } /// <summary> <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, /// except it reads horizontally instead of vertically. This is used to cross-cross /// check a vertical cross check and locate the real center of the alignment pattern.</p> /// </summary> private float? crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) { int maxJ = image.Width; int[] stateCount = CrossCheckStateCount; int j = startJ; while (j >= 0 && image[j, centerI]) { stateCount[2]++; j--; } if (j < 0) { return null; } while (j >= 0 && !image[j, centerI] && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return null; } while (j >= 0 && image[j, centerI] && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return null; } j = startJ + 1; while (j < maxJ && image[j, centerI]) { stateCount[2]++; j++; } if (j == maxJ) { return null; } while (j < maxJ && !image[j, centerI] && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j == maxJ || stateCount[3] >= maxCount) { return null; } while (j < maxJ && image[j, centerI] && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return null; } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return null; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : null; } /// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will /// cross check with a vertical scan, and if successful, will, ah, cross-cross-check /// with another horizontal scan. This is needed primarily to locate the real horizontal /// center of the pattern in cases of extreme skew.</p> /// /// If that succeeds the finder pattern location is added to a list that tracks /// the number of times each location has been nearly-matched as a finder pattern. /// Each additional find is more evidence that the location is in fact a finder /// pattern center /// /// </summary> /// <param name="stateCount">reading state module counts from horizontal scan /// </param> /// <param name="i">row where finder pattern may be found /// </param> /// <param name="j">end of possible finder pattern in row /// </param> /// <returns> true if a finder pattern candidate was found this time /// </returns> protected bool handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; float? centerJ = centerFromEnd(stateCount, j); if (centerJ == null) return false; float? centerI = crossCheckVertical(i, (int)centerJ.Value, stateCount[2], stateCountTotal); if (centerI != null) { // Re-cross check centerJ = crossCheckHorizontal((int)centerJ.Value, (int)centerI.Value, stateCount[2], stateCountTotal); if (centerJ != null) { float estimatedModuleSize = stateCountTotal / 7.0f; bool found = false; for (int index = 0; index < possibleCenters.Count; index++) { var center = possibleCenters[index]; // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI.Value, centerJ.Value)) { possibleCenters.RemoveAt(index); possibleCenters.Insert(index, center.combineEstimate(centerI.Value, centerJ.Value, estimatedModuleSize)); found = true; break; } } if (!found) { var point = new FinderPattern(centerJ.Value, centerI.Value, estimatedModuleSize); possibleCenters.Add(point); if (resultPointCallback != null) { resultPointCallback(point); } } return true; } } return false; } /// <returns> number of rows we could safely skip during scanning, based on the first /// two finder patterns that have been located. In some cases their position will /// allow us to infer that the third pattern must lie below a certain point farther /// down in the image. /// </returns> private int findRowSkip() { int max = possibleCenters.Count; if (max <= 1) { return 0; } FinderPattern firstConfirmedCenter = null; foreach (var center in possibleCenters) { if (center.Count >= CENTER_QUORUM) { if (firstConfirmedCenter == null) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left last. hasSkipped = true; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (int)(Math.Abs(firstConfirmedCenter.X - center.X) - Math.Abs(firstConfirmedCenter.Y - center.Y)) / 2; } } } return 0; } /// <returns> true iff we have found at least 3 finder patterns that have been detected /// at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the /// candidates is "pretty similar" /// </returns> private bool haveMultiplyConfirmedCenters() { int confirmedCount = 0; float totalModuleSize = 0.0f; int max = possibleCenters.Count; foreach (var pattern in possibleCenters) { if (pattern.Count >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern.EstimatedModuleSize; } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 5% of the total module size estimates, it's too much. float average = totalModuleSize / max; float totalDeviation = 0.0f; for (int i = 0; i < max; i++) { var pattern = possibleCenters[i]; totalDeviation += Math.Abs(pattern.EstimatedModuleSize - average); } return totalDeviation <= 0.05f * totalModuleSize; } /// <returns> the 3 best {@link FinderPattern}s from our list of candidates. The "best" are /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module /// size differs from the average among those patterns the least /// </returns> private FinderPattern[] selectBestPatterns() { int startSize = possibleCenters.Count; if (startSize < 3) { // Couldn't find enough finder patterns return null; } // Filter outlier possibilities whose module size is too different if (startSize > 3) { // But we can only afford to do so if we have at least 4 possibilities to choose from float totalModuleSize = 0.0f; float square = 0.0f; foreach (var center in possibleCenters) { float size = center.EstimatedModuleSize; totalModuleSize += size; square += size * size; } float average = totalModuleSize / startSize; float stdDev = (float)Math.Sqrt(square / startSize - average * average); possibleCenters.Sort(new FurthestFromAverageComparator(average)); float limit = Math.Max(0.2f * average, stdDev); for (int i = 0; i < possibleCenters.Count && possibleCenters.Count > 3; i++) { FinderPattern pattern = possibleCenters[i]; if (Math.Abs(pattern.EstimatedModuleSize - average) > limit) { possibleCenters.RemoveAt(i); i--; } } } if (possibleCenters.Count > 3) { // Throw away all but those first size candidate points we found. float totalModuleSize = 0.0f; foreach (var possibleCenter in possibleCenters) { totalModuleSize += possibleCenter.EstimatedModuleSize; } float average = totalModuleSize / possibleCenters.Count; possibleCenters.Sort(new CenterComparator(average)); //possibleCenters.subList(3, possibleCenters.Count).clear(); possibleCenters = possibleCenters.GetRange(0, 3); } return new[] { possibleCenters[0], possibleCenters[1], possibleCenters[2] }; } /// <summary> /// Orders by furthest from average /// </summary> private sealed class FurthestFromAverageComparator : IComparer<FinderPattern> { private readonly float average; public FurthestFromAverageComparator(float f) { average = f; } public int Compare(FinderPattern x, FinderPattern y) { float dA = Math.Abs(y.EstimatedModuleSize - average); float dB = Math.Abs(x.EstimatedModuleSize - average); return dA < dB ? -1 : dA == dB ? 0 : 1; } } /// <summary> <p>Orders by {@link FinderPattern#getCount()}, descending.</p></summary> private sealed class CenterComparator : IComparer<FinderPattern> { private readonly float average; public CenterComparator(float f) { average = f; } public int Compare(FinderPattern x, FinderPattern y) { if (y.Count == x.Count) { float dA = Math.Abs(y.EstimatedModuleSize - average); float dB = Math.Abs(x.EstimatedModuleSize - average); return dA < dB ? 1 : dA == dB ? 0 : -1; } return y.Count - x.Count; } } } }
using System; using System.Collections.Generic; using Cake.Core; using Cake.Core.IO; using Cake.Curl.Tests.Fixtures; using Cake.Testing; using Xunit; namespace Cake.Curl.Tests { public sealed class CurlDownloadFileTests { public sealed class TheExecutable { [Fact] public void Should_Throw_If_Host_Is_Null() { // Given var fixture = new CurlDownloadFileFixture(); fixture.Host = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<ArgumentNullException>(result); Assert.Equal("host", ((ArgumentNullException)result).ParamName); } [Fact] public void Should_Throw_If_Settings_Is_Null() { // Given var fixture = new CurlDownloadFileFixture(); fixture.Settings = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<ArgumentNullException>(result); Assert.Equal("settings", ((ArgumentNullException)result).ParamName); } [Fact] public void Should_Throw_If_Curl_Executable_Was_Not_Found() { // Given var fixture = new CurlDownloadFileFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("curl: Could not locate executable.", result.Message); } [Theory] [InlineData("/bin/curl", "/bin/curl")] [InlineData("./tools/curl", "/Working/tools/curl")] public void Should_Use_Curl_Runner_From_Tool_Path_If_Provided( string toolPath, string expected) { // Given var fixture = new CurlDownloadFileFixture { Settings = { ToolPath = toolPath } }; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } #if NETFX [Theory] [InlineData(@"C:\bin\curl.exe", "C:/bin/curl.exe")] [InlineData(@".\tools\curl.exe", "/Working/tools/curl.exe")] public void Should_Use_Curl_Runner_From_Tool_Path_If_Provided_On_Windows( string toolPath, string expected) { // Given var fixture = new CurlDownloadFileFixture { Settings = { ToolPath = toolPath } }; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } #endif [Fact] public void Should_Find_Curl_Runner_If_Tool_Path_Not_Provided() { // Given var fixture = new CurlDownloadFileFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/curl", result.Path.FullPath); } [Fact] public void Should_Set_The_Remote_Name_Switch_And_The_Url_Of_The_Host_As_Arguments() { // Given var fixture = new CurlDownloadFileFixture { Host = new Uri("protocol://host/path") }; // When var result = fixture.Run(); // Then Assert.Contains("-O protocol://host/path", result.Args); } [Fact] public void Should_Set_The_Absolute_Output_File_Path_In_Quotes_And_The_Url_Of_The_Host_As_Arguments() { // Given var fixture = new CurlDownloadFileFixture { Host = new Uri("protocol://host/path"), Settings = { OutputPaths = new FilePath[] { "output/file" } } }; // When var result = fixture.Run(); // Then Assert.Contains( "-o \"/Working/output/file\" protocol://host/path", result.Args); } [Fact] public void Should_Set_The_User_Credentials_In_Quotes_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Username = "user", Password = "password" } }; // When var result = fixture.Run(); // Then Assert.Contains("--user \"user:password\"", result.Args); } [Fact] public void Should_Redact_The_User_Password_In_The_Safe_Arguments() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Username = "user", Password = "password" } }; // When var result = fixture.Run(); // Then Assert.Contains("--user \"user:[REDACTED]\"", result.SafeArgs); } [Fact] public void Should_Not_Set_The_User_Credentials_As_Argument_If_Username_Is_Null() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Username = null, Password = "password" } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--user", result.Args); } [Fact] public void Should_Set_The_Verbose_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Verbose = true } }; // When var result = fixture.Run(); // Then Assert.Contains("--verbose", result.Args); } [Fact] public void Should_Set_The_Progress_Bar_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { ProgressBar = true } }; // When var result = fixture.Run(); // Then Assert.Contains("--progress-bar", result.Args); } [Fact] public void Should_Set_The_Headers_In_Quotes_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Headers = new Dictionary<string, string> { ["name"] = "value" } } }; // When var result = fixture.Run(); // Then Assert.Contains("--header \"name:value\"", result.Args); } [Fact] public void Should_Set_Multiple_Headers_In_Quotes_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Headers = new Dictionary<string, string> { ["name1"] = "value1", ["name2"] = "value2", ["name3"] = "value3" } } }; // When var result = fixture.Run(); // Then Assert.Contains("--header \"name1:value1\" --header \"name2:value2\" --header \"name3:value3\"", result.Args); } [Fact] public void Should_Set_The_Request_Command_In_Quotes_And_Upper_Case_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RequestCommand = "Command" } }; // When var result = fixture.Run(); // Then Assert.Contains("--request \"COMMAND\"", result.Args); } [Fact] public void Should_Set_The_Location_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { FollowRedirects = true } }; // When var result = fixture.Run(); // Then Assert.Contains("--location", result.Args); } [Fact] public void Should_Not_Set_The_Location_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { FollowRedirects = false } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--location", result.Args); } [Fact] public void Should_Set_The_Fail_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Fail = true } }; // When var result = fixture.Run(); // Then Assert.Contains("--fail", result.Args); } [Fact] public void Should_Not_Set_The_Fail_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { Fail = false } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--fail", result.Args); } [Fact] public void Should_Set_The_Retry_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryCount = 3 } }; // When var result = fixture.Run(); // Then Assert.Contains("--retry 3", result.Args); } [Fact] public void Should_Not_Set_The_Retry_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryCount = 0 } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--retry", result.Args); } [Fact] public void Should_Set_The_RetryDelay_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryDelaySeconds = 30 } }; // When var result = fixture.Run(); // Then Assert.Contains("--retry-delay 30", result.Args); } [Fact] public void Should_Not_Set_The_RetryDelay_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryDelaySeconds = 0 } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--retry-delay", result.Args); } [Fact] public void Should_Set_The_RetryMaxTime_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryMaxTimeSeconds = 300 } }; // When var result = fixture.Run(); // Then Assert.Contains("--retry-max-time 300", result.Args); } [Fact] public void Should_Not_Set_The_RetryMaxTime_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryMaxTimeSeconds = 0 } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--retry-max-time", result.Args); } [Fact] public void Should_Set_The_RetryConnRefused_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryOnConnectionRefused = true } }; // When var result = fixture.Run(); // Then Assert.Contains("--retry-connrefused", result.Args); } [Fact] public void Should_Not_Set_The_RetryConnRefused_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { RetryOnConnectionRefused = false } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--retry-connrefused", result.Args); } [Fact] public void Should_Set_The_MaxTime_Option_As_Argument() { // Given var maxTime = TimeSpan.FromSeconds(2.37); var fixture = new CurlDownloadFileFixture { Settings = { MaxTime = maxTime } }; // When var result = fixture.Run(); // Then Assert.Contains( $"--max-time {maxTime.TotalSeconds}", result.Args); } [Fact] public void Should_Not_Set_The_MaxTime_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { MaxTime = null } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--max-time", result.Args); } [Fact] public void Should_Set_The_ConnectTimeout_Option_As_Argument() { // Given var connectionTimeout = TimeSpan.FromSeconds(5.5); var fixture = new CurlDownloadFileFixture { Settings = { ConnectionTimeout = connectionTimeout } }; // When var result = fixture.Run(); // Then Assert.Contains( $"--connect-timeout {connectionTimeout.TotalSeconds}", result.Args); } [Fact] public void Should_Not_Set_The_ConnectTimeout_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { ConnectionTimeout = null } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--connect-timeout", result.Args); } [Fact] public void Should_Set_The_CreateDirs_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { CreateDirectories = true } }; // When var result = fixture.Run(); // Then Assert.Contains("--create-dirs", result.Args); } [Fact] public void Should_Not_Set_The_CreateDirs_Option_As_Argument() { // Given var fixture = new CurlDownloadFileFixture { Settings = { CreateDirectories = false } }; // When var result = fixture.Run(); // Then Assert.DoesNotContain("--create-dirs", result.Args); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //============================================================================= // // Class: HResults // // Purpose: Define HResult constants. Every exception has one of these. // // Date: 98/08/31 11:57:11 AM // //===========================================================================*/ using System; namespace System { // Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that // range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc). // In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type // HResults. Also note that some of our HResults have to map to certain // COM HR's, etc. // Another arbitrary decision... Feel free to change this, as long as you // renumber the HResults yourself (and update rexcep.h). // Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f. // Security will use 0x1640 -> 0x165f // There are HResults files in the IO, Remoting, Reflection & // Security/Util directories as well, so choose your HResults carefully. internal static class HResults { internal const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54); internal const int CLDB_E_FILE_CORRUPT = unchecked((int)0x8013110e); internal const int CLDB_E_FILE_OLDVER = unchecked((int)0x80131107); internal const int CLDB_E_INDEX_NOTFOUND = unchecked((int)0x80131124); internal const int CLR_E_BIND_ASSEMBLY_NOT_FOUND = unchecked((int)0x80132004); internal const int CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH = unchecked((int)0x80132001); internal const int CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW = unchecked((int)0x80132000); internal const int CLR_E_BIND_TYPE_NOT_FOUND = unchecked((int)0x80132005); internal const int CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT = unchecked((int)0x80132003); internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D); internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D); internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014); internal const int COR_E_APPLICATION = unchecked((int)0x80131600); internal const int COR_E_ARGUMENT = unchecked((int)0x80070057); internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502); internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216); internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503); internal const int COR_E_ASSEMBLYEXPECTED = unchecked((int)0x80131018); internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B); internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015); internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504); internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605); internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541); internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524); internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529); internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523); internal const int COR_E_EXCEPTION = unchecked((int)0x80131500); internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506); internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507); internal const int COR_E_FIXUPSINEXE = unchecked((int)0x80131019); internal const int COR_E_FORMAT = unchecked((int)0x80131537); internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508); internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578); internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002); internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527); internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601); internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531); internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509); internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153a); internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577); internal const int COR_E_LOADING_REFERENCE_ASSEMBLY = unchecked((int)0x80131058); internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535); internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A); internal const int COR_E_METHODACCESS = unchecked((int)0x80131510); internal const int COR_E_MISSINGFIELD = unchecked((int)0x80131511); internal const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532); internal const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512); internal const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513); internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536); internal const int COR_E_MODULE_HASH_CHECK_FAILED = unchecked((int)0x80131039); internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514); internal const int COR_E_NEWER_RUNTIME = unchecked((int)0x8013101b); internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528); internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515); internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003); internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622); internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B); internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int COR_E_OVERFLOW = unchecked((int)0x80131516); internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539); internal const int COR_E_RANK = unchecked((int)0x80131517); internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602); internal const int COR_E_REMOTING = unchecked((int)0x8013150b); internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153e); internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538); internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533); internal const int COR_E_SECURITY = unchecked((int)0x8013150A); internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C); internal const int COR_E_SERVER = unchecked((int)0x8013150e); internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9); internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518); internal const int COR_E_SYSTEM = unchecked((int)0x80131501); internal const int COR_E_TARGET = unchecked((int)0x80131603); internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604); internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e); internal const int COR_E_THREADABORTED = unchecked((int)0x80131530); internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519); internal const int COR_E_THREADSTART = unchecked((int)0x80131525); internal const int COR_E_THREADSTATE = unchecked((int)0x80131520); internal const int COR_E_TIMEOUT = unchecked((int)0x80131505); internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543); internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534); internal const int COR_E_TYPELOAD = unchecked((int)0x80131522); internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013); internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005); internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D); internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C); internal const int CORSEC_E_CRYPTO = unchecked((int)0x80131430); internal const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431); internal const int CORSEC_E_INVALID_IMAGE_FORMAT = unchecked((int)0x8013141d); internal const int CORSEC_E_INVALID_PUBLICKEY = unchecked((int)0x8013141e); internal const int CORSEC_E_INVALID_STRONGNAME = unchecked((int)0x8013141a); internal const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417); internal const int CORSEC_E_MISSING_STRONGNAME = unchecked((int)0x8013141b); internal const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418); internal const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416); internal const int CORSEC_E_SIGNATURE_MISMATCH = unchecked((int)0x80131420); internal const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131419); internal const int CTL_E_DEVICEIOERROR = unchecked((int)0x800A0039); internal const int CTL_E_DIVISIONBYZERO = unchecked((int)0x800A000B); internal const int CTL_E_FILENOTFOUND = unchecked((int)0x800A0035); internal const int CTL_E_OUTOFMEMORY = unchecked((int)0x800A0007); internal const int CTL_E_OUTOFSTACKSPACE = unchecked((int)0x800A001C); internal const int CTL_E_OVERFLOW = unchecked((int)0x800A0006); internal const int CTL_E_PATHFILEACCESSERROR = unchecked((int)0x800A004B); internal const int CTL_E_PATHNOTFOUND = unchecked((int)0x800A004C); internal const int CTL_E_PERMISSIONDENIED = unchecked((int)0x800A0046); internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F); internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E); internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_HANDLE = unchecked((int)0x80070006); internal const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018); internal const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000E); internal const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000D); internal const int E_INVALIDARG = unchecked((int)0x80070057); internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014); internal const int E_NOTIMPL = unchecked((int)0x80004001); internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int E_POINTER = unchecked((int)0x80004003L); internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A); internal const int ERROR_BAD_EXE_FORMAT = unchecked((int)0x800700C1); internal const int ERROR_BAD_NET_NAME = unchecked((int)0x80070043); internal const int ERROR_BAD_NETPATH = unchecked((int)0x80070035); internal const int ERROR_DISK_CORRUPT = unchecked((int)0x80070571); internal const int ERROR_DLL_INIT_FAILED = unchecked((int)0x8007045A); internal const int ERROR_DLL_NOT_FOUND = unchecked((int)0x80070485); internal const int ERROR_EXE_MARKED_INVALID = unchecked((int)0x800700C0); internal const int ERROR_FILE_CORRUPT = unchecked((int)0x80070570); internal const int ERROR_FILE_INVALID = unchecked((int)0x800703EE); internal const int ERROR_FILE_NOT_FOUND = unchecked((int)0x80070002); internal const int ERROR_INVALID_DLL = unchecked((int)0x80070482); internal const int ERROR_INVALID_NAME = unchecked((int)0x8007007B); internal const int ERROR_INVALID_ORDINAL = unchecked((int)0x800700B6); internal const int ERROR_INVALID_PARAMETER = unchecked((int)0x80070057); internal const int ERROR_LOCK_VIOLATION = unchecked((int)0x80070021); internal const int ERROR_MOD_NOT_FOUND = unchecked((int)0x8007007E); internal const int ERROR_NO_UNICODE_TRANSLATION = unchecked((int)0x80070459); internal const int ERROR_NOACCESS = unchecked((int)0x800703E6); internal const int ERROR_NOT_READY = unchecked((int)0x80070015); internal const int ERROR_OPEN_FAILED = unchecked((int)0x8007006E); internal const int ERROR_PATH_NOT_FOUND = unchecked((int)0x80070003); internal const int ERROR_SHARING_VIOLATION = unchecked((int)0x80070020); internal const int ERROR_TOO_MANY_OPEN_FILES = unchecked((int)0x80070004); internal const int ERROR_UNRECOGNIZED_VOLUME = unchecked((int)0x800703ED); internal const int ERROR_WRONG_TARGET_NAME = unchecked((int)0x80070574); internal const int FUSION_E_ASM_MODULE_MISSING = unchecked((int)0x80131042); internal const int FUSION_E_CACHEFILE_FAILED = unchecked((int)0x80131052); internal const int FUSION_E_CODE_DOWNLOAD_DISABLED = unchecked((int)0x80131048); internal const int FUSION_E_HOST_GAC_ASM_MISMATCH = unchecked((int)0x80131050); internal const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal const int FUSION_E_INVALID_PRIVATE_ASM_LOCATION = unchecked((int)0x80131041); internal const int FUSION_E_LOADFROM_BLOCKED = unchecked((int)0x80131051); internal const int FUSION_E_PRIVATE_ASM_DISALLOWED = unchecked((int)0x80131044); internal const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040); internal const int FUSION_E_SIGNATURE_CHECK_FAILED = unchecked((int)0x80131045); internal const int INET_E_CANNOT_CONNECT = unchecked((int)0x800C0004); internal const int INET_E_CONNECTION_TIMEOUT = unchecked((int)0x800C000B); internal const int INET_E_DATA_NOT_AVAILABLE = unchecked((int)0x800C0007); internal const int INET_E_DOWNLOAD_FAILURE = unchecked((int)0x800C0008); internal const int INET_E_OBJECT_NOT_FOUND = unchecked((int)0x800C0006); internal const int INET_E_RESOURCE_NOT_FOUND = unchecked((int)0x800C0005); internal const int INET_E_UNKNOWN_PROTOCOL = unchecked((int)0x800C000D); internal const int ISS_E_ALLOC_TOO_LARGE = unchecked((int)0x80131484); internal const int ISS_E_BLOCK_SIZE_TOO_SMALL = unchecked((int)0x80131483); internal const int ISS_E_CALLER = unchecked((int)0x801314A1); internal const int ISS_E_CORRUPTED_STORE_FILE = unchecked((int)0x80131480); internal const int ISS_E_CREATE_DIR = unchecked((int)0x80131468); internal const int ISS_E_CREATE_MUTEX = unchecked((int)0x80131464); internal const int ISS_E_DEPRECATE = unchecked((int)0x801314A0); internal const int ISS_E_FILE_NOT_MAPPED = unchecked((int)0x80131482); internal const int ISS_E_FILE_WRITE = unchecked((int)0x80131466); internal const int ISS_E_GET_FILE_SIZE = unchecked((int)0x80131463); internal const int ISS_E_ISOSTORE = unchecked((int)0x80131450); internal const int ISS_E_LOCK_FAILED = unchecked((int)0x80131465); internal const int ISS_E_MACHINE = unchecked((int)0x801314A3); internal const int ISS_E_MACHINE_DACL = unchecked((int)0x801314A4); internal const int ISS_E_MAP_VIEW_OF_FILE = unchecked((int)0x80131462); internal const int ISS_E_OPEN_FILE_MAPPING = unchecked((int)0x80131461); internal const int ISS_E_OPEN_STORE_FILE = unchecked((int)0x80131460); internal const int ISS_E_PATH_LENGTH = unchecked((int)0x801314A2); internal const int ISS_E_SET_FILE_POINTER = unchecked((int)0x80131467); internal const int ISS_E_STORE_NOT_OPEN = unchecked((int)0x80131469); internal const int ISS_E_STORE_VERSION = unchecked((int)0x80131481); internal const int ISS_E_TABLE_ROW_NOT_FOUND = unchecked((int)0x80131486); internal const int ISS_E_USAGE_WILL_EXCEED_QUOTA = unchecked((int)0x80131485); internal const int META_E_BAD_SIGNATURE = unchecked((int)0x80131192); internal const int META_E_CA_FRIENDS_SN_REQUIRED = unchecked((int)0x801311e6); internal const int MSEE_E_ASSEMBLYLOADINPROGRESS = unchecked((int)0x80131016); internal const int RO_E_CLOSED = unchecked((int)0x80000013); internal const int E_BOUNDS = unchecked((int)0x8000000B); internal const int RO_E_METADATA_NAME_NOT_FOUND = unchecked((int)0x8000000F); internal const int SECURITY_E_INCOMPATIBLE_EVIDENCE = unchecked((int)0x80131403); internal const int SECURITY_E_INCOMPATIBLE_SHARE = unchecked((int)0x80131401); internal const int SECURITY_E_UNVERIFIABLE = unchecked((int)0x80131402); internal const int STG_E_PATHNOTFOUND = unchecked((int)0x80030003); public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003); public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined public const int COR_E_FILELOAD = unchecked((int)0x80131621); public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002); public const int COR_E_IO = unchecked((int)0x80131620); public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE); } }
using System; using System.Collections.Generic; using UnityEngine; namespace UMA { /// <summary> /// Class links UMA's bone data with Unity's transform hierarchy. /// </summary> [Serializable] public class UMASkeleton { /// <summary> /// Internal class for storing bone and transform information. /// </summary> [Serializable] public class BoneData { public int boneNameHash; public int parentBoneNameHash; public Transform boneTransform; public UMATransform umaTransform; public Quaternion rotation; public Vector3 position; public Vector3 scale; public int accessedFrame; } public IEnumerable<int> BoneHashes { get { return GetBoneHashes(); } } //DynamicUMADna:: DynamicUMADnaConverterCustomizer Editor interface needs to have an array of bone names public string[] BoneNames { get { return GetBoneNames(); } } protected bool updating; protected int frame; /// <value>The hash for the root bone of the skeleton.</value> public int rootBoneHash { get; protected set; } /// <value>The bone count.</value> public virtual int boneCount { get { return boneHashData.Count; } } public bool isUpdating { get { return updating; } } private Dictionary<int, BoneData> boneHashDataLookup; #if UNITY_EDITOR // Dictionary backup to support code reload private List<BoneData> boneHashDataBackup = new List<BoneData>(); #endif private Dictionary<int, BoneData> boneHashData { get { if (boneHashDataLookup == null) { boneHashDataLookup = new Dictionary<int, BoneData>(); #if UNITY_EDITOR foreach (BoneData tData in boneHashDataBackup) { boneHashDataLookup.Add(tData.boneNameHash, tData); } #endif } return boneHashDataLookup; } set { boneHashDataLookup = value; #if UNITY_EDITOR boneHashDataBackup = new List<BoneData>(value.Values); #endif } } /// <summary> /// Initializes a new UMASkeleton from a transform hierarchy. /// </summary> /// <param name="rootBone">Root transform.</param> public UMASkeleton(Transform rootBone) { rootBoneHash = UMAUtils.StringToHash(rootBone.name); this.boneHashData = new Dictionary<int, BoneData>(); BeginSkeletonUpdate(); AddBonesRecursive(rootBone); EndSkeletonUpdate(); } protected UMASkeleton() { } /// <summary> /// Marks the skeleton as being updated. /// </summary> public virtual void BeginSkeletonUpdate() { frame++; if (frame < 0) frame = 0; updating = true; } /// <summary> /// Marks the skeleton update as complete. /// </summary> public virtual void EndSkeletonUpdate() { foreach (var bd in boneHashData.Values) { bd.rotation = bd.boneTransform.localRotation; bd.position = bd.boneTransform.localPosition; bd.scale = bd.boneTransform.localScale; } updating = false; } public virtual void SetAnimatedBone(int nameHash) { // The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface. } public virtual void SetAnimatedBoneHierachy(int nameHash) { // The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface. } public virtual void ClearAnimatedBoneHierachy(int nameHash, bool recursive) { // The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface. } private void AddBonesRecursive(Transform transform) { var hash = UMAUtils.StringToHash(transform.name); var parentHash = transform.parent != null ? UMAUtils.StringToHash(transform.parent.name) : 0; BoneData data = new BoneData() { parentBoneNameHash = parentHash, boneNameHash = hash, accessedFrame = frame, boneTransform = transform, umaTransform = new UMATransform(transform, hash, parentHash) }; if (!boneHashData.ContainsKey(hash)) { boneHashData.Add(hash, data); #if UNITY_EDITOR boneHashDataBackup.Add(data); #endif } else Debug.LogError("AddBonesRecursive: " + transform.name + " already exists in the dictionary!"); for (int i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); AddBonesRecursive(child); } } protected virtual BoneData GetBone(int nameHash) { BoneData data = null; boneHashData.TryGetValue(nameHash, out data); return data; } /// <summary> /// Does this skeleton contains bone with specified name hash? /// </summary> /// <returns><c>true</c> if this instance has bone the specified name hash; otherwise, <c>false</c>.</returns> /// <param name="nameHash">Name hash.</param> public virtual bool HasBone(int nameHash) { return boneHashData.ContainsKey(nameHash); } /// <summary> /// Adds the transform into the skeleton. /// </summary> /// <param name="parentHash">Hash of parent transform name.</param> /// <param name="hash">Hash of transform name.</param> /// <param name="transform">Transform.</param> public virtual void AddBone(int parentHash, int hash, Transform transform) { BoneData newBone = new BoneData() { accessedFrame = frame, parentBoneNameHash = parentHash, boneNameHash = hash, boneTransform = transform, umaTransform = new UMATransform(transform, hash, parentHash), }; if (!boneHashData.ContainsKey(hash)) { boneHashData.Add(hash, newBone); #if UNITY_EDITOR boneHashDataBackup.Add(newBone); #endif } else Debug.LogError("AddBone: " + transform.name + " already exists in the dictionary!"); } /// <summary> /// Adds the transform into the skeleton. /// </summary> /// <param name="transform">Transform.</param> public virtual void AddBone(UMATransform transform) { var go = new GameObject(transform.name); BoneData newBone = new BoneData() { accessedFrame = -1, parentBoneNameHash = transform.parent, boneNameHash = transform.hash, boneTransform = go.transform, umaTransform = transform.Duplicate(), }; if (!boneHashData.ContainsKey(transform.hash)) { boneHashData.Add(transform.hash, newBone); #if UNITY_EDITOR boneHashDataBackup.Add(newBone); #endif } else Debug.LogError("AddBone: " + transform.name + " already exists in the dictionary!"); } /// <summary> /// Removes the bone with the given name hash. /// </summary> /// <param name="nameHash">Name hash.</param> public virtual void RemoveBone(int nameHash) { BoneData bd = GetBone(nameHash); if (bd != null) { boneHashData.Remove(nameHash); #if UNITY_EDITOR boneHashDataBackup.Remove(bd); #endif } } /// <summary> /// Tries to find bone transform in skeleton. /// </summary> /// <returns><c>true</c>, if transform was found, <c>false</c> otherwise.</returns> /// <param name="nameHash">Name hash.</param> /// <param name="boneTransform">Bone transform.</param> /// <param name="transformDirty">Transform is dirty.</param> /// <param name="parentBoneNameHash">Name hash of parent bone.</param> public virtual bool TryGetBoneTransform(int nameHash, out Transform boneTransform, out bool transformDirty, out int parentBoneNameHash) { BoneData res; if (boneHashData.TryGetValue(nameHash, out res)) { transformDirty = res.accessedFrame != frame; res.accessedFrame = frame; boneTransform = res.boneTransform; parentBoneNameHash = res.parentBoneNameHash; return true; } transformDirty = false; boneTransform = null; parentBoneNameHash = 0; return false; } /// <summary> /// Gets the transform for a bone in the skeleton. /// </summary> /// <returns>The transform or null, if not found.</returns> /// <param name="nameHash">Name hash.</param> public virtual Transform GetBoneTransform(int nameHash) { BoneData res; if (boneHashData.TryGetValue(nameHash, out res)) { res.accessedFrame = frame; return res.boneTransform; } return null; } /// <summary> /// Gets the game object for a transform in the skeleton. /// </summary> /// <returns>The game object or null, if not found.</returns> /// <param name="nameHash">Name hash.</param> public virtual GameObject GetBoneGameObject(int nameHash) { BoneData res; if (boneHashData.TryGetValue(nameHash, out res)) { res.accessedFrame = frame; return res.boneTransform.gameObject; } return null; } protected virtual IEnumerable<int> GetBoneHashes() { foreach (int hash in boneHashData.Keys) { yield return hash; } } //DynamicUMADna:: a method to return a string of bonenames for use in editor intefaces private string[] GetBoneNames() { string[] boneNames = new string[boneHashData.Count]; int index = 0; foreach (KeyValuePair<int, BoneData> kp in boneHashData) { boneNames[index] = kp.Value.boneTransform.gameObject.name; index++; } return boneNames; } public virtual void Set(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; db.boneTransform.localPosition = position; db.boneTransform.localRotation = rotation; db.boneTransform.localScale = scale; } else { throw new Exception("Bone not found."); } } /// <summary> /// Sets the position of a bone. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="position">Position.</param> public virtual void SetPosition(int nameHash, Vector3 position) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; db.boneTransform.localPosition = position; } } /// <summary> /// Sets the position of a bone relative to it's old position. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="delta">Position delta.</param> public virtual void SetPositionRelative(int nameHash, Vector3 delta) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; db.boneTransform.localPosition = db.boneTransform.localPosition + delta; } } /// <summary> /// Sets the scale of a bone. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="scale">Scale.</param> public virtual void SetScale(int nameHash, Vector3 scale) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; db.boneTransform.localScale = scale; } } /// <summary> /// DynamicUMADnaConverterBahaviour:: Sets the scale of a bone relatively. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="scale">Scale.</param> public virtual void SetScaleRelative(int nameHash, Vector3 scale) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; var fullScale = scale; fullScale.Scale(db.boneTransform.localScale); db.boneTransform.localScale = fullScale; } } /// <summary> /// Sets the rotation of a bone. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="rotation">Rotation.</param> public virtual void SetRotation(int nameHash, Quaternion rotation) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; db.boneTransform.localRotation = rotation; } } /// <summary> /// DynamicUMADnaConverterBahaviour:: Sets the rotation of a bone relative to its initial rotation. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="rotation">Rotation.</param> /// <param name="weight">Weight.</param> public virtual void SetRotationRelative(int nameHash, Quaternion rotation, float weight /*, bool hasAnimator = true*/) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; Quaternion fullRotation = db.boneTransform.localRotation * rotation; db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, fullRotation, weight); } } /// <summary> /// Lerp the specified bone toward a new position, rotation, and scale. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="position">Position.</param> /// <param name="scale">Scale.</param> /// <param name="rotation">Rotation.</param> /// <param name="weight">Weight.</param> public virtual void Lerp(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation, float weight) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; db.boneTransform.localPosition = Vector3.Lerp(db.boneTransform.localPosition, position, weight); db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, db.boneTransform.localRotation, weight); db.boneTransform.localScale = Vector3.Lerp(db.boneTransform.localScale, scale, weight); } } /// <summary> /// Lerp the specified bone toward a new position, rotation, and scale. /// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion) /// </summary> /// <param name="nameHash">Name hash.</param> /// <param name="position">Position.</param> /// <param name="scale">Scale.</param> /// <param name="rotation">Rotation.</param> /// <param name="weight">Weight.</param> public virtual void Morph(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation, float weight) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; db.boneTransform.localPosition += position * weight; Quaternion fullRotation = db.boneTransform.localRotation * rotation; db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, fullRotation, weight); var fullScale = scale; fullScale.Scale(db.boneTransform.localScale); db.boneTransform.localScale = Vector3.Lerp(db.boneTransform.localScale, fullScale, weight); } } /// <summary> /// Reset the specified transform to the pre-dna state. /// </summary> /// <param name="nameHash">Name hash.</param> public virtual bool Reset(int nameHash) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db) && (db.boneTransform != null)) { db.accessedFrame = frame; db.boneTransform.localPosition = db.umaTransform.position; db.boneTransform.localRotation = db.umaTransform.rotation; db.boneTransform.localScale = db.umaTransform.scale; return true; } return false; } /// <summary> /// Reset all transforms to the pre-dna state. /// </summary> public virtual void ResetAll() { foreach (BoneData db in boneHashData.Values) { if (db.boneTransform != null) { db.accessedFrame = frame; db.boneTransform.localPosition = db.umaTransform.position; db.boneTransform.localRotation = db.umaTransform.rotation; db.boneTransform.localScale = db.umaTransform.scale; } } } /// <summary> /// Restore the specified transform to the post-dna state. /// </summary> /// <param name="nameHash">Name hash.</param> public virtual bool Restore(int nameHash) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db) && (db.boneTransform != null)) { db.accessedFrame = frame; db.boneTransform.localPosition = db.position; db.boneTransform.localRotation = db.rotation; db.boneTransform.localScale = db.scale; return true; } return false; } /// <summary> /// Restore all transforms to the post-dna state. /// </summary> public virtual void RestoreAll() { foreach (BoneData db in boneHashData.Values) { if (db.boneTransform != null) { db.accessedFrame = frame; db.boneTransform.localPosition = db.position; db.boneTransform.localRotation = db.rotation; db.boneTransform.localScale = db.scale; } } } /// <summary> /// Gets the position of a bone. /// </summary> /// <returns>The position.</returns> /// <param name="nameHash">Name hash.</param> public virtual Vector3 GetPosition(int nameHash) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; return db.boneTransform.localPosition; } else { throw new Exception("Bone not found."); } } /// <summary> /// Gets the scale of a bone. /// </summary> /// <returns>The scale.</returns> /// <param name="nameHash">Name hash.</param> public virtual Vector3 GetScale(int nameHash) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; return db.boneTransform.localScale; } else { throw new Exception("Bone not found."); } } /// <summary> /// Gets the rotation of a bone. /// </summary> /// <returns>The rotation.</returns> /// <param name="nameHash">Name hash.</param> public virtual Quaternion GetRotation(int nameHash) { BoneData db; if (boneHashData.TryGetValue(nameHash, out db)) { db.accessedFrame = frame; return db.boneTransform.localRotation; } else { throw new Exception("Bone not found."); } } public static int StringToHash(string name) { return UMAUtils.StringToHash(name); } public virtual Transform[] HashesToTransforms(int[] boneNameHashes) { Transform[] res = new Transform[boneNameHashes.Length]; for (int i = 0; i < boneNameHashes.Length; i++) { res[i] = boneHashData[boneNameHashes[i]].boneTransform; } return res; } public virtual Transform[] HashesToTransforms(List<int> boneNameHashes) { Transform[] res = new Transform[boneNameHashes.Count]; for (int i = 0; i < boneNameHashes.Count; i++) { res[i] = boneHashData[boneNameHashes[i]].boneTransform; } return res; } /// <summary> /// Ensures the bone exists in the skeleton. /// </summary> /// <param name="umaTransform">UMA transform.</param> public virtual void EnsureBone(UMATransform umaTransform) { BoneData res; if (boneHashData.TryGetValue(umaTransform.hash, out res)) { res.accessedFrame = -1; //res.umaTransform.Assign(umaTransform); } else { AddBone(umaTransform); } } /// <summary> /// Ensures all bones are properly initialized and parented. /// </summary> public virtual void EnsureBoneHierarchy() { foreach (var entry in boneHashData.Values) { if (entry.accessedFrame == -1) { if (boneHashData.ContainsKey(entry.umaTransform.parent)) { entry.boneTransform.parent = boneHashData[entry.umaTransform.parent].boneTransform; entry.boneTransform.localPosition = entry.umaTransform.position; entry.boneTransform.localRotation = entry.umaTransform.rotation; entry.boneTransform.localScale = entry.umaTransform.scale; entry.accessedFrame = frame; } else Debug.LogError("EnsureBoneHierarchy: " + entry.umaTransform.name + " parent not found in dictionary!"); } } } public virtual Quaternion GetTPoseCorrectedRotation(int nameHash, Quaternion tPoseRotation) { return boneHashData[nameHash].boneTransform.localRotation; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Xml; using System.Xml.Serialization; using AgenaTrader.API; using AgenaTrader.Custom; using AgenaTrader.Plugins; using AgenaTrader.Helper; /// <summary> /// Version: in progress /// ------------------------------------------------------------------------- /// Simon Pucher 2016 /// Christian Kovar 2016 /// ------------------------------------------------------------------------- /// Golden & Death cross: http://www.investopedia.com/ask/answers/121114/what-difference-between-golden-cross-and-death-cross-pattern.asp /// ------------------------------------------------------------------------- /// ****** Important ****** /// To compile this script without any error you also need access to the utility indicator to use these global source code elements. /// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs /// ------------------------------------------------------------------------- /// Namespace holds all indicators and is required. Do not change it. /// </summary> namespace AgenaTrader.UserCode { [Description("Use SMA or EMA crosses to find trends.")] [IsEntryAttribute(true)] [IsStopAttribute(false)] [IsTargetAttribute(false)] [OverrulePreviousStopPrice(false)] public class RunningWithTheWolves_Condition : UserScriptedCondition { #region Variables //input private Enum_RunningWithTheWolves_Indicator_MA _MA_Selected = Enum_RunningWithTheWolves_Indicator_MA.SMA; private int _ma_slow = 200; private int _ma_medium = 100; private int _ma_fast = 20; private bool _IsShortEnabled = true; private bool _IsLongEnabled = true; //output //internal private RunningWithTheWolves_Indicator _RunningWithTheWolves_Indicator = null; #endregion protected override void OnInit() { IsEntry = true; IsStop = false; IsTarget = false; Add(new OutputDescriptor(Const.DefaultIndicatorColor, "Occurred")); Add(new OutputDescriptor(Const.DefaultIndicatorColor, "Entry")); IsOverlay = false; CalculateOnClosedBar = true; //For SMA200 we need at least 200 Bars. this.RequiredBarsCount = 200; } protected override void OnBarsRequirements() { base.OnBarsRequirements(); } protected override void OnStart() { base.OnStart(); //Init our indicator to get code access this._RunningWithTheWolves_Indicator = new RunningWithTheWolves_Indicator(); } protected override void OnCalculate() { //calculate data OrderDirection_Enum? resultdata = this._RunningWithTheWolves_Indicator.calculate(InSeries, this.MA_Selected, this.MA_Fast, this.MA_Medium, this.MA_Slow); if (resultdata.HasValue) { switch (resultdata) { case OrderDirection_Enum.OpenLong: Occurred.Set(1); //Entry.Set(InSeries[0]); break; case OrderDirection_Enum.OpenShort: Occurred.Set(-1); //Entry.Set(InSeries[0]); break; //case OrderDirection.Buy: // break; //case OrderDirection.Sell: // break; default: //nothing to do Occurred.Set(0); //Entry.Set(InSeries[0]); break; } } else { Occurred.Set(0); } } public override string ToString() { return "Running with the wolves (C)"; } public override string DisplayName { get { return "Running with the wolves (C)"; } } #region Properties #region InSeries /// <summary> /// </summary> [Description("Select the type of MA you would like to use")] [InputParameter] [DisplayName("Type of MA")] public Enum_RunningWithTheWolves_Indicator_MA MA_Selected { get { return _MA_Selected; } set { _MA_Selected = value; } } /// <summary> /// </summary> [Description("Period for the slow mean average")] [InputParameter] [DisplayName("MA Slow")] public int MA_Slow { get { return _ma_slow; } set { _ma_slow = value; } } /// <summary> /// </summary> [Description("Period for the medium mean average")] [InputParameter] [DisplayName("MA Medium")] public int MA_Medium { get { return _ma_medium; } set { _ma_medium = value; } } /// <summary> /// </summary> [Description("Period for the fast mean average")] [InputParameter] [DisplayName("MA Fast")] public int MA_Fast { get { return _ma_fast; } set { _ma_fast = value; } } /// <summary> /// </summary> [Description("If true it is allowed to go long")] [InputParameter] [DisplayName("Allow Long")] public bool IsLongEnabled { get { return _IsLongEnabled; } set { _IsLongEnabled = value; } } /// <summary> /// </summary> [Description("If true it is allowed to go short")] [InputParameter] [DisplayName("Allow Short")] public bool IsShortEnabled { get { return _IsShortEnabled; } set { _IsShortEnabled = value; } } #endregion #region Output [Browsable(false)] [XmlIgnore()] public DataSeries Occurred { get { return Outputs[0]; } } [Browsable(false)] [XmlIgnore()] public DataSeries Entry { get { return Outputs[1]; } } public override IList<DataSeries> GetEntries() { return new[] { Entry }; } #endregion #region Internals #endregion #endregion } }
using Assets.Gamelogic.Core; using Assets.Gamelogic.EntityTemplate; using Assets.Gamelogic.Life; using Improbable; using Improbable.Building; using Improbable.Core; using Improbable.Team; using Improbable.Unity.Core; using Improbable.Unity.Visualizer; using Improbable.Worker; using System.Collections; using System.Collections.Generic; using Assets.Gamelogic.Utils; using UnityEngine; namespace Assets.Gamelogic.HQ { public class HQSpawnBarracksBehaviour : MonoBehaviour { [Require] private HQInfo.Writer hqInfo; [Require] private TeamAssignment.Reader teamAssignment; private Coroutine spawnBarracksPeriodicallyCoroutine; private readonly HashSet<GameObject> barracksSet = new HashSet<GameObject>(); private float barracksSpawnRadius; private void OnEnable() { barracksSpawnRadius = SimulationSettings.DefaultHQBarracksSpawnRadius; spawnBarracksPeriodicallyCoroutine = StartCoroutine(TimerUtils.CallRepeatedly(SimulationSettings.SimulationTickInterval * 5f, SpawnBarracks)); hqInfo.CommandReceiver.OnRegisterBarracks += OnRegisterBarracks; hqInfo.CommandReceiver.OnUnregisterBarracks += OnUnregisterBarracks; hqInfo.ComponentUpdated += OnComponentUpdated; PopulateBarracksDictionary(); } private void OnDisable() { hqInfo.CommandReceiver.OnRegisterBarracks -= OnRegisterBarracks; hqInfo.CommandReceiver.OnUnregisterBarracks -= OnUnregisterBarracks; hqInfo.ComponentUpdated -= OnComponentUpdated; CancelSpawnBarracksPeriodicallyCoroutine(); } private void PopulateBarracksDictionary() { for (var i = 0; i < hqInfo.Data.barracks.Count; i++) { var barracksEntityObject = SpatialOS.Universe.Get(hqInfo.Data.barracks[i]); if (barracksEntityObject != null) { var barracksGameObject = barracksEntityObject.UnderlyingGameObject; if (!barracksSet.Contains(barracksGameObject)) { barracksSet.Add(barracksGameObject); } } } } private void OnRegisterBarracks(Improbable.Entity.Component.ResponseHandle<HQInfo.Commands.RegisterBarracks, RegisterBarracksRequest, Nothing> request) { var newBarracks = new Improbable.Collections.List<EntityId>(hqInfo.Data.barracks); newBarracks.Add(request.Request.entityId); hqInfo.Send(new HQInfo.Update().SetBarracks(newBarracks)); request.Respond(new Nothing()); } private void OnUnregisterBarracks(Improbable.Entity.Component.ResponseHandle<HQInfo.Commands.UnregisterBarracks, UnregisterBarracksRequest, Nothing> request) { var barracks = new Improbable.Collections.List<EntityId>(hqInfo.Data.barracks); if (barracks.Contains(request.Request.entityId)) { barracks.Remove(request.Request.entityId); } hqInfo.Send(new HQInfo.Update().SetBarracks(barracks)); request.Respond(new Nothing()); } private void CancelSpawnBarracksPeriodicallyCoroutine() { if (spawnBarracksPeriodicallyCoroutine != null) { StopCoroutine(spawnBarracksPeriodicallyCoroutine); spawnBarracksPeriodicallyCoroutine = null; } } private void OnComponentUpdated(HQInfo.Update update) { if (update.barracks.HasValue) { PopulateBarracksDictionary(); } } private void SpawnBarracks() { if (AllBarracksAtFullHealth()) { SpawnUnconstructedBarracksAtRandomLocation(); } } private bool AllBarracksAtFullHealth() { var barracksEnumerator = Physics.OverlapSphere(transform.position, barracksSpawnRadius); var allBarracksFullHealth = true; for(var i = 0; i < barracksEnumerator.Length; i++) { if(barracksEnumerator[i].gameObject.name.Contains("Barracks")) { var health = barracksEnumerator[i].gameObject.GetComponent<HealthVisualizer>(); if (health.CurrentHealth < health.MaxHealth) { allBarracksFullHealth = false; } } } return allBarracksFullHealth; } private void SpawnUnconstructedBarracksAtRandomLocation() { var spawnPosition = FindSpawnLocation(); if (SpawnLocationInvalid(spawnPosition)) { Debug.LogError("HQ failed to find place to spawn barracks."); return; } var teamId = teamAssignment.Data.teamId; var template = EntityTemplateFactory.CreateBarracksTemplate(spawnPosition.ToCoordinates(), BarracksState.UNDER_CONSTRUCTION, teamId); SpatialOS.Commands.CreateEntity(hqInfo, SimulationSettings.BarracksPrefabName, template, response => OnBarracksSpawnResponse(response)); } private void OnBarracksSpawnResponse(ICommandCallbackResponse<EntityId> response) { if (response.StatusCode != StatusCode.Success) { Debug.LogError("HQ failed to spawn barracks due to timeout."); return; } PopulateBarracksDictionary(); } private bool SpawnLocationInvalid(Vector3 position) { return position.y < 0f; } private Vector3 FindSpawnLocation() { while (true) { for (var attemptNum = 0; attemptNum < SimulationSettings.HQBarracksSpawnPositionPickingRetries; attemptNum++) { var spawnLocation = PickRandomLocationNearby(); if (NotCollidingWithAnything(spawnLocation)) { return spawnLocation; } } if (barracksSpawnRadius > SimulationSettings.MaxHQBarracksSpawnRadius) { return Vector3.down; } barracksSpawnRadius += SimulationSettings.HQBarracksSpawnRadiusIncrease; } } private Vector3 PickRandomLocationNearby() { var randomOffset = new Vector3(Random.Range(-barracksSpawnRadius, barracksSpawnRadius), 0f, Random.Range(-barracksSpawnRadius, barracksSpawnRadius)); return transform.position + randomOffset; } private bool NotCollidingWithAnything(Vector3 spawnLocation) { return NotCollidingWithHQ(spawnLocation) && NotCollidingWithOtherBarracks(spawnLocation); } private bool NotCollidingWithHQ(Vector3 spawnLocation) { return Vector3.Distance(transform.position, spawnLocation) > SimulationSettings.HQBarracksSpawningSeparation; } private bool NotCollidingWithOtherBarracks(Vector3 spawnLocation) { foreach (GameObject barracks in barracksSet) { if (Vector3.Distance(barracks.transform.position, spawnLocation) <= SimulationSettings.HQBarracksSpawningSeparation) { return false; } } return true; } } }
/* ********************************************************************************** * * Copyright (c) Microsoft Corporation. All rights reserved. * * This source code is subject to terms and conditions of the Shared Source License * for IronPython. A copy of the license can be found in the License.html file * at the root of this distribution. If you can not locate the Shared Source License * for IronPython, please send an email to [email protected]. * By using this source code in any fashion, you are agreeing to be bound by * the terms of the Shared Source License for IronPython. * * You must not remove this notice, or any other, from this software. * * **********************************************************************************/ using System; using System.Text; using System.Collections.Generic; using System.Collections; namespace RubyClr.Tests { public class BindingTestClass { public static object Bind(bool parm) { return parm; } public static object Bind(string parm) { return parm; } public static object Bind(int parm) { return parm; } } public class InheritedBindingBase { public virtual object Bind(bool parm) { return "Base bool"; } public virtual object Bind(string parm) { return "Base string"; } public virtual object Bind(int parm) { return "Base int"; } } public class InheritedBindingSub : InheritedBindingBase { public override object Bind(bool parm) { return "Subclass bool"; } public override object Bind(string parm) { return "Subclass string"; } public override object Bind(int parm) { return "Subclass int"; } } [Flags] public enum BindResult { None = 0, Bool = 1, Byte = 2, Char = 3, Decimal = 4, Double = 5, Float = 6, Int = 7, Long = 8, Object = 9, SByte = 10, Short = 11, String = 12, UInt = 13, ULong = 14, UShort = 15, Array = 0x1000, Out = 0x2000, Ref = 0x4000, } public class BindTest { public static object BoolValue = (bool)true; public static object ByteValue = (byte)0; public static object CharValue = (char)'\0'; public static object DecimalValue = (decimal)0; public static object DoubleValue = (double)0; public static object FloatValue = (float)0; public static object IntValue = (int)0; public static object LongValue = (long)0; public static object ObjectValue = (object)new System.Collections.Hashtable(); public static object SByteValue = (sbyte)0; public static object ShortValue = (short)0; public static object StringValue = (string)String.Empty; public static object UIntValue = (uint)0; public static object ULongValue = (ulong)0; public static object UShortValue = (ushort)0; public static BindResult Bind() { return BindResult.None; } public static BindResult Bind(bool value) { return BindResult.Bool; } public static BindResult Bind(byte value) { return BindResult.Byte; } public static BindResult Bind(char value) { return BindResult.Char; } public static BindResult Bind(decimal value) { return BindResult.Decimal; } public static BindResult Bind(double value) { return BindResult.Double; } public static BindResult Bind(float value) { return BindResult.Float; } public static BindResult Bind(int value) { return BindResult.Int; } public static BindResult Bind(long value) { return BindResult.Long; } public static BindResult Bind(object value) { return BindResult.Object; } public static BindResult Bind(sbyte value) { return BindResult.SByte; } public static BindResult Bind(short value) { return BindResult.Short; } public static BindResult Bind(string value) { return BindResult.String; } public static BindResult Bind(uint value) { return BindResult.UInt; } public static BindResult Bind(ulong value) { return BindResult.ULong; } public static BindResult Bind(ushort value) { return BindResult.UShort; } public static BindResult Bind(bool[] value) { return BindResult.Bool | BindResult.Array; } public static BindResult Bind(byte[] value) { return BindResult.Byte | BindResult.Array; } public static BindResult Bind(char[] value) { return BindResult.Char | BindResult.Array; } public static BindResult Bind(decimal[] value) { return BindResult.Decimal | BindResult.Array; } public static BindResult Bind(double[] value) { return BindResult.Double | BindResult.Array; } public static BindResult Bind(float[] value) { return BindResult.Float | BindResult.Array; } public static BindResult Bind(int[] value) { return BindResult.Int | BindResult.Array; } public static BindResult Bind(long[] value) { return BindResult.Long | BindResult.Array; } public static BindResult Bind(object[] value) { return BindResult.Object | BindResult.Array; } public static BindResult Bind(sbyte[] value) { return BindResult.SByte | BindResult.Array; } public static BindResult Bind(short[] value) { return BindResult.Short | BindResult.Array; } public static BindResult Bind(string[] value) { return BindResult.String | BindResult.Array; } public static BindResult Bind(uint[] value) { return BindResult.UInt | BindResult.Array; } public static BindResult Bind(ulong[] value) { return BindResult.ULong | BindResult.Array; } public static BindResult Bind(ushort[] value) { return BindResult.UShort | BindResult.Array; } public static BindResult Bind(out bool value) { value = false; return BindResult.Bool | BindResult.Out; } public static BindResult Bind(out byte value) { value = 0; return BindResult.Byte | BindResult.Out; } public static BindResult Bind(out char value) { value = '\0'; return BindResult.Char | BindResult.Out; } public static BindResult Bind(out decimal value) { value = 0; return BindResult.Decimal | BindResult.Out; } public static BindResult Bind(out double value) { value = 0; return BindResult.Double | BindResult.Out; } public static BindResult Bind(out float value) { value = 0; return BindResult.Float | BindResult.Out; } public static BindResult Bind(out int value) { value = 0; return BindResult.Int | BindResult.Out; } public static BindResult Bind(out long value) { value = 0; return BindResult.Long | BindResult.Out; } public static BindResult Bind(out object value) { value = null; return BindResult.Object | BindResult.Out; } public static BindResult Bind(out sbyte value) { value = 0; return BindResult.SByte | BindResult.Out; } public static BindResult Bind(out short value) { value = 0; return BindResult.Short | BindResult.Out; } public static BindResult Bind(out string value) { value = null; return BindResult.String | BindResult.Out; } public static BindResult Bind(out uint value) { value = 0; return BindResult.UInt | BindResult.Out; } public static BindResult Bind(out ulong value) { value = 0; return BindResult.ULong | BindResult.Out; } public static BindResult Bind(out ushort value) { value = 0; return BindResult.UShort | BindResult.Out; } public static BindResult BindRef(ref bool value) { value = false; return BindResult.Bool | BindResult.Ref; } public static BindResult BindRef(ref byte value) { value = 0; return BindResult.Byte | BindResult.Ref; } public static BindResult BindRef(ref char value) { value = '\0'; return BindResult.Char | BindResult.Ref; } public static BindResult BindRef(ref decimal value) { value = 0; return BindResult.Decimal | BindResult.Ref; } public static BindResult BindRef(ref double value) { value = 0; return BindResult.Double | BindResult.Ref; } public static BindResult BindRef(ref float value) { value = 0; return BindResult.Float | BindResult.Ref; } public static BindResult BindRef(ref int value) { value = 0; return BindResult.Int | BindResult.Ref; } public static BindResult BindRef(ref long value) { value = 0; return BindResult.Long | BindResult.Ref; } public static BindResult BindRef(ref object value) { value = null; return BindResult.Object | BindResult.Ref; } public static BindResult BindRef(ref sbyte value) { value = 0; return BindResult.SByte | BindResult.Ref; } public static BindResult BindRef(ref short value) { value = 0; return BindResult.Short | BindResult.Ref; } public static BindResult BindRef(ref string value) { value = null; return BindResult.String | BindResult.Ref; } public static BindResult BindRef(ref uint value) { value = 0; return BindResult.UInt | BindResult.Ref; } public static BindResult BindRef(ref ulong value) { value = 0; return BindResult.ULong | BindResult.Ref; } public static BindResult BindRef(ref ushort value) { value = 0; return BindResult.UShort | BindResult.Ref; } } namespace DispatchHelpers { public class B { } public class D : B { } public interface I { } public class C1 : I { } public class C2 : I { } public enum Color { Red, Blue } } public class Dispatch { public static int Flag = 0; public void M1(int arg) { Flag = 101; } public void M1(DispatchHelpers.Color arg) { Flag = 201; } public void M2(int arg) { Flag = 102; } public void M2(int arg, params int[] arg2) { Flag = 202; } public void M3(int arg) { Flag = 103; } public void M3(int arg, int arg2) { Flag = 203; } public void M4(int arg) { Flag = 104; } public void M4(int arg, __arglist) { Flag = 204; } public void M5(float arg) { Flag = 105; } public void M5(double arg) { Flag = 205; } public void M6(char arg) { Flag = 106; } public void M6(string arg) { Flag = 206; } public void M7(int arg) { Flag = 107; } public void M7(params int[] args) { Flag = 207; } public void M8(int arg) { Flag = 108; } public void M8(ref int arg) { Flag = 208; arg = 999; } public void M10(ref int arg) { Flag = 210; arg = 999; } public void M11(int arg, int arg2) { Flag = 111; } public void M11(DispatchHelpers.Color arg, int arg2) { Flag = 211; } public void M12(int arg, DispatchHelpers.Color arg2) { Flag = 112; } public void M12(DispatchHelpers.Color arg, int arg2) { Flag = 212; } public void M20(DispatchHelpers.B arg) { Flag = 120; } public void M22(DispatchHelpers.B arg) { Flag = 122; } public void M22(DispatchHelpers.D arg) { Flag = 222; } public void M23(DispatchHelpers.I arg) { Flag = 123; } public void M23(DispatchHelpers.C2 arg) { Flag = 223; } public void M50(params DispatchHelpers.B[] args) { Flag = 150; } public void M51(params DispatchHelpers.B[] args) { Flag = 151; } public void M51(params DispatchHelpers.D[] args) { Flag = 251; } public void M60(int? arg) { Flag = 160; } public void M70(Dispatch arg) { Flag = 170; } public static void M71(Dispatch arg) { Flag = 171; } public static void M81(Dispatch arg, int arg2) { Flag = 181; } public void M81(int arg) { Flag = 281; } public static void M82(bool arg) { Flag = 182; } public static void M82(string arg) { Flag = 282; } public void M83(bool arg) { Flag = 183; } public void M83(string arg) { Flag = 283; } public void M90<T>(int arg) { Flag = 190; } public void M91(int arg) { Flag = 191; } public void M91<T>(int arg) { Flag = 291; } } public class DispatchBase { public virtual void M1(int arg) { Dispatch.Flag = 101; } public virtual void M2(int arg) { Dispatch.Flag = 102; } public virtual void M3(int arg) { Dispatch.Flag = 103; } public void M4(int arg) { Dispatch.Flag = 104; } public virtual void M5(int arg) { Dispatch.Flag = 105; } public virtual void M6(int arg) { Dispatch.Flag = 106; } } public class DispatchDerived : DispatchBase { public override void M1(int arg) { Dispatch.Flag = 201; } public virtual void M2(DispatchHelpers.Color arg) { Dispatch.Flag = 202; } public virtual void M3(string arg) { Dispatch.Flag = 203; } public void M4(string arg) { Dispatch.Flag = 204; } public new virtual void M5(int arg) { Dispatch.Flag = 205; } } public class ConversionDispatch { public object Array(object[] arr) { return arr; } public object IntArray(int[] arr) { return arr; } public object StringArray(string[] arr) { return arr; } public object Enumerator(IEnumerator<object> enm) { return enm; } public object StringEnumerator(IEnumerator<string> enm) { return enm; } public object IntEnumerator(IEnumerator<int> enm) { return enm; } public object ArrayList(System.Collections.ArrayList list) { return list; } public object ObjIList(IList<object> list) { return list; } public object IntIList(IList<int> list) { return list; } public object StringIList(IList<string> list) { return list; } public object ObjList(List<object> list) { return list; } public object IntList(List<int> list) { return list; } public object StringList(List<string> list) { return list; } public object DictTest(IDictionary<object, object> dict) { return dict; } public object IntDictTest(IDictionary<int, int> dict) { return dict; } public object StringDictTest(IDictionary<string, string> dict) { return dict; } public object MixedDictTest(IDictionary<string, int> dict) { return dict; } public object HashtableTest(Hashtable dict) { return dict; } } public class FieldTest { public IList<Type> Field; } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using MongoDB.Util; namespace MongoDB.Configuration.Mapping.Util { /// <summary> /// </summary> public static class MemberReflectionOptimizer { private static readonly Dictionary<string, Func<object, object>> GetterCache = new Dictionary<string, Func<object, object>>(); private static readonly Dictionary<string, Action<object, object>> SetterCache = new Dictionary<string, Action<object, object>>(); private static readonly object SyncObject = new object(); /// <summary> /// Gets the getter. /// </summary> /// <param name = "memberInfo">The member info.</param> /// <returns></returns> public static Func<object, object> GetGetter(MemberInfo memberInfo) { if(memberInfo == null) throw new ArgumentNullException("memberInfo"); if(memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) throw new ArgumentException("Only fields and properties are supported.", "memberInfo"); if(memberInfo.MemberType == MemberTypes.Field) return GetFieldGetter(memberInfo as FieldInfo); if(memberInfo.MemberType == MemberTypes.Property) return GetPropertyGetter(memberInfo as PropertyInfo); throw new InvalidOperationException("Can only create getters for fields or properties."); } /// <summary> /// Gets the field getter. /// </summary> /// <param name = "fieldInfo">The field info.</param> /// <returns></returns> public static Func<object, object> GetFieldGetter(FieldInfo fieldInfo) { if(fieldInfo == null) throw new ArgumentNullException("fieldInfo"); var key = CreateKey(fieldInfo); Func<object, object> getter; lock (SyncObject) { if (GetterCache.TryGetValue(key, out getter)) return getter; } //We release the lock here, so the relatively time consuming compiling //does not imply contention. The price to pay is potential multiple compilations //of the same expression... var instanceParameter = Expression.Parameter(typeof (object), "target"); var member = Expression.Field(Expression.Convert(instanceParameter, fieldInfo.DeclaringType), fieldInfo); var lambda = Expression.Lambda<Func<object, object>>( Expression.Convert(member, typeof (object)), instanceParameter); getter = lambda.Compile(); lock(SyncObject) { GetterCache[key] = getter; } return getter; } /// <summary> /// Gets the property getter. /// </summary> /// <param name = "propertyInfo">The property info.</param> /// <returns></returns> public static Func<object, object> GetPropertyGetter(PropertyInfo propertyInfo) { if(propertyInfo == null) throw new ArgumentNullException("propertyInfo"); var key = CreateKey(propertyInfo); Func<object, object> getter; lock (SyncObject) { if (GetterCache.TryGetValue(key, out getter)) return getter; } if(!propertyInfo.CanRead) throw new InvalidOperationException("Cannot create a getter for a writeonly property."); var instanceParameter = Expression.Parameter(typeof(object), "target"); var member = Expression.Property(Expression.Convert(instanceParameter, propertyInfo.DeclaringType), propertyInfo); var lambda = Expression.Lambda<Func<object, object>>( Expression.Convert(member, typeof(object)), instanceParameter); getter = lambda.Compile(); lock (SyncObject) { GetterCache[key] = getter; } return getter; } /// <summary> /// Gets the setter. /// </summary> /// <param name = "memberInfo">The member info.</param> /// <returns></returns> public static Action<object, object> GetSetter(MemberInfo memberInfo) { if(memberInfo == null) throw new ArgumentNullException("memberInfo"); if(memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) throw new ArgumentException("Only fields and properties are supported.", "memberInfo"); if(memberInfo.MemberType == MemberTypes.Field) return GetFieldSetter(memberInfo as FieldInfo); if(memberInfo.MemberType == MemberTypes.Property) return GetPropertySetter(memberInfo as PropertyInfo); throw new InvalidOperationException("Can only create setters for fields or properties."); } /// <summary> /// Gets the field setter. /// </summary> /// <param name = "fieldInfo">The field info.</param> /// <returns></returns> public static Action<object, object> GetFieldSetter(FieldInfo fieldInfo) { if(fieldInfo == null) throw new ArgumentNullException("fieldInfo"); var key = CreateKey(fieldInfo); Action<object, object> setter; lock (SyncObject) { if (SetterCache.TryGetValue(key, out setter)) return setter; } if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) throw new InvalidOperationException("Cannot create a setter for a readonly field."); var sourceType = fieldInfo.DeclaringType; var method = new DynamicMethod("Set" + fieldInfo.Name, null, new[] {typeof (object), typeof (object)}, true); var gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Castclass, sourceType); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType); gen.Emit(OpCodes.Stfld, fieldInfo); gen.Emit(OpCodes.Ret); setter = (Action<object, object>) method.CreateDelegate(typeof (Action<object, object>)); lock (SyncObject) { SetterCache[key] = setter; } return setter; } /// <summary> /// Gets the property setter. /// </summary> /// <param name = "propertyInfo">The property info.</param> /// <returns></returns> public static Action<object, object> GetPropertySetter(PropertyInfo propertyInfo) { if(propertyInfo == null) throw new ArgumentNullException("propertyInfo"); var key = CreateKey(propertyInfo); Action<object, object> setter; lock (SyncObject) { if (SetterCache.TryGetValue(key, out setter)) return setter; } if (!propertyInfo.CanWrite) throw new InvalidOperationException("Cannot create a setter for a readonly property."); var instanceParameter = Expression.Parameter(typeof (object), "target"); var valueParameter = Expression.Parameter(typeof (object), "value"); var lambda = Expression.Lambda<Action<object, object>>( Expression.Call( Expression.Convert(instanceParameter, propertyInfo.DeclaringType), propertyInfo.GetSetMethod(true), Expression.Convert(valueParameter, propertyInfo.PropertyType)), instanceParameter, valueParameter); setter = lambda.Compile(); lock (SyncObject) { SetterCache[key] = setter; } return setter; } /// <summary> /// Creates the key. /// </summary> /// <param name = "memberInfo">The member info.</param> /// <returns></returns> private static string CreateKey(MemberInfo memberInfo) { return string.Format("{0}_{1}_{2}_{3}", memberInfo.DeclaringType.FullName, memberInfo.MemberType, memberInfo.GetReturnType(), memberInfo.Name); } } }
using System; using System.Collections.Generic; using System.Linq; using Foundation; using GameplayKit; namespace FourInARow { public class Board : NSObject, IGKGameModel { public const int Width = 7; public const int Height = 6; public Chip[] Cells { get; private set; } public Player CurrentPlayer { get; set; } public bool IsFull { get { for (int column = 0; column < Width; column++) { if (CanMoveInColumn (column)) return false; } return true; } } public Board () { CurrentPlayer = Player.RedPlayer; Cells = new Chip [Width * Height]; } public Chip ChipInColumnRow (int column, int row) { var index = row + column * Height; return (index >= Cells.Length) ? Chip.None : Cells [index]; } public bool CanMoveInColumn (int column) { return NextEmptySlotInColumn (column) >= 0; } public void AddChipInColumn (Chip chip, int column) { int row = NextEmptySlotInColumn (column); if (row >= 0) SetChipInColumnRow (chip, column, row); } public IGKGameModelPlayer[] GetPlayers () { return Player.AllPlayers; } public IGKGameModelPlayer GetActivePlayer () { return CurrentPlayer; } public NSObject Copy (NSZone zone) { return null; } public void SetGameModel (IGKGameModel gameModel) { var board = (Board)gameModel; UpdateChipsFromBoard (board); CurrentPlayer = board.CurrentPlayer; } public IGKGameModelUpdate[] GetGameModelUpdates (IGKGameModelPlayer player) { var moves = new List<Move> (); for (int column = 0; column < Width; column++) { if (CanMoveInColumn (column)) moves.Add (Move.MoveInColumn (column)); } return moves.ToArray (); } public void ApplyGameModelUpdate (IGKGameModelUpdate gameModelUpdate) { AddChipInColumn (CurrentPlayer.Chip, ((Move)gameModelUpdate).Column); CurrentPlayer = CurrentPlayer.Opponent; } [Export ("scoreForPlayer:")] public nint ScorForPlayer (Player player) { var playerRunCounts = RunCountsForPlayer (player); int playerTotal = playerRunCounts.Sum (); var opponentRunCounts = RunCountsForPlayer (player.Opponent); int opponentTotal = opponentRunCounts.Sum (); // Return the sum of player runs minus the sum of opponent runs. return playerTotal - opponentTotal; } public bool IsWin (Player player) { var runCounts = RunCountsForPlayer (player); return runCounts.Max () >= Player.CountToWin; } bool IsLoss (Player player) { return IsWin (player.Opponent); } int[] RunCountsForPlayer (Player player) { var chip = player.Chip; var counts = new List<int> (); // Detect horizontal runs. for (int row = 0; row < Height; row++) { int runCount = 0; for (int column = 0; column < Width; column++) { if (ChipInColumnRow (column, row) == chip) { ++runCount; } else { if (runCount > 0) counts.Add (runCount); runCount = 0; } } if (runCount > 0) counts.Add (runCount); } // Detect vertical runs. for (int column = 0; column < Width; column++) { int runCount = 0; for (int row = 0; row < Height; row++) { if (ChipInColumnRow (column, row) == chip) { ++runCount; } else { if (runCount > 0) counts.Add (runCount); runCount = 0; } } if (runCount > 0) counts.Add (runCount); } // Detect diagonal (northeast) runs for (int startColumn = -Height; startColumn < Width; startColumn++) { int runCount = 0; for (int offset = 0; offset < Height; offset++) { int column = startColumn + offset; if (column < 0 || column > Width) continue; if (ChipInColumnRow (column, offset) == chip) { ++runCount; } else { if (runCount > 0) counts.Add (runCount); runCount = 0; } } if (runCount > 0) counts.Add (runCount); } // Detect diagonal (northwest) runs for (int startColumn = 0; startColumn < Width + Height; startColumn++) { int runCount = 0; for (int offset = 0; offset < Height; offset++) { int column = startColumn - offset; if (column < 0 || column > Width) continue; if (ChipInColumnRow (column, offset) == chip) { ++runCount; } else { if (runCount > 0) counts.Add (runCount); runCount = 0; } } if (runCount > 0) counts.Add (runCount); } return counts.ToArray (); } void UpdateChipsFromBoard (Board otherBoard) { Cells = otherBoard.Cells; } void SetChipInColumnRow (Chip chip, int column, int row) { Cells [row + column * Height] = chip; } int NextEmptySlotInColumn (int column) { for (int row = 0; row < Height; row++) { if (ChipInColumnRow (column, row) == Chip.None) return row; } return -1; } } }
/* * 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.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 class Application { /// <summary> /// Text Console Logger /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Path to the main ini Configuration file /// </summary> public static string iniFilePath = ""; /// <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> protected 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); if(Util.IsWindows()) ServicePointManager.DefaultConnectionLimit = 32; else { ServicePointManager.DefaultConnectionLimit = 12; try { ServicePointManager.DnsRefreshTimeout = 120000; } // just is case some crazy mono decides to have it infinity catch { } } ServicePointManager.Expect100Continue = false; ServicePointManager.UseNagleAlgorithm = false; // 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 (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } m_log.InfoFormat( "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture); string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU"); m_log.InfoFormat( "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset"); // Verify the Threadpool allocates or uses enough worker and IO completion threads // .NET 2.0, workerthreads default to 50 * numcores // .NET 3.0, workerthreads defaults to 250 * numcores // .NET 4.0, workerthreads are dynamic based on bitness and OS resources // Max IO Completion threads are 1000 on all 3 CLRs // // Mono 2.10.9 to at least Mono 3.1, workerthreads default to 100 * numcores, iocp threads to 4 * numcores int workerThreadsMin = 500; int workerThreadsMax = 1000; // may need further adjustment to match other CLR int iocpThreadsMin = 1000; int iocpThreadsMax = 2000; // may need further adjustment to match other CLR { int currentMinWorkerThreads, currentMinIocpThreads; System.Threading.ThreadPool.GetMinThreads(out currentMinWorkerThreads, out currentMinIocpThreads); m_log.InfoFormat( "[OPENSIM MAIN]: Runtime gave us {0} min worker threads and {1} min IOCP threads", currentMinWorkerThreads, currentMinIocpThreads); } int workerThreads, iocpThreads; System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); if (workerThreads < workerThreadsMin) { workerThreads = workerThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max worker threads to {0}",workerThreads); } if (workerThreads > workerThreadsMax) { workerThreads = workerThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max worker threads to {0}",workerThreads); } // Increase the number of IOCP threads available. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17) if (iocpThreads < iocpThreadsMin) { iocpThreads = iocpThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up max IOCP threads to {0}",iocpThreads); } // Make sure we don't overallocate IOCP threads and thrash system resources if ( iocpThreads > iocpThreadsMax ) { iocpThreads = iocpThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting max IOCP completion threads to {0}",iocpThreads); } // set the resulting worker and IO completion thread counts back to ThreadPool if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) ) { m_log.InfoFormat( "[OPENSIM MAIN]: Threadpool set to {0} max worker threads and {1} max IOCP threads", workerThreads, iocpThreads); } else { m_log.Warn("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect."); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("[OPENSIM MAIN]: Environment is supported by OpenSimulator."); } else { m_log.Warn("[OPENSIM MAIN]: Environment is not supported by OpenSimulator (" + supported + ")\n"); } // Configure nIni aliases and localles Culture.SetCurrentCulture(); // Validate that the user has the most basic configuration done // If not, offer to do the most basic configuration for them warning them along the way of the importance of // reading these files. /* m_log.Info("Checking for reguired configuration...\n"); bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini"))); bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini")); bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini")); bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini")); if ((OpenSim_Ini) && ( (StanaloneCommon_ProperCased || StanaloneCommon_lowercased || GridCommon_ProperCased || GridCommon_lowerCased ))) { m_log.Info("Required Configuration Files Found\n"); } else { MainConsole.Instance = new LocalConsole("Region"); string resp = MainConsole.Instance.CmdPrompt( "\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?", "yes"); if (resp == "yes") { if (!(OpenSim_Ini)) { try { File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"), Path.Combine(Util.configDir(), "OpenSim.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } } if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased)) { try { File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"), Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } } } MainConsole.Instance = null; } */ 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", "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("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true); } catch (Exception e2) { m_log.ErrorFormat("[CRASH LOGGER CRASHED]: {0}", e2); } } _IsHandlingException = false; } } }
//! \file ImageIPH.cs //! \date Sun Nov 08 12:09:06 2015 //! \brief TechnoBrain's "Inteligent Picture Format" (original spelling) // // Copyright (C) 2015-2016 by morkt // // 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 GameRes.Utility; using System; using System.ComponentModel.Composition; using System.IO; using System.Windows.Media; namespace GameRes.Formats.TechnoBrain { internal class IphMetaData : ImageMetaData { public int PackedSize; public bool IsCompressed; } [Export(typeof(ImageFormat))] public class IphFormat : ImageFormat { public override string Tag { get { return "IPH"; } } public override string Description { get { return "TechnoBrain's 'Inteligent Picture Format'"; } } public override uint Signature { get { return 0; } } // 'RIFF' public override ImageMetaData ReadMetaData (IBinaryStream file) { // 'RIFF' isn't included into signature to avoid auto-detection of the WAV files as IPH images. if (0x46464952 != file.Signature) // 'RIFF' return null; var header = file.ReadHeader (0x10); if (0x38 != header.ToInt32 (4)) return null; var signature = header.ToInt32 (8); if (signature != 0x20485049 && signature != 0x00485049) // 'IPH' return null; if (0x20746D66 != header.ToInt32 (12)) // 'fmt ' return null; file.Position = 0x38; if (0x20706D62 != file.ReadInt32()) // 'bmp ' return null; var info = new IphMetaData(); info.PackedSize = file.ReadInt32(); info.Width = file.ReadUInt16(); info.Height = file.ReadUInt16(); file.Position = 0x50; info.BPP = file.ReadUInt16(); info.IsCompressed = 0 != file.ReadInt16(); // XXX int16@[0x54] is a transparency color or 0xFFFF if image is not transparent return info; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { if (info.BPP != 16) throw new NotSupportedException ("Not supported IPH color depth"); using (var reader = new IphReader (stream, (IphMetaData)info)) { reader.Unpack(); return ImageData.Create (info, reader.Format, null, reader.Data); } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("IphFormat.Write not implemented"); } } internal sealed class IphReader : IDisposable { IBinaryStream m_input; byte[] m_output; int m_width; int m_height; IphMetaData m_info; public PixelFormat Format { get { return PixelFormats.Bgr555; } } public byte[] Data { get { return m_output; } } public IphReader (IBinaryStream input, IphMetaData info) { m_info = info; m_input = input; m_width = (int)info.Width; m_height = (int)info.Height; m_output = new byte[m_width*m_height*2]; } public void Unpack () { m_input.Position = 0x58; if (!m_info.IsCompressed) { m_input.Read (m_output, 0, m_output.Length); return; } int stride = m_width * 2; var extra_line = new byte[stride]; for (int y = 0; y < m_height; ++y) { int row = stride * y; byte ctl = m_input.ReadUInt8(); if (ctl != 0) { int dst = row; int pixel = 0; while (dst < m_output.Length) { ctl = m_input.ReadUInt8(); if (0xFF == ctl) break; if (0xFE == ctl) { int count = m_input.ReadByte() + 1; pixel = m_input.ReadUInt16(); for (int j = 0; j < count; ++j) { LittleEndian.Pack ((ushort)pixel, m_output, dst); dst += 2; } } else if (ctl < 0x80) { byte lo = m_input.ReadUInt8(); m_output[dst++] = lo; m_output[dst++] = ctl; pixel = ctl << 8 | lo; } else { ctl &= 0x7F; int r = (pixel & 0x7C00) >> 10; int g = (pixel & 0x3E0) >> 5; int b = pixel & 0x1F; pixel = (b + ctl / 25 % 5 - 2) | (g + ctl / 5 % 5 - 2) << 5 | (r + ctl % 5 - 2) << 10; LittleEndian.Pack ((ushort)pixel, m_output, dst); dst += 2; } } } else { m_input.Read (m_output, row, stride); m_input.ReadByte(); } ctl = m_input.ReadUInt8(); if (0 != ctl) { int dst = 0; for (;;) { ctl = m_input.ReadUInt8(); if (0xFF == ctl) break; if (ctl >= 0x80) { byte b = (byte)(ctl & 0x7F); int count = m_input.ReadByte() + 1; for (int j = 0; j < count; ++j) { extra_line[dst++] = b; } } else { extra_line[dst++] = ctl; } } dst = row + 1; for (int i = 0; i < m_width; ++i) { int v46 = extra_line[i / 6]; if (0 != ((32 >> i % 6) & v46)) m_output[dst] |= 0x80; dst += 2; } } else { m_input.ReadByte(); } } } #region IDisposable Members public void Dispose () { } #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.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading; using System.Xml; namespace System.ServiceModel.Channels { public sealed class MessageHeaders : IEnumerable<MessageHeaderInfo> { private int _collectionVersion; private int _headerCount; private Header[] _headers; private MessageVersion _version; private IBufferedMessageData _bufferedMessageData; private UnderstoodHeaders _understoodHeaders; private const int InitialHeaderCount = 4; private const int MaxRecycledArrayLength = 8; private static XmlDictionaryString[] s_localNames; internal const string WildcardAction = "*"; // The highest node and attribute counts reached by the BVTs were 1829 and 667 respectively. private const int MaxBufferedHeaderNodes = 4096; private const int MaxBufferedHeaderAttributes = 2048; private int _nodeCount = 0; private int _attrCount = 0; private bool _understoodHeadersModified; public MessageHeaders(MessageVersion version, int initialSize) { Init(version, initialSize); } public MessageHeaders(MessageVersion version) : this(version, InitialHeaderCount) { } internal MessageHeaders(MessageVersion version, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes, ref int maxSizeOfHeaders) : this(version) { if (maxSizeOfHeaders < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("maxSizeOfHeaders", maxSizeOfHeaders, SR.ValueMustBeNonNegative)); } if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("version")); if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); if (reader.IsEmptyElement) { reader.Read(); return; } XmlBuffer xmlBuffer = null; EnvelopeVersion envelopeVersion = version.Envelope; reader.ReadStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace); while (reader.IsStartElement()) { if (xmlBuffer == null) xmlBuffer = new XmlBuffer(maxSizeOfHeaders); BufferedHeader bufferedHeader = new BufferedHeader(version, xmlBuffer, reader, envelopeAttributes, headerAttributes); HeaderProcessing processing = bufferedHeader.MustUnderstand ? HeaderProcessing.MustUnderstand : 0; HeaderKind kind = GetHeaderKind(bufferedHeader); if (kind != HeaderKind.Unknown) { processing |= HeaderProcessing.Understood; MessageHeaders.TraceUnderstood(bufferedHeader); } Header newHeader = new Header(kind, bufferedHeader, processing); AddHeader(newHeader); } if (xmlBuffer != null) { xmlBuffer.Close(); maxSizeOfHeaders -= xmlBuffer.BufferSize; } reader.ReadEndElement(); _collectionVersion = 0; } internal MessageHeaders(MessageVersion version, XmlDictionaryReader reader, IBufferedMessageData bufferedMessageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified) { _headers = new Header[InitialHeaderCount]; Init(version, reader, bufferedMessageData, recycledMessageState, understoodHeaders, understoodHeadersModified); } internal MessageHeaders(MessageVersion version, MessageHeaders headers, IBufferedMessageData bufferedMessageData) { _version = version; _bufferedMessageData = bufferedMessageData; _headerCount = headers._headerCount; _headers = new Header[_headerCount]; Array.Copy(headers._headers, _headers, _headerCount); _collectionVersion = 0; } public MessageHeaders(MessageHeaders collection) { if (collection == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection"); Init(collection._version, collection._headers.Length); CopyHeadersFrom(collection); _collectionVersion = 0; } public string Action { get { int index = FindHeaderProperty(HeaderKind.Action); if (index < 0) return null; ActionHeader actionHeader = _headers[index].HeaderInfo as ActionHeader; if (actionHeader != null) return actionHeader.Action; using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { return ActionHeader.ReadHeaderValue(reader, _version.Addressing); } } set { if (value != null) SetActionHeader(ActionHeader.Create(value, _version.Addressing)); else SetHeaderProperty(HeaderKind.Action, null); } } internal bool CanRecycle { get { return _headers.Length <= MaxRecycledArrayLength; } } internal bool ContainsOnlyBufferedMessageHeaders { get { return (_bufferedMessageData != null && _collectionVersion == 0); } } internal int CollectionVersion { get { return _collectionVersion; } } public int Count { get { return _headerCount; } } public EndpointAddress FaultTo { get { int index = FindHeaderProperty(HeaderKind.FaultTo); if (index < 0) return null; FaultToHeader faultToHeader = _headers[index].HeaderInfo as FaultToHeader; if (faultToHeader != null) return faultToHeader.FaultTo; using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { return FaultToHeader.ReadHeaderValue(reader, _version.Addressing); } } set { if (value != null) SetFaultToHeader(FaultToHeader.Create(value, _version.Addressing)); else SetHeaderProperty(HeaderKind.FaultTo, null); } } public EndpointAddress From { get { int index = FindHeaderProperty(HeaderKind.From); if (index < 0) return null; FromHeader fromHeader = _headers[index].HeaderInfo as FromHeader; if (fromHeader != null) return fromHeader.From; using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { return FromHeader.ReadHeaderValue(reader, _version.Addressing); } } set { if (value != null) SetFromHeader(FromHeader.Create(value, _version.Addressing)); else SetHeaderProperty(HeaderKind.From, null); } } internal bool HasMustUnderstandBeenModified { get { if (_understoodHeaders != null) { return _understoodHeaders.Modified; } else { return _understoodHeadersModified; } } } public UniqueId MessageId { get { int index = FindHeaderProperty(HeaderKind.MessageId); if (index < 0) return null; MessageIDHeader messageIDHeader = _headers[index].HeaderInfo as MessageIDHeader; if (messageIDHeader != null) return messageIDHeader.MessageId; using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { return MessageIDHeader.ReadHeaderValue(reader, _version.Addressing); } } set { if (value != null) SetMessageIDHeader(MessageIDHeader.Create(value, _version.Addressing)); else SetHeaderProperty(HeaderKind.MessageId, null); } } public MessageVersion MessageVersion { get { return _version; } } public UniqueId RelatesTo { get { return GetRelatesTo(RelatesToHeader.ReplyRelationshipType); } set { SetRelatesTo(RelatesToHeader.ReplyRelationshipType, value); } } public EndpointAddress ReplyTo { get { int index = FindHeaderProperty(HeaderKind.ReplyTo); if (index < 0) return null; ReplyToHeader replyToHeader = _headers[index].HeaderInfo as ReplyToHeader; if (replyToHeader != null) return replyToHeader.ReplyTo; using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { return ReplyToHeader.ReadHeaderValue(reader, _version.Addressing); } } set { if (value != null) SetReplyToHeader(ReplyToHeader.Create(value, _version.Addressing)); else SetHeaderProperty(HeaderKind.ReplyTo, null); } } public Uri To { get { int index = FindHeaderProperty(HeaderKind.To); if (index < 0) return null; ToHeader toHeader = _headers[index].HeaderInfo as ToHeader; if (toHeader != null) return toHeader.To; using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { return ToHeader.ReadHeaderValue(reader, _version.Addressing); } } set { if (value != null) SetToHeader(ToHeader.Create(value, _version.Addressing)); else SetHeaderProperty(HeaderKind.To, null); } } public UnderstoodHeaders UnderstoodHeaders { get { if (_understoodHeaders == null) _understoodHeaders = new UnderstoodHeaders(this, _understoodHeadersModified); return _understoodHeaders; } } public MessageHeaderInfo this[int index] { get { if (index < 0 || index >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("index", index, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } return _headers[index].HeaderInfo; } } public void Add(MessageHeader header) { Insert(_headerCount, header); } internal void AddActionHeader(ActionHeader actionHeader) { Insert(_headerCount, actionHeader, HeaderKind.Action); } internal void AddMessageIDHeader(MessageIDHeader messageIDHeader) { Insert(_headerCount, messageIDHeader, HeaderKind.MessageId); } internal void AddRelatesToHeader(RelatesToHeader relatesToHeader) { Insert(_headerCount, relatesToHeader, HeaderKind.RelatesTo); } internal void AddReplyToHeader(ReplyToHeader replyToHeader) { Insert(_headerCount, replyToHeader, HeaderKind.ReplyTo); } internal void AddToHeader(ToHeader toHeader) { Insert(_headerCount, toHeader, HeaderKind.To); } private void Add(MessageHeader header, HeaderKind kind) { Insert(_headerCount, header, kind); } private void AddHeader(Header header) { InsertHeader(_headerCount, header); } internal void AddUnderstood(int i) { _headers[i].HeaderProcessing |= HeaderProcessing.Understood; MessageHeaders.TraceUnderstood(_headers[i].HeaderInfo); } internal void AddUnderstood(MessageHeaderInfo headerInfo) { if (headerInfo == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo")); for (int i = 0; i < _headerCount; i++) { if ((object)_headers[i].HeaderInfo == (object)headerInfo) { if ((_headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.HeaderAlreadyUnderstood, headerInfo.Name, headerInfo.Namespace), "headerInfo")); } AddUnderstood(i); } } } private void CaptureBufferedHeaders() { CaptureBufferedHeaders(-1); } private void CaptureBufferedHeaders(int exceptIndex) { using (XmlDictionaryReader reader = GetBufferedMessageHeaderReaderAtHeaderContents(_bufferedMessageData)) { for (int i = 0; i < _headerCount; i++) { if (reader.NodeType != XmlNodeType.Element) { if (reader.MoveToContent() != XmlNodeType.Element) break; } Header header = _headers[i]; if (i == exceptIndex || header.HeaderType != HeaderType.BufferedMessageHeader) { reader.Skip(); } else { _headers[i] = new Header(header.HeaderKind, CaptureBufferedHeader(reader, header.HeaderInfo), header.HeaderProcessing); } } } _bufferedMessageData = null; } private BufferedHeader CaptureBufferedHeader(XmlDictionaryReader reader, MessageHeaderInfo headerInfo) { XmlBuffer buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = buffer.OpenSection(_bufferedMessageData.Quotas); writer.WriteNode(reader, false); buffer.CloseSection(); buffer.Close(); return new BufferedHeader(_version, buffer, 0, headerInfo); } private BufferedHeader CaptureBufferedHeader(IBufferedMessageData bufferedMessageData, MessageHeaderInfo headerInfo, int bufferedMessageHeaderIndex) { XmlBuffer buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = buffer.OpenSection(bufferedMessageData.Quotas); WriteBufferedMessageHeader(bufferedMessageData, bufferedMessageHeaderIndex, writer); buffer.CloseSection(); buffer.Close(); return new BufferedHeader(_version, buffer, 0, headerInfo); } private BufferedHeader CaptureWriteableHeader(MessageHeader writeableHeader) { XmlBuffer buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); writeableHeader.WriteHeader(writer, _version); buffer.CloseSection(); buffer.Close(); return new BufferedHeader(_version, buffer, 0, writeableHeader); } public void Clear() { for (int i = 0; i < _headerCount; i++) _headers[i] = new Header(); _headerCount = 0; _collectionVersion++; _bufferedMessageData = null; } public void CopyHeaderFrom(Message message, int headerIndex) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message")); CopyHeaderFrom(message.Headers, headerIndex); } public void CopyHeaderFrom(MessageHeaders collection, int headerIndex) { if (collection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("collection"); } if (collection._version != _version) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionMismatch, collection._version.ToString(), _version.ToString()), "collection")); } if (headerIndex < 0 || headerIndex >= collection._headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", headerIndex, SR.Format(SR.ValueMustBeInRange, 0, collection._headerCount))); } Header header = collection._headers[headerIndex]; HeaderProcessing processing = header.HeaderInfo.MustUnderstand ? HeaderProcessing.MustUnderstand : 0; if ((header.HeaderProcessing & HeaderProcessing.Understood) != 0 || header.HeaderKind != HeaderKind.Unknown) processing |= HeaderProcessing.Understood; switch (header.HeaderType) { case HeaderType.BufferedMessageHeader: AddHeader(new Header(header.HeaderKind, collection.CaptureBufferedHeader(collection._bufferedMessageData, header.HeaderInfo, headerIndex), processing)); break; case HeaderType.ReadableHeader: AddHeader(new Header(header.HeaderKind, header.ReadableHeader, processing)); break; case HeaderType.WriteableHeader: AddHeader(new Header(header.HeaderKind, header.MessageHeader, processing)); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, header.HeaderType))); } } public void CopyHeadersFrom(Message message) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message")); CopyHeadersFrom(message.Headers); } public void CopyHeadersFrom(MessageHeaders collection) { if (collection == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("collection")); for (int i = 0; i < collection._headerCount; i++) CopyHeaderFrom(collection, i); } public void CopyTo(MessageHeaderInfo[] array, int index) { if (array == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("array"); } if (index < 0 || (index + _headerCount) > array.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("index", index, SR.Format(SR.ValueMustBeInRange, 0, array.Length - _headerCount))); } for (int i = 0; i < _headerCount; i++) array[i + index] = _headers[i].HeaderInfo; } private Exception CreateDuplicateHeaderException(HeaderKind kind) { string name; switch (kind) { case HeaderKind.Action: name = AddressingStrings.Action; break; case HeaderKind.FaultTo: name = AddressingStrings.FaultTo; break; case HeaderKind.From: name = AddressingStrings.From; break; case HeaderKind.MessageId: name = AddressingStrings.MessageId; break; case HeaderKind.ReplyTo: name = AddressingStrings.ReplyTo; break; case HeaderKind.To: name = AddressingStrings.To; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, kind))); } return new MessageHeaderException( SR.Format(SR.MultipleMessageHeaders, name, _version.Addressing.Namespace), name, _version.Addressing.Namespace, true); } public int FindHeader(string name, string ns) { if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); if (ns == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns")); if (ns == _version.Addressing.Namespace) { return FindAddressingHeader(name, ns); } else { return FindNonAddressingHeader(name, ns, _version.Envelope.UltimateDestinationActorValues); } } private int FindAddressingHeader(string name, string ns) { int foundAt = -1; for (int i = 0; i < _headerCount; i++) { if (_headers[i].HeaderKind != HeaderKind.Unknown) { MessageHeaderInfo info = _headers[i].HeaderInfo; if (info.Name == name && info.Namespace == ns) { if (foundAt >= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new MessageHeaderException(SR.Format(SR.MultipleMessageHeaders, name, ns), name, ns, true)); } foundAt = i; } } } return foundAt; } private int FindNonAddressingHeader(string name, string ns, string[] actors) { int foundAt = -1; for (int i = 0; i < _headerCount; i++) { if (_headers[i].HeaderKind == HeaderKind.Unknown) { MessageHeaderInfo info = _headers[i].HeaderInfo; if (info.Name == name && info.Namespace == ns) { for (int j = 0; j < actors.Length; j++) { if (actors[j] == info.Actor) { if (foundAt >= 0) { if (actors.Length == 1) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeadersWithActor, name, ns, actors[0]), name, ns, true)); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeaders, name, ns), name, ns, true)); } foundAt = i; } } } } } return foundAt; } public int FindHeader(string name, string ns, params string[] actors) { if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); if (ns == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns")); if (actors == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("actors")); int foundAt = -1; for (int i = 0; i < _headerCount; i++) { MessageHeaderInfo info = _headers[i].HeaderInfo; if (info.Name == name && info.Namespace == ns) { for (int j = 0; j < actors.Length; j++) { if (actors[j] == info.Actor) { if (foundAt >= 0) { if (actors.Length == 1) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeadersWithActor, name, ns, actors[0]), name, ns, true)); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.MultipleMessageHeaders, name, ns), name, ns, true)); } foundAt = i; } } } } return foundAt; } private int FindHeaderProperty(HeaderKind kind) { int index = -1; for (int i = 0; i < _headerCount; i++) { if (_headers[i].HeaderKind == kind) { if (index >= 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateDuplicateHeaderException(kind)); index = i; } } return index; } private int FindRelatesTo(Uri relationshipType, out UniqueId messageId) { UniqueId foundValue = null; int foundIndex = -1; for (int i = 0; i < _headerCount; i++) { if (_headers[i].HeaderKind == HeaderKind.RelatesTo) { Uri tempRelationship; UniqueId tempValue; GetRelatesToValues(i, out tempRelationship, out tempValue); if (relationshipType == tempRelationship) { if (foundValue != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new MessageHeaderException( SR.Format(SR.MultipleRelatesToHeaders, relationshipType.AbsoluteUri), AddressingStrings.RelatesTo, _version.Addressing.Namespace, true)); } foundValue = tempValue; foundIndex = i; } } } messageId = foundValue; return foundIndex; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public IEnumerator<MessageHeaderInfo> GetEnumerator() { MessageHeaderInfo[] headers = new MessageHeaderInfo[_headerCount]; CopyTo(headers, 0); return GetEnumerator(headers); } private IEnumerator<MessageHeaderInfo> GetEnumerator(MessageHeaderInfo[] headers) { IList<MessageHeaderInfo> list = new ReadOnlyCollection<MessageHeaderInfo>(headers); return list.GetEnumerator(); } internal IEnumerator<MessageHeaderInfo> GetUnderstoodEnumerator() { List<MessageHeaderInfo> understoodHeaders = new List<MessageHeaderInfo>(); for (int i = 0; i < _headerCount; i++) { if ((_headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0) { understoodHeaders.Add(_headers[i].HeaderInfo); } } return understoodHeaders.GetEnumerator(); } private static XmlDictionaryReader GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData) { XmlDictionaryReader reader = bufferedMessageData.GetMessageReader(); if (reader.NodeType == XmlNodeType.Element) reader.Read(); else reader.ReadStartElement(); if (reader.NodeType == XmlNodeType.Element) reader.Read(); else reader.ReadStartElement(); return reader; } private XmlDictionaryReader GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex) { // Check if we need to change representations if (_nodeCount > MaxBufferedHeaderNodes || _attrCount > MaxBufferedHeaderAttributes) { CaptureBufferedHeaders(); return _headers[bufferedMessageHeaderIndex].ReadableHeader.GetHeaderReader(); } XmlDictionaryReader reader = GetBufferedMessageHeaderReaderAtHeaderContents(bufferedMessageData); for (;;) { if (reader.NodeType != XmlNodeType.Element) reader.MoveToContent(); if (bufferedMessageHeaderIndex == 0) break; Skip(reader); bufferedMessageHeaderIndex--; } return reader; } private void Skip(XmlDictionaryReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && !reader.IsEmptyElement) { int depth = reader.Depth; do { _attrCount += reader.AttributeCount; _nodeCount++; } while (reader.Read() && depth < reader.Depth); // consume end tag if (reader.NodeType == XmlNodeType.EndElement) { _nodeCount++; reader.Read(); } } else { _attrCount += reader.AttributeCount; _nodeCount++; reader.Read(); } } public T GetHeader<T>(string name, string ns) { return GetHeader<T>(name, ns, DataContractSerializerDefaults.CreateSerializer(typeof(T), name, ns, int.MaxValue/*maxItems*/)); } public T GetHeader<T>(string name, string ns, params string[] actors) { int index = FindHeader(name, ns, actors); if (index < 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.HeaderNotFound, name, ns), name, ns)); return GetHeader<T>(index); } public T GetHeader<T>(string name, string ns, XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); int index = FindHeader(name, ns); if (index < 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(SR.Format(SR.HeaderNotFound, name, ns), name, ns)); return GetHeader<T>(index, serializer); } public T GetHeader<T>(int index) { if (index < 0 || index >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("index", index, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } MessageHeaderInfo headerInfo = _headers[index].HeaderInfo; return GetHeader<T>(index, DataContractSerializerDefaults.CreateSerializer(typeof(T), headerInfo.Name, headerInfo.Namespace, int.MaxValue/*maxItems*/)); } public T GetHeader<T>(int index, XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { return (T)serializer.ReadObject(reader); } } private HeaderKind GetHeaderKind(MessageHeaderInfo headerInfo) { HeaderKind headerKind = HeaderKind.Unknown; if (headerInfo.Namespace == _version.Addressing.Namespace) { if (_version.Envelope.IsUltimateDestinationActor(headerInfo.Actor)) { string name = headerInfo.Name; if (name.Length > 0) { switch (name[0]) { case 'A': if (name == AddressingStrings.Action) { headerKind = HeaderKind.Action; } break; case 'F': if (name == AddressingStrings.From) { headerKind = HeaderKind.From; } else if (name == AddressingStrings.FaultTo) { headerKind = HeaderKind.FaultTo; } break; case 'M': if (name == AddressingStrings.MessageId) { headerKind = HeaderKind.MessageId; } break; case 'R': if (name == AddressingStrings.ReplyTo) { headerKind = HeaderKind.ReplyTo; } else if (name == AddressingStrings.RelatesTo) { headerKind = HeaderKind.RelatesTo; } break; case 'T': if (name == AddressingStrings.To) { headerKind = HeaderKind.To; } break; } } } } ValidateHeaderKind(headerKind); return headerKind; } private void ValidateHeaderKind(HeaderKind headerKind) { if (_version.Envelope == EnvelopeVersion.None) { if (headerKind != HeaderKind.Action && headerKind != HeaderKind.To) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.Format(SR.HeadersCannotBeAddedToEnvelopeVersion, _version.Envelope))); } } if (_version.Addressing == AddressingVersion.None) { if (headerKind != HeaderKind.Unknown && headerKind != HeaderKind.Action && headerKind != HeaderKind.To) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.Format(SR.AddressingHeadersCannotBeAddedToAddressingVersion, _version.Addressing))); } } } public XmlDictionaryReader GetReaderAtHeader(int headerIndex) { if (headerIndex < 0 || headerIndex >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", headerIndex, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } switch (_headers[headerIndex].HeaderType) { case HeaderType.ReadableHeader: return _headers[headerIndex].ReadableHeader.GetHeaderReader(); case HeaderType.WriteableHeader: MessageHeader writeableHeader = _headers[headerIndex].MessageHeader; BufferedHeader bufferedHeader = CaptureWriteableHeader(writeableHeader); _headers[headerIndex] = new Header(_headers[headerIndex].HeaderKind, bufferedHeader, _headers[headerIndex].HeaderProcessing); _collectionVersion++; return bufferedHeader.GetHeaderReader(); case HeaderType.BufferedMessageHeader: return GetBufferedMessageHeaderReader(_bufferedMessageData, headerIndex); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[headerIndex].HeaderType))); } } internal UniqueId GetRelatesTo(Uri relationshipType) { if (relationshipType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("relationshipType")); UniqueId messageId; FindRelatesTo(relationshipType, out messageId); return messageId; } private void GetRelatesToValues(int index, out Uri relationshipType, out UniqueId messageId) { RelatesToHeader relatesToHeader = _headers[index].HeaderInfo as RelatesToHeader; if (relatesToHeader != null) { relationshipType = relatesToHeader.RelationshipType; messageId = relatesToHeader.UniqueId; } else { using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { RelatesToHeader.ReadHeaderValue(reader, _version.Addressing, out relationshipType, out messageId); } } } internal string[] GetHeaderAttributes(string localName, string ns) { string[] attrs = null; if (ContainsOnlyBufferedMessageHeaders) { XmlDictionaryReader reader = _bufferedMessageData.GetMessageReader(); reader.ReadStartElement(); // Envelope reader.ReadStartElement(); // Header for (int index = 0; reader.IsStartElement(); index++) { string value = reader.GetAttribute(localName, ns); if (value != null) { if (attrs == null) attrs = new string[_headerCount]; attrs[index] = value; } if (index == _headerCount - 1) break; reader.Skip(); } reader.Dispose(); } else { for (int index = 0; index < _headerCount; index++) { if (_headers[index].HeaderType != HeaderType.WriteableHeader) { using (XmlDictionaryReader reader = GetReaderAtHeader(index)) { string value = reader.GetAttribute(localName, ns); if (value != null) { if (attrs == null) attrs = new string[_headerCount]; attrs[index] = value; } } } } } return attrs; } internal MessageHeader GetMessageHeader(int index) { if (index < 0 || index >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", index, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } MessageHeader messageHeader; switch (_headers[index].HeaderType) { case HeaderType.WriteableHeader: case HeaderType.ReadableHeader: return _headers[index].MessageHeader; case HeaderType.BufferedMessageHeader: messageHeader = CaptureBufferedHeader(_bufferedMessageData, _headers[index].HeaderInfo, index); _headers[index] = new Header(_headers[index].HeaderKind, messageHeader, _headers[index].HeaderProcessing); _collectionVersion++; return messageHeader; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[index].HeaderType))); } } internal Collection<MessageHeaderInfo> GetHeadersNotUnderstood() { Collection<MessageHeaderInfo> notUnderstoodHeaders = null; for (int headerIndex = 0; headerIndex < _headerCount; headerIndex++) { if (_headers[headerIndex].HeaderProcessing == HeaderProcessing.MustUnderstand) { if (notUnderstoodHeaders == null) notUnderstoodHeaders = new Collection<MessageHeaderInfo>(); MessageHeaderInfo headerInfo = _headers[headerIndex].HeaderInfo; notUnderstoodHeaders.Add(headerInfo); } } return notUnderstoodHeaders; } public bool HaveMandatoryHeadersBeenUnderstood() { return HaveMandatoryHeadersBeenUnderstood(_version.Envelope.MustUnderstandActorValues); } public bool HaveMandatoryHeadersBeenUnderstood(params string[] actors) { if (actors == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("actors")); for (int headerIndex = 0; headerIndex < _headerCount; headerIndex++) { if (_headers[headerIndex].HeaderProcessing == HeaderProcessing.MustUnderstand) { for (int actorIndex = 0; actorIndex < actors.Length; ++actorIndex) { if (_headers[headerIndex].HeaderInfo.Actor == actors[actorIndex]) { return false; } } } } return true; } internal void Init(MessageVersion version, int initialSize) { _nodeCount = 0; _attrCount = 0; if (initialSize < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("initialSize", initialSize, SR.ValueMustBeNonNegative)); } if (version == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); } _version = version; _headers = new Header[initialSize]; } internal void Init(MessageVersion version) { _nodeCount = 0; _attrCount = 0; _version = version; _collectionVersion = 0; } internal void Init(MessageVersion version, XmlDictionaryReader reader, IBufferedMessageData bufferedMessageData, RecycledMessageState recycledMessageState, bool[] understoodHeaders, bool understoodHeadersModified) { _nodeCount = 0; _attrCount = 0; _version = version; _bufferedMessageData = bufferedMessageData; if (version.Envelope != EnvelopeVersion.None) { _understoodHeadersModified = (understoodHeaders != null) && understoodHeadersModified; if (reader.IsEmptyElement) { reader.Read(); return; } EnvelopeVersion envelopeVersion = version.Envelope; Fx.Assert(reader.IsStartElement(XD.MessageDictionary.Header, envelopeVersion.DictionaryNamespace), ""); reader.ReadStartElement(); AddressingDictionary dictionary = XD.AddressingDictionary; if (s_localNames == null) { XmlDictionaryString[] strings = new XmlDictionaryString[7]; strings[(int)HeaderKind.To] = dictionary.To; strings[(int)HeaderKind.Action] = dictionary.Action; strings[(int)HeaderKind.MessageId] = dictionary.MessageId; strings[(int)HeaderKind.RelatesTo] = dictionary.RelatesTo; strings[(int)HeaderKind.ReplyTo] = dictionary.ReplyTo; strings[(int)HeaderKind.From] = dictionary.From; strings[(int)HeaderKind.FaultTo] = dictionary.FaultTo; Interlocked.MemoryBarrier(); s_localNames = strings; } int i = 0; while (reader.IsStartElement()) { ReadBufferedHeader(reader, recycledMessageState, s_localNames, (understoodHeaders == null) ? false : understoodHeaders[i++]); } reader.ReadEndElement(); } _collectionVersion = 0; } public void Insert(int headerIndex, MessageHeader header) { if (header == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("header")); if (!header.IsMessageVersionSupported(_version)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionNotSupported, header.GetType().FullName, _version.Envelope.ToString()), "header")); Insert(headerIndex, header, GetHeaderKind(header)); } private void Insert(int headerIndex, MessageHeader header, HeaderKind kind) { ReadableMessageHeader readableMessageHeader = header as ReadableMessageHeader; HeaderProcessing processing = header.MustUnderstand ? HeaderProcessing.MustUnderstand : 0; if (kind != HeaderKind.Unknown) processing |= HeaderProcessing.Understood; if (readableMessageHeader != null) InsertHeader(headerIndex, new Header(kind, readableMessageHeader, processing)); else InsertHeader(headerIndex, new Header(kind, header, processing)); } private void InsertHeader(int headerIndex, Header header) { ValidateHeaderKind(header.HeaderKind); if (headerIndex < 0 || headerIndex > _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", headerIndex, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } if (_headerCount == _headers.Length) { if (_headers.Length == 0) { _headers = new Header[1]; } else { Header[] newHeaders = new Header[_headers.Length * 2]; _headers.CopyTo(newHeaders, 0); _headers = newHeaders; } } if (headerIndex < _headerCount) { if (_bufferedMessageData != null) { for (int i = headerIndex; i < _headerCount; i++) { if (_headers[i].HeaderType == HeaderType.BufferedMessageHeader) { CaptureBufferedHeaders(); break; } } } Array.Copy(_headers, headerIndex, _headers, headerIndex + 1, _headerCount - headerIndex); } _headers[headerIndex] = header; _headerCount++; _collectionVersion++; } internal bool IsUnderstood(int i) { return (_headers[i].HeaderProcessing & HeaderProcessing.Understood) != 0; } internal bool IsUnderstood(MessageHeaderInfo headerInfo) { if (headerInfo == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo")); for (int i = 0; i < _headerCount; i++) { if ((object)_headers[i].HeaderInfo == (object)headerInfo) { if (IsUnderstood(i)) return true; } } return false; } private void ReadBufferedHeader(XmlDictionaryReader reader, RecycledMessageState recycledMessageState, XmlDictionaryString[] localNames, bool understood) { string actor; bool mustUnderstand; bool relay; bool isRefParam; if (_version.Addressing == AddressingVersion.None && reader.NamespaceURI == AddressingVersion.None.Namespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.Format(SR.AddressingHeadersCannotBeAddedToAddressingVersion, _version.Addressing))); } MessageHeader.GetHeaderAttributes(reader, _version, out actor, out mustUnderstand, out relay, out isRefParam); HeaderKind kind = HeaderKind.Unknown; MessageHeaderInfo info = null; if (_version.Envelope.IsUltimateDestinationActor(actor)) { Fx.Assert(_version.Addressing.DictionaryNamespace != null, "non-None Addressing requires a non-null DictionaryNamespace"); kind = (HeaderKind)reader.IndexOfLocalName(localNames, _version.Addressing.DictionaryNamespace); switch (kind) { case HeaderKind.To: info = ToHeader.ReadHeader(reader, _version.Addressing, recycledMessageState.UriCache, actor, mustUnderstand, relay); break; case HeaderKind.Action: info = ActionHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay); break; case HeaderKind.MessageId: info = MessageIDHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay); break; case HeaderKind.RelatesTo: info = RelatesToHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay); break; case HeaderKind.ReplyTo: info = ReplyToHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay); break; case HeaderKind.From: info = FromHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay); break; case HeaderKind.FaultTo: info = FaultToHeader.ReadHeader(reader, _version.Addressing, actor, mustUnderstand, relay); break; default: kind = HeaderKind.Unknown; break; } } if (info == null) { info = recycledMessageState.HeaderInfoCache.TakeHeaderInfo(reader, actor, mustUnderstand, relay, isRefParam); reader.Skip(); } HeaderProcessing processing = mustUnderstand ? HeaderProcessing.MustUnderstand : 0; if (kind != HeaderKind.Unknown || understood) { processing |= HeaderProcessing.Understood; MessageHeaders.TraceUnderstood(info); } AddHeader(new Header(kind, info, processing)); } internal void Recycle(HeaderInfoCache headerInfoCache) { for (int i = 0; i < _headerCount; i++) { if (_headers[i].HeaderKind == HeaderKind.Unknown) { headerInfoCache.ReturnHeaderInfo(_headers[i].HeaderInfo); } } Clear(); _collectionVersion = 0; if (_understoodHeaders != null) { _understoodHeaders.Modified = false; } } internal void RemoveUnderstood(MessageHeaderInfo headerInfo) { if (headerInfo == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("headerInfo")); for (int i = 0; i < _headerCount; i++) { if ((object)_headers[i].HeaderInfo == (object)headerInfo) { if ((_headers[i].HeaderProcessing & HeaderProcessing.Understood) == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.HeaderAlreadyNotUnderstood, headerInfo.Name, headerInfo.Namespace), "headerInfo")); } _headers[i].HeaderProcessing &= ~HeaderProcessing.Understood; } } } public void RemoveAll(string name, string ns) { if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); if (ns == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns")); for (int i = _headerCount - 1; i >= 0; i--) { MessageHeaderInfo info = _headers[i].HeaderInfo; if (info.Name == name && info.Namespace == ns) { RemoveAt(i); } } } public void RemoveAt(int headerIndex) { if (headerIndex < 0 || headerIndex >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", headerIndex, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } if (_bufferedMessageData != null && _headers[headerIndex].HeaderType == HeaderType.BufferedMessageHeader) CaptureBufferedHeaders(headerIndex); Array.Copy(_headers, headerIndex + 1, _headers, headerIndex, _headerCount - headerIndex - 1); _headers[--_headerCount] = new Header(); _collectionVersion++; } internal void ReplaceAt(int headerIndex, MessageHeader header) { if (headerIndex < 0 || headerIndex >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", headerIndex, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } if (header == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("header"); } ReplaceAt(headerIndex, header, GetHeaderKind(header)); } private void ReplaceAt(int headerIndex, MessageHeader header, HeaderKind kind) { HeaderProcessing processing = header.MustUnderstand ? HeaderProcessing.MustUnderstand : 0; if (kind != HeaderKind.Unknown) processing |= HeaderProcessing.Understood; ReadableMessageHeader readableMessageHeader = header as ReadableMessageHeader; if (readableMessageHeader != null) _headers[headerIndex] = new Header(kind, readableMessageHeader, processing); else _headers[headerIndex] = new Header(kind, header, processing); _collectionVersion++; } public void SetAction(XmlDictionaryString action) { if (action == null) SetHeaderProperty(HeaderKind.Action, null); else SetActionHeader(ActionHeader.Create(action, _version.Addressing)); } internal void SetActionHeader(ActionHeader actionHeader) { SetHeaderProperty(HeaderKind.Action, actionHeader); } internal void SetFaultToHeader(FaultToHeader faultToHeader) { SetHeaderProperty(HeaderKind.FaultTo, faultToHeader); } internal void SetFromHeader(FromHeader fromHeader) { SetHeaderProperty(HeaderKind.From, fromHeader); } internal void SetMessageIDHeader(MessageIDHeader messageIDHeader) { SetHeaderProperty(HeaderKind.MessageId, messageIDHeader); } internal void SetRelatesTo(Uri relationshipType, UniqueId messageId) { if (relationshipType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("relationshipType"); } RelatesToHeader relatesToHeader; if (!object.ReferenceEquals(messageId, null)) { relatesToHeader = RelatesToHeader.Create(messageId, _version.Addressing, relationshipType); } else { relatesToHeader = null; } SetRelatesTo(RelatesToHeader.ReplyRelationshipType, relatesToHeader); } private void SetRelatesTo(Uri relationshipType, RelatesToHeader relatesToHeader) { UniqueId previousUniqueId; int index = FindRelatesTo(relationshipType, out previousUniqueId); if (index >= 0) { if (relatesToHeader == null) { RemoveAt(index); } else { ReplaceAt(index, relatesToHeader, HeaderKind.RelatesTo); } } else if (relatesToHeader != null) { Add(relatesToHeader, HeaderKind.RelatesTo); } } internal void SetReplyToHeader(ReplyToHeader replyToHeader) { SetHeaderProperty(HeaderKind.ReplyTo, replyToHeader); } internal void SetToHeader(ToHeader toHeader) { SetHeaderProperty(HeaderKind.To, toHeader); } private void SetHeaderProperty(HeaderKind kind, MessageHeader header) { int index = FindHeaderProperty(kind); if (index >= 0) { if (header == null) { RemoveAt(index); } else { ReplaceAt(index, header, kind); } } else if (header != null) { Add(header, kind); } } public void WriteHeader(int headerIndex, XmlWriter writer) { WriteHeader(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteHeader(int headerIndex, XmlDictionaryWriter writer) { WriteStartHeader(headerIndex, writer); WriteHeaderContents(headerIndex, writer); writer.WriteEndElement(); } public void WriteStartHeader(int headerIndex, XmlWriter writer) { WriteStartHeader(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteStartHeader(int headerIndex, XmlDictionaryWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (headerIndex < 0 || headerIndex >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", headerIndex, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } switch (_headers[headerIndex].HeaderType) { case HeaderType.ReadableHeader: case HeaderType.WriteableHeader: _headers[headerIndex].MessageHeader.WriteStartHeader(writer, _version); break; case HeaderType.BufferedMessageHeader: WriteStartBufferedMessageHeader(_bufferedMessageData, headerIndex, writer); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[headerIndex].HeaderType))); } } public void WriteHeaderContents(int headerIndex, XmlWriter writer) { WriteHeaderContents(headerIndex, XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteHeaderContents(int headerIndex, XmlDictionaryWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (headerIndex < 0 || headerIndex >= _headerCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("headerIndex", headerIndex, SR.Format(SR.ValueMustBeInRange, 0, _headerCount))); } switch (_headers[headerIndex].HeaderType) { case HeaderType.ReadableHeader: case HeaderType.WriteableHeader: _headers[headerIndex].MessageHeader.WriteHeaderContents(writer, _version); break; case HeaderType.BufferedMessageHeader: WriteBufferedMessageHeaderContents(_bufferedMessageData, headerIndex, writer); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidEnumValue, _headers[headerIndex].HeaderType))); } } private static void TraceUnderstood(MessageHeaderInfo info) { } private void WriteBufferedMessageHeader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer) { using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex)) { writer.WriteNode(reader, false); } } private void WriteStartBufferedMessageHeader(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer) { using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex)) { writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, false); } } private void WriteBufferedMessageHeaderContents(IBufferedMessageData bufferedMessageData, int bufferedMessageHeaderIndex, XmlWriter writer) { using (XmlReader reader = GetBufferedMessageHeaderReader(bufferedMessageData, bufferedMessageHeaderIndex)) { if (!reader.IsEmptyElement) { reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) { writer.WriteNode(reader, false); } reader.ReadEndElement(); } } } internal enum HeaderType : byte { Invalid, ReadableHeader, BufferedMessageHeader, WriteableHeader } internal enum HeaderKind : byte { Action, FaultTo, From, MessageId, ReplyTo, RelatesTo, To, Unknown, } [Flags] internal enum HeaderProcessing : byte { MustUnderstand = 0x1, Understood = 0x2, } internal struct Header { private HeaderType _type; private HeaderKind _kind; private HeaderProcessing _processing; private MessageHeaderInfo _info; public Header(HeaderKind kind, MessageHeaderInfo info, HeaderProcessing processing) { _kind = kind; _type = HeaderType.BufferedMessageHeader; _info = info; _processing = processing; } public Header(HeaderKind kind, ReadableMessageHeader readableHeader, HeaderProcessing processing) { _kind = kind; _type = HeaderType.ReadableHeader; _info = readableHeader; _processing = processing; } public Header(HeaderKind kind, MessageHeader header, HeaderProcessing processing) { _kind = kind; _type = HeaderType.WriteableHeader; _info = header; _processing = processing; } public HeaderType HeaderType { get { return _type; } } public HeaderKind HeaderKind { get { return _kind; } } public MessageHeaderInfo HeaderInfo { get { return _info; } } public MessageHeader MessageHeader { get { Fx.Assert(_type == HeaderType.WriteableHeader || _type == HeaderType.ReadableHeader, ""); return (MessageHeader)_info; } } public HeaderProcessing HeaderProcessing { get { return _processing; } set { _processing = value; } } public ReadableMessageHeader ReadableHeader { get { Fx.Assert(_type == HeaderType.ReadableHeader, ""); return (ReadableMessageHeader)_info; } } } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using LaunchPad.Models; namespace LaunchPad.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("LaunchPad.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("LaunchPad.Models.Job", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("Date"); b.Property<int>("JobId"); b.Property<int>("JobType"); b.Property<string>("Outcome"); b.Property<int>("RecurringId"); b.Property<int>("ScriptId"); b.Property<int>("Status"); b.Property<string>("UserName"); b.HasKey("Id"); }); modelBuilder.Entity("LaunchPad.Models.Script", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Author"); b.Property<string>("LastOutput"); b.Property<string>("Name") .IsRequired() .HasAnnotation("MaxLength", 257); b.HasKey("Id"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("LaunchPad.Models.Job", b => { b.HasOne("LaunchPad.Models.Script") .WithMany() .HasForeignKey("ScriptId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("LaunchPad.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("LaunchPad.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("LaunchPad.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// 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 ILCompiler.DependencyAnalysis.ReadyToRun; namespace ILCompiler.IBC { public class IBCException : Exception { public IBCException(string message) : base(message) { } } public static class IBCData { private static readonly SectionTypeInfo[] s_sectionTypeInfo = ComputeSectionTypeInfos(); // Methods and types for managing the various stream types public enum TokenType { MetaDataToken, MethodToken, TypeToken, TokenTypeOther } public struct SectionTypeInfo { public readonly TokenType TokenType; public readonly string Description; public SectionTypeInfo(TokenType tokenType, SectionFormat section) { TokenType = tokenType; Description = section.ToString(); } } // // Class constuctor for class IBCData // private static SectionTypeInfo[] ComputeSectionTypeInfos() { TokenType tokenType; SectionTypeInfo[] sectionTypeInfo = new SectionTypeInfo[(int)SectionFormat.SectionFormatCount]; tokenType = TokenType.TokenTypeOther; sectionTypeInfo[(int)SectionFormat.BasicBlockInfo] = new SectionTypeInfo(tokenType, SectionFormat.BasicBlockInfo); sectionTypeInfo[(int)SectionFormat.BlobStream] = new SectionTypeInfo(tokenType, SectionFormat.BlobStream); for (SectionFormat section = 0; section < SectionFormat.SectionFormatCount; section++) { // // Initialize tokenType, commonMask and description with their typical values // tokenType = TokenType.MetaDataToken; // // Override the typical values of tokenType or commonMask // using this switch statement whenever necessary // switch (section) { case SectionFormat.ScenarioInfo: case SectionFormat.BasicBlockInfo: case SectionFormat.BlobStream: tokenType = TokenType.TokenTypeOther; break; case SectionFormat.TypeProfilingData: case SectionFormat.GenericTypeProfilingData: tokenType = TokenType.TypeToken; break; case SectionFormat.MethodProfilingData: tokenType = TokenType.MethodToken; break; } sectionTypeInfo[(int)section] = new SectionTypeInfo(tokenType, section); } return sectionTypeInfo; } public static bool IsTokenList(SectionFormat sectionType) { return (s_sectionTypeInfo[(int)sectionType].TokenType != TokenType.TokenTypeOther); } public enum SectionIteratorKind : int { None, All, BasicBlocks, TokenFlags } public static IEnumerable<SectionFormat> SectionIterator(SectionIteratorKind iteratorKind) { switch (iteratorKind) { case SectionIteratorKind.BasicBlocks: yield return SectionFormat.BasicBlockInfo; yield return SectionFormat.MethodProfilingData; break; case SectionIteratorKind.TokenFlags: case SectionIteratorKind.All: for (SectionFormat section = 0; section < SectionFormat.SectionFormatCount; section++) { if (IBCData.IsTokenList(section) || iteratorKind == SectionIteratorKind.All) { yield return section; } } break; default: throw new IBCException("Unsupported iteratorKind"); } } } // Minified files store streams of tokens more efficiently by stripping // off the top byte unless it has changed. This class is useful to both // the reader and the writer for keeping track of the state necessary // to write the next token. public class LastTokens { public uint LastMethodToken = 0x06000000; public uint LastBlobToken; public uint LastAssemblyToken = 0x23000000; public uint LastExternalTypeToken = 0x62000000; public uint LastExternalNamespaceToken = 0x61000000; public uint LastExternalSignatureToken = 0x63000000; } public static class Constants { public const uint HeaderMagicNumber = 0xb1d0f11e; public const uint FooterMagicNumber = 0xb4356f98; // What is the newest version? public const int CurrentMajorVersion = 3; public const int CurrentMinorVersion = 0; // Unless there is a reason to use a newer format, IBCMerge // should write data in this version by default. public const int DefaultMajorVersion = 2; public const int DefaultMinorVersion = 1; // What is the oldest version that can be read? public const int CompatibleMajorVersion = 1; public const int CompatibleMinorVersion = 0; public const int LowestMajorVersionSupportingMinify = 3; [Flags] public enum FileFlags : uint { Empty = 0, Minified = 1, PartialNGen = 2 } } public static class Utilities { public static uint InitialTokenForSection(SectionFormat format) { return ((uint)format - (uint)CONSTANT.FirstTokenFlagSection) << 24; } } public class ScenarioRunData { public DateTime RunTime; public Guid Mvid; public string CommandLine; public string SystemInformation; } public class ScenarioData { public ScenarioData() { Runs = new List<ScenarioRunData>(); } public uint Id; public uint Mask; public uint Priority; public string Name; public List<ScenarioRunData> Runs; } public class BasicBlockData { public uint ILOffset; public uint ExecutionCount; } public class MethodData { public MethodData() { BasicBlocks = new List<BasicBlockData>(); } public uint Token; public uint ILSize; public List<BasicBlockData> BasicBlocks; } public class TokenData { public uint Token; public uint Flags; public uint? ScenarioMask; // Scenario masks aren't stored in minified files. } public abstract class BlobEntry { public uint Token; public BlobType Type; public class PoolEntry : BlobEntry { public byte[] Data; } public class SignatureEntry : BlobEntry { public byte[] Signature; } public class ExternalNamespaceEntry : BlobEntry { public byte[] Name; } public class ExternalTypeEntry : BlobEntry { public uint AssemblyToken; public uint NestedClassToken; public uint NamespaceToken; public byte[] Name; } public class ExternalSignatureEntry : BlobEntry { public byte[] Signature; } public class ExternalMethodEntry : BlobEntry { public uint ClassToken; public uint SignatureToken; public byte[] Name; } public class UnknownEntry : BlobEntry { public byte[] Payload; } public class EndOfStreamEntry : BlobEntry { } } // Fields are null if the corresponding section did not occur in the file. public class AssemblyData { public AssemblyData() { // Tokens is special in that it represents more than one section of // the file. For that reason it's always initialized. Tokens = new Dictionary<SectionFormat, List<TokenData>>(); } public uint FormatMajorVersion; public uint FormatMinorVersion; public Guid Mvid; public bool PartialNGen; public uint TotalNumberOfRuns; public List<ScenarioData> Scenarios; public List<MethodData> Methods; public Dictionary<SectionFormat, List<TokenData>> Tokens { get; private set; } public List<BlobEntry> BlobStream; } // // Token tags. // public enum CorTokenType : uint { mdtModule = 0x00000000, // mdtTypeRef = 0x01000000, // mdtTypeDef = 0x02000000, // mdtFieldDef = 0x04000000, // mdtMethodDef = 0x06000000, // mdtParamDef = 0x08000000, // mdtInterfaceImpl = 0x09000000, // mdtMemberRef = 0x0a000000, // mdtConstant = 0x0b000000, // mdtCustomAttribute = 0x0c000000, // mdtFieldMarshal = 0x0d000000, // mdtPermission = 0x0e000000, // mdtClassLayout = 0x0f000000, // mdtFieldLayout = 0x10000000, // mdtSignature = 0x11000000, // mdtEventMap = 0x12000000, // mdtEvent = 0x14000000, // mdtPropertyMap = 0x15000000, // mdtProperty = 0x17000000, // mdtMethodSemantics = 0x18000000, // mdtMethodImpl = 0x19000000, // mdtModuleRef = 0x1a000000, // mdtTypeSpec = 0x1b000000, // mdtImplMap = 0x1c000000, // mdtFieldRVA = 0x1d000000, // mdtAssembly = 0x20000000, // mdtAssemblyRef = 0x23000000, // mdtFile = 0x26000000, // mdtExportedType = 0x27000000, // mdtManifestResource = 0x28000000, // mdtNestedClass = 0x29000000, // mdtGenericParam = 0x2a000000, // mdtMethodSpec = 0x2b000000, // mdtGenericParamConstraint = 0x2c000000, // mdtLastMetadataTable = mdtGenericParamConstraint, ibcExternalNamespace = 0x61000000, ibcExternalType = 0x62000000, ibcExternalSignature = 0x63000000, ibcExternalMethod = 0x64000000, ibcTypeSpec = 0x68000000, ibcMethodSpec = 0x69000000, mdtString = 0x70000000, // mdtName = 0x71000000, // mdtBaseType = 0x72000000, // Leave this on the high end value. This does not correspond to metadata table } public static class Cor { public static class Macros { // // Build / decompose tokens. // public static uint RidToToken(uint rid, CorTokenType tktype) { return (((uint)rid) | ((uint)tktype)); } public static uint TokenFromRid(uint rid, CorTokenType tktype) { return (((uint)rid) | ((uint)tktype)); } public static uint RidFromToken(uint tk) { return (uint)(((uint)tk) & 0x00ffffff); } public static CorTokenType TypeFromToken(uint tk) { return ((CorTokenType)(((uint)tk) & 0xff000000)); } public static bool IsNilToken(uint tk) { return ((RidFromToken(tk)) == 0); } } } public static class Macros { // Macros for testing MethodSigFlags public static bool IsInstantiationNeeded(uint flags) { return (flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MethodInstantiation) != 0; } public static bool IsSlotUsedInsteadOfToken(uint flags) { return (flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_SlotInsteadOfToken) != 0; } public static bool IsUnboxingStub(uint flags) { return (flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_UnboxingStub) != 0; } public static bool IsInstantiatingStub(uint flags) { return (flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_InstantiatingStub) != 0; } } public enum SectionFormat : int { ScenarioInfo = 0, BasicBlockInfo = 1, BlobStream = 2, ModuleProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtModule >> 24), TypeRefProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtTypeRef >> 24), TypeProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtTypeDef >> 24), FieldDefProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtFieldDef >> 24), MethodProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtMethodDef >> 24), ParamDefProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtParamDef >> 24), InterfaceImplProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtInterfaceImpl >> 24), MemberRefProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtMemberRef >> 24), ConstantProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtConstant >> 24), CustomAttributeProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtCustomAttribute >> 24), FieldMarshalProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtFieldMarshal >> 24), PermissionProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtPermission >> 24), ClassLayoutProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtClassLayout >> 24), FieldLayoutProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtFieldLayout >> 24), SignatureProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtSignature >> 24), EventMapProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtEventMap >> 24), EventProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtEvent >> 24), PropertyMapProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtPropertyMap >> 24), PropertyProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtProperty >> 24), MethodSemanticsProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtMethodSemantics >> 24), MethodImplProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtMethodImpl >> 24), ModuleRefProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtModuleRef >> 24), TypeSpecProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtTypeSpec >> 24), ImplMapProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtImplMap >> 24), FieldRVAProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtFieldRVA >> 24), AssemblyProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtAssembly >> 24), AssemblyRefProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtAssemblyRef >> 24), FileProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtFile >> 24), ExportedTypeProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtExportedType >> 24), ManifestResourceProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtManifestResource >> 24), NestedClassProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtNestedClass >> 24), GenericParamProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtGenericParam >> 24), MethodSpecProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtMethodSpec >> 24), GenericParamConstraintProfilingData = CONSTANT.FirstTokenFlagSection + ((int)CorTokenType.mdtGenericParamConstraint >> 24), StringPoolProfilingData, GuidPoolProfilingData, BlobPoolProfilingData, UserStringPoolProfilingData, GenericTypeProfilingData = 63, // 0x3f SectionFormatCount = 64, // 0x40 SectionFormatInvalid = -1, } public enum BlobType : int { // IMPORTANT: Keep the first four enums together in the same order and at the // very begining of this enum. See MetaModelPub.h for the order MetadataStringPool = 0, MetadataGuidPool = 1, MetadataBlobPool = 2, MetadataUserStringPool = 3, FirstMetadataPool = MetadataStringPool, LastMetadataPool = MetadataUserStringPool, ParamTypeSpec = 4, // Instantiated Type Signature ParamMethodSpec = 5, // Instantiated Method Signature ExternalNamespaceDef = 6, // External Namespace Token Definition ExternalTypeDef = 7, // External Type Token Definition ExternalSignatureDef = 8, // External Signature Definition ExternalMethodDef = 9, // External Method Token Definition IllegalBlob = 10, // Failed to allocate the blob EndOfBlobStream = -1 } public enum ModuleId : uint { CurrentModule = 0, // Tokens are encoded/decoded using current modules metadata ExternalModule = 1, // Tokens are (or will be) encoded/decoded using ibcExternalType and ibcExternalMethod } internal static class CONSTANT { public const SectionFormat FirstTokenFlagSection = SectionFormat.BlobStream + 1; } }
// 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.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using OpenLiveWriter.Interop.Windows; using System.Windows.Forms; namespace OpenLiveWriter.CoreServices { public enum TimePeriod { MINUTES = 0, HOURS = 1, DAYS = 2, WEEKS = 3, SECONDS = 4 }; /// <summary> /// Summary description for DateTimeHelper. /// </summary> public class DateTimeHelper { private DateTimeHelper() { } /// <summary> /// Returns the current time in UTC. /// </summary> public static DateTime UtcNow { get { return LocalToUtc(DateTime.Now); } } private const long BASETICKS = 504911232000000000; //new DateTime(1601, 1, 1).Ticks; /// <summary> /// Converts local DateTime to local FILETIME, /// or UTC DateTime to UTC FILETIME. /// </summary> public static System.Runtime.InteropServices.ComTypes.FILETIME ToFileTime(DateTime dateTime) { long fileTimeVal = dateTime.Ticks - BASETICKS; System.Runtime.InteropServices.ComTypes.FILETIME result = new System.Runtime.InteropServices.ComTypes.FILETIME(); result.dwHighDateTime = (int)(fileTimeVal >> 32); result.dwLowDateTime = (int)(fileTimeVal & 0xFFFFFFFF); return result; } /// <summary> /// Converts local FILETIME to local DateTime, /// or UTC FILETIME to UTC DateTime. /// </summary> public static DateTime ToDateTime(System.Runtime.InteropServices.ComTypes.FILETIME fileTime) { long ticks = BASETICKS + ((fileTime.dwLowDateTime & 0xFFFFFFFF) | ((long)fileTime.dwHighDateTime << 32)); return new DateTime(Math.Min(Math.Max(DateTime.MinValue.Ticks, ticks), DateTime.MaxValue.Ticks)); } /// <summary> /// Convert from a .NET to a W3C date-time (http://www.w3.org/TR/NOTE-datetime) /// </summary> /// <param name="dateTime">date time </param> /// <returns>w3c date-time</returns> public static string ToW3CDateTime(DateTime dateTime) { return dateTime.ToString(W3C_DATE_FORMAT, CultureInfo.InvariantCulture); } /// <summary> /// Convert from a W3C (http://www.w3.org/TR/NOTE-datetime) to a .NET DateTime (based in local timezone) /// </summary> /// <param name="w3cDateTime">w3c date-time</param> /// <returns></returns> public static DateTime ToDateTime(string w3cDateTime) { IFormatProvider culture = new CultureInfo("en-US", true); DateTime dateTime; try { dateTime = DateTime.ParseExact(w3cDateTime, W3C_DATE_FORMATS, culture, DateTimeStyles.AllowWhiteSpaces); } catch (Exception) { //Now try the W3C UTC date formats //Since .NET doesn't realize the the 'Z' is an indicator of the GMT timezone, //ParseExact will return the date exactly as parsed (no shift for GMT) so we have //to call ToLocalTime() on it to get it into the local time zone. dateTime = DateTime.ParseExact(w3cDateTime, W3C_DATE_FORMATS_UTC, culture, DateTimeStyles.AllowWhiteSpaces); dateTime = LocalToUtc(dateTime); } return dateTime; } private const string W3C_DATE_FORMAT = "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz"; private static readonly string[] W3C_DATE_FORMATS = new string[] { "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz" }; private static readonly string[] W3C_DATE_FORMATS_UTC = new string[] { "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy'-'MM'-'dd'T'HH':'mm'Z'" }; public static DateTime LocalToUtc(DateTime localTime) { System.Runtime.InteropServices.ComTypes.FILETIME localFileTime = ToFileTime(localTime); System.Runtime.InteropServices.ComTypes.FILETIME utcFileTime; Kernel32.LocalFileTimeToFileTime(ref localFileTime, out utcFileTime); return ToDateTime(utcFileTime); } public static DateTime UtcToLocal(DateTime utcTime) { System.Runtime.InteropServices.ComTypes.FILETIME utcFileTime = ToFileTime(utcTime); System.Runtime.InteropServices.ComTypes.FILETIME localFileTime; Kernel32.FileTimeToLocalFileTime(ref utcFileTime, out localFileTime); return ToDateTime(localFileTime); } public static TimeSpan GetUtcOffset(DateTime forLocalTime) { DateTime utc = LocalToUtc(forLocalTime); return forLocalTime - utc; } /// <summary> /// Gets the start and end dates for "this week" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetThisWeekDateRange(DateTime dateTime, out DateTime start, out DateTime end) { dateTime = dateTime.Date; start = dateTime.AddDays(-(int)dateTime.DayOfWeek); end = dateTime.AddDays((int)DayOfWeek.Saturday - (int)dateTime.DayOfWeek); } /// <summary> /// Gets the start and end dates for the "last week" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetLastWeekDateRange(DateTime dateTime, out DateTime start, out DateTime end) { dateTime = dateTime.Date.AddDays(-7); start = dateTime.AddDays(-(int)dateTime.DayOfWeek); end = dateTime.AddDays((int)DayOfWeek.Saturday - (int)dateTime.DayOfWeek); } /// <summary> /// Gets the start and end dates for the "two weeks ago" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetTwoWeeksAgoDateRange(DateTime dateTime, out DateTime start, out DateTime end) { dateTime = dateTime.Date.AddDays(-14); start = dateTime.AddDays(-(int)dateTime.DayOfWeek); end = dateTime.AddDays((int)DayOfWeek.Saturday - (int)dateTime.DayOfWeek); } /// <summary> /// Gets the start and end dates for the "three weeks ago" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetThreeWeeksAgoDateRange(DateTime dateTime, out DateTime start, out DateTime end) { dateTime = dateTime.Date.AddDays(-21); start = dateTime.AddDays(-(int)dateTime.DayOfWeek); end = dateTime.AddDays((int)DayOfWeek.Saturday - (int)dateTime.DayOfWeek); } /// <summary> /// Gets the start and end dates for "this month" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetThisMonthDateRange(DateTime dateTime, out DateTime start, out DateTime end) { dateTime = dateTime.Date; start = dateTime.AddDays(-(dateTime.Day - 1)); end = dateTime.AddDays(DateTime.DaysInMonth(dateTime.Year, dateTime.Month) - dateTime.Day); } /// <summary> /// Gets the start and end dates for "last month" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetLastMonthDateRange(DateTime dateTime, out DateTime start, out DateTime end) { dateTime = dateTime.Date; end = dateTime.AddDays(-dateTime.Day); start = end.AddDays(-(end.Day - 1)); } /// <summary> /// Gets the start and end dates for "last 3 days" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetLast3DaysDateRange(DateTime dateTime, out DateTime start, out DateTime end) { end = dateTime.Date; start = end.AddDays(-2); } /// <summary> /// Gets the start and end dates for "last 7 days" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetLast7DaysDateRange(DateTime dateTime, out DateTime start, out DateTime end) { end = dateTime.Date; start = end.AddDays(-6); } /// <summary> /// Gets the start and end dates for "last 30 days" date-range, relative to a specified date. /// </summary> /// <param name="dateTime">The DateTime that the calculation is relative to.</param> /// <param name="start">Start date.</param> /// <param name="end">End date.</param> public static void GetLast30DaysDateRange(DateTime dateTime, out DateTime start, out DateTime end) { end = dateTime.Date; start = end.AddDays(-29); } /// <summary> /// Strips Whidbey dates of their high byte information (which distinguishes /// UTC times from local times, or "Unspecified"). /// /// If the high byte information is allowed to remain in the object, we get /// big problems trying to deserialize these values from .NET 1.1 processes. /// </summary> public static DateTime MakeSafeForSerialization(DateTime val) { return new DateTime(val.Ticks); } } public class DateTimerPickerExtended : DateTimePicker { public DateTimerPickerExtended() : base() { } private bool lastTimeChangedWasChecked = false; protected override void OnValueChanged(EventArgs eventargs) { lastTimeChangedWasChecked = Checked; base.OnValueChanged(eventargs); } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (lastTimeChangedWasChecked != Checked) OnValueChanged(EventArgs.Empty); } protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (lastTimeChangedWasChecked != Checked) OnValueChanged(EventArgs.Empty); } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor(s): * UTF-Unknown Contributors (2019) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ namespace UtfUnknown.Core; /// <summary> /// This class defines the available codepage .NET Name. /// </summary> /// <remarks>Based on https://github.com/dotnet/corefx/blob/cf28b7896a762f71c990a5896a160a4138d833c9/src/System.Text.Encoding.CodePages/src/System/Text/EncodingTable.Data.cs</remarks> public static class CodepageName { /// <summary> /// ASCII codepage name. /// </summary> public const string ASCII = "ascii"; /// <summary> /// UTF-7 codepage name. /// </summary> public const string UTF7 = "utf-7"; /// <summary> /// UTF-8 codepage name. /// </summary> public const string UTF8 = "utf-8"; /// <summary> /// UTF-16LE codepage name. /// </summary> public const string UTF16_LE = "utf-16le"; /// <summary> /// UTF-16BE codepage name. /// </summary> public const string UTF16_BE = "utf-16be"; /// <summary> /// UTF-32LE codepage name. /// </summary> public const string UTF32_LE = "utf-32le"; /// <summary> /// UTF-32BE codepage name. /// </summary> public const string UTF32_BE = "utf-32be"; /// <summary> /// EUC Japanese codepage name. /// </summary> /// <remarks> /// Are other aliases x-euc, x-euc-jp, iso-2022-jpeuc, extended_unix_code_packed_format_for_japanese in .NET /// </remarks> public const string EUC_JP = "euc-jp"; /// <summary> /// EUC Korean codepage name. /// </summary> /// <remarks> /// Are other aliases iso-2022-kr-8, iso-2022-kr-8bit, cseuckr in .NET /// </remarks> public const string EUC_KR = "euc-kr"; /// <summary> /// EUC Taiwan codepage name. /// </summary> /// <remarks> /// Not supported. /// </remarks> public const string EUC_TW = "euc-tw"; /// <summary> /// ISO 2022 Chinese codepage name. /// </summary> /// <remarks> /// Supported by alias is x-cp50227 (Codepage 50227) in. NET. Codepage identifier 50229 is currently unsupported (see for example https://github.com/microsoft/referencesource/blob/17b97365645da62cf8a49444d979f94a59bbb155/mscorlib/system/text/iso2022encoding.cs#L92). /// </remarks> public const string ISO_2022_CN = "iso-2022-cn"; /// <summary> /// ISO 2022 Korean codepage name. /// </summary> /// <remarks> /// Are other aliases iso-2022-kr-7, iso-2022-kr-7bit, csiso2022kr in .NET /// </remarks> public const string ISO_2022_KR = "iso-2022-kr"; /// <summary> /// ISO 2022 Japanese codepage name. /// </summary> public const string ISO_2022_JP = "iso-2022-jp"; /// <summary> /// ISO 2022 Simplified Chinese codepage name. /// </summary> /// <remarks> /// Other alias is cp50227. /// </remarks> public const string X_CP50227 = "x-cp50227"; /// <summary> /// Big5 codepage name. /// </summary> /// <remarks> /// Are other aliases big5-hkscs, cn-big5, csbig5, x-x-big5 in .NET /// </remarks> public const string BIG5 = "big5"; /// <summary> /// GB18030 codepage name. /// </summary> public const string GB18030 = "gb18030"; /// <summary> /// HZ-GB2312 codepage name. /// </summary> public const string HZ_GB_2312 = "hz-gb-2312"; /// <summary> /// Shift-JIS codepage name. /// </summary> /// <remarks> /// Are other aliases shift_jis, sjis, csshiftjis, cswindows31j, ms_kanji, x-sjis in .NET /// </remarks> public const string SHIFT_JIS = "shift-jis"; /// <summary> /// ANSI/OEM Korean codepage name. /// </summary> /// <remarks> /// Are other aliases korean, ks-c-5601, ks-c5601, ks_c_5601, ks_c_5601-1989, ks_c_5601_1987, ksc5601, ksc_5601, iso-ir-149, csksc56011987 in .NET /// </remarks> public const string KS_C_5601_1987 = "ks_c_5601-1987"; /// <summary> /// CP949 codepage name. /// </summary> /// <remarks> /// Not supported in .NET. A nearly identical version of cp949 is ks_c_5601-1987 (see https://lists.w3.org/Archives/Public/ietf-charsets/2002JulSep/0020.html) /// </remarks> public const string CP949 = "cp949"; /// <summary> /// OEM Latin-2 codepage name. /// </summary> /// <remarks> /// Is other alias cp852 in .NET /// </remarks> public const string IBM852 = "ibm852"; /// <summary> /// OEM Cyrillic (primarily Russian) codepage name. /// </summary> /// <remarks> /// Is other alias cp855 in .NET /// </remarks> public const string IBM855 = "ibm855"; /// <summary> /// OEM Cyrillic (primarily Russian) codepage name. /// </summary> /// <remarks> /// Is other alias cp866 in .NET /// </remarks> public const string IBM866 = "ibm866"; /// <summary> /// ISO 8859-1 Latin-1 Western European codepage name. /// </summary> public const string ISO_8859_1 = "iso-8859-1"; /// <summary> /// ISO 8859-2 Central European (Latin 2 Eastern European) codepage name. /// </summary> /// <remarks> /// Are other aliases iso8859-2, iso_8859-2, iso_8859-2:1987, iso-ir-101, l2, latin2, csisolatin2 in .NET /// </remarks> public const string ISO_8859_2 = "iso-8859-2"; /// <summary> /// ISO 8859-3 Latin-3 (South European) codepage name. /// </summary> /// <remarks> /// Are other aliases iso_8859-3, iso_8859-3:1988, iso-ir-109, l3, latin3, csisolatin3 in .NET /// </remarks> public const string ISO_8859_3 = "iso-8859-3"; /// <summary> /// ISO 8859-4 Baltic (Latin-4 North European) codepage name. /// </summary> /// <remarks> /// Are other aliases iso_8859-4, iso_8859-4:1988, iso-ir-110, l4, latin4, csisolatin4 in .NET /// </remarks> public const string ISO_8859_4 = "iso-8859-4"; /// <summary> /// ISO 8859-5 Cyrillic codepage name. /// </summary> /// <remarks> /// Are other aliases iso_8859-5, iso_8859-5:1988, iso-ir-144, cyrillic, csisolatincyrillic in .NET /// </remarks> public const string ISO_8859_5 = "iso-8859-5"; /// <summary> /// ISO 8859-6 Arabic codepage name. /// </summary> /// <remarks> /// Are other aliases iso_8859-6, iso_8859-6:1987, iso-ir-127, arabic, csisolatinarabic, ecma-114 in .NET /// </remarks> public const string ISO_8859_6 = "iso-8859-6"; /// <summary> /// ISO 8859-7 Greek codepage name. /// </summary> /// <remarks> /// Are other aliases iso_8859-7, iso_8859-7:1987, iso-ir-126, greek, greek8, csisolatingreek, ecma-118, elot_928 in .NET /// </remarks> public const string ISO_8859_7 = "iso-8859-7"; /// <summary> /// ISO 8859-8 Hebrew codepage name. /// </summary> /// <remarks> /// Are other aliases iso_8859-8, iso_8859-8:1988, iso-8859-8 visual, iso-ir-138, hebrew, logical, visual, csisolatinhebrew in .NET /// </remarks> public const string ISO_8859_8 = "iso-8859-8"; /// <summary> /// ISO 8859-9 Latin-5 Turkish codepage name. /// </summary> /// <remarks> /// Is other alias iso-ir-148 in .NET /// </remarks> public const string ISO_8859_9 = "iso-8859-9"; /// <summary> /// ISO 8859-10 Latin-6 Nordic codepage name. /// </summary> /// <remarks> /// Not supported. /// </remarks> public const string ISO_8859_10 = "iso-8859-10"; /// <summary> /// ANSI/OEM Thai codepage name. /// </summary> /// <remarks> /// Are other aliases tis-620, windows-874, dos-874 in .NET /// </remarks> public const string ISO_8859_11 = "iso-8859-11"; /// <summary> /// ISO 8859-13 Estonian (Latin 7 BalticRim) codepage name. /// </summary> public const string ISO_8859_13 = "iso-8859-13"; /// <summary> /// ISO 8859-15 Latin-9 (Western European) codepage name. /// </summary> /// <remarks> /// Are other aliases iso_8859-15, l9, latin9, csisolatin9 in .NET /// </remarks> public const string ISO_8859_15 = "iso-8859-15"; /// <summary> /// ISO 8859-16 codepage name. /// </summary> /// <remarks> /// Not supported. /// </remarks> public const string ISO_8859_16 = "iso-8859-16"; /// <summary> /// ANSI Central European codepage name. /// </summary> /// <remarks> /// Is other alias x-cp1250 in .NET /// </remarks> public const string WINDOWS_1250 = "windows-1250"; /// <summary> /// ANSI Cyrillic codepage name. /// </summary> /// <remarks> /// Is other alias x-cp1251 in .NET /// </remarks> public const string WINDOWS_1251 = "windows-1251"; /// <summary> /// ANSI Latin-1 codepage name. /// </summary> /// <remarks> /// Is other alias x-ansi in .NET /// </remarks> public const string WINDOWS_1252 = "windows-1252"; /// <summary> /// ANSI Greek codepage name. /// </summary> public const string WINDOWS_1253 = "windows-1253"; /// <summary> /// ANSI Hebrew codepage name. /// </summary> public const string WINDOWS_1255 = "windows-1255"; /// <summary> /// ANSI Arabic codepage name. /// </summary> /// <remarks> /// Is other alias cp1256 in .NET /// </remarks> public const string WINDOWS_1256 = "windows-1256"; /// <summary> /// ANSI Baltic codepage name. /// </summary> public const string WINDOWS_1257 = "windows-1257"; /// <summary> /// ANSI/OEM Vietnamese codepage name. /// </summary> public const string WINDOWS_1258 = "windows-1258"; /// <summary> /// MAC Latin-2 codepage name. /// </summary> public const string X_MAC_CE = "x-mac-ce"; /// <summary> /// Cyrillic (Mac) codepage name. /// </summary> public const string X_MAC_CYRILLIC = "x-mac-cyrillic"; /// <summary> /// Cyrillic (KOI8-R) codepage name. /// </summary> /// <remarks> /// Are other aliases koi, koi8, koi8r, cskoi8r in .NET /// </remarks> public const string KOI8_R = "koi8-r"; /// <summary> /// TIS-620 codepage name. /// </summary> /// <remarks> /// A nearly identical version of TIS-620 is iso-8859-11. The sole difference being that iso-8859-11 defines hex A0 as a non-breaking space, while TIS-620 leaves it undefined but reserved. /// </remarks> public const string TIS_620 = "tis-620"; /// <summary> /// VISCII codepage name. /// </summary> /// <remarks> /// Not supported. It's an unofficially-defined modified ASCII character encoding for using the Vietnamese language with computers. /// See https://en.wikipedia.org/wiki/VISCII /// </remarks> public const string VISCII = "viscii"; /// <summary> /// X-ISO-10646-UCS-4-3412 codepage name. /// </summary> /// <remarks> /// Not supported? ISO 10646 and Unicode only include big-endian and little-endian UCS-4/UTF-32, not middle-endian. /// See https://stackoverflow.com/a/21896370 /// </remarks> public const string X_ISO_10646_UCS_4_3412 = "X-ISO-10646-UCS-4-3412"; /// <summary> /// X-ISO-10646-UCS-4-2143 codepage name. /// </summary> /// <remarks> /// Not supported? ISO 10646 and Unicode only include big-endian and little-endian UCS-4/UTF-32, not middle-endian. /// See https://stackoverflow.com/a/21896370 /// </remarks> public const string X_ISO_10646_UCS_4_2143 = "X-ISO-10646-UCS-4-2143"; }
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using System.ComponentModel; namespace InteractiveDataDisplay.WPF { /// <summary> /// A control to show information about size of drawing markers in a legend. /// </summary> [Description("Visually maps value to screen units")] public class SizeLegendControl : ContentControl { #region Fields private Canvas image; private Axis axis; #endregion #region Properties /// <summary> /// Gets or sets the range of axis values. /// Default value is [0, 1]. /// </summary> [Category("InteractiveDataDisplay")] [Description("Range of mapped values")] public Range Range { get { return (Range)GetValue(RangeProperty); } set { SetValue(RangeProperty, value); } } /// <summary> /// Gets or sets the filling color. /// Default value is black color. /// </summary> [Category("Appearance")] public Color Color { get { return (Color)GetValue(ColorProperty); } set { SetValue(ColorProperty, value); } } /// <summary> /// Gets or sets the maximum value of displaying height. /// Default value is 20. /// </summary> [Category("InteractiveDataDisplay")] [Description("Maximum screen height of palette")] public new double MaxHeight { get { return (double)GetValue(MaxHeightProperty); } set { SetValue(MaxHeightProperty, value); } } /// <summary> /// Gets or sets the value indicating whether an axis should be rendered or not. /// Default value is true. /// </summary> [Category("InteractiveDataDisplay")] public bool IsAxisVisible { get { return (bool)GetValue(IsAxisVisibleProperty); } set { SetValue(IsAxisVisibleProperty, value); } } /// <summary> /// Gets or sets the minimum of size to display in a legend. This is screen size that corresponds to minimum value of data. /// Default value is Double.NaN. /// </summary> [Category("InteractiveDataDisplay")] [Description("Screen size that corresponds to minimum value")] public double Min { get { return (double)GetValue(MinProperty); } set { SetValue(MinProperty, value); } } /// <summary> /// Gets or sets the maximum of size to display in a legend. This is screen size that corresponds to maximum value of data. /// Default value is Double.NaN. /// </summary> [Category("InteractiveDataDisplay")] [Description("Screen size that corresponds to maximum value")] public double Max { get { return (double)GetValue(MaxProperty); } set { SetValue(MaxProperty, value); } } #endregion #region Dependency properties /// <summary> /// Identifies the <see cref="Range"/> dependency property. /// </summary> public static readonly DependencyProperty RangeProperty = DependencyProperty.Register( "Range", typeof(Range), typeof(SizeLegendControl), new PropertyMetadata(new Range(0, 1), OnRangeChanged)); /// <summary> /// Identifies the <see cref="Color"/> dependency property. /// </summary> public static readonly DependencyProperty ColorProperty = DependencyProperty.Register( "Color", typeof(Color), typeof(SizeLegendControl), new PropertyMetadata(Colors.Black, OnColorChanged)); /// <summary> /// Identifies the <see cref="MaxHeight"/> dependency property. /// </summary> public static new readonly DependencyProperty MaxHeightProperty = DependencyProperty.Register( "MaxHeight", typeof(double), typeof(SizeLegendControl), new PropertyMetadata(20.0, OnMinMaxChanged)); /// <summary> /// Identifies the <see cref="IsAxisVisible"/> dependency property. /// </summary> public static readonly DependencyProperty IsAxisVisibleProperty = DependencyProperty.Register( "IsAxisVisible", typeof(bool), typeof(SizeLegendControl), new PropertyMetadata(true)); /// <summary> /// Identifies the <see cref="Min"/> dependency property. /// </summary> public static readonly DependencyProperty MinProperty = DependencyProperty.Register( "Min", typeof(double), typeof(SizeLegendControl), new PropertyMetadata(Double.NaN, OnMinMaxChanged)); /// <summary> /// Identifies the <see cref="Max"/> dependency property. /// </summary> public static readonly DependencyProperty MaxProperty = DependencyProperty.Register( "Max", typeof(double), typeof(SizeLegendControl), new PropertyMetadata(Double.NaN, OnMinMaxChanged)); #endregion #region ctor /// <summary> /// Initializes a new instance of the <see cref="SizeLegendControl"/> class. /// </summary> public SizeLegendControl() { StackPanel stackPanel = new StackPanel(); image = new Canvas { HorizontalAlignment = HorizontalAlignment.Stretch }; axis = new Axis { AxisOrientation = AxisOrientation.Bottom, HorizontalAlignment = HorizontalAlignment.Stretch }; stackPanel.Children.Add(image); stackPanel.Children.Add(axis); Content = stackPanel; SizeChanged += (o, e) => { if (e.PreviousSize.Width == 0 || e.PreviousSize.Height == 0 || Double.IsNaN(e.PreviousSize.Width) || Double.IsNaN(e.PreviousSize.Height)) UpdateCanvas(); }; IsTabStop = false; } #endregion #region Private methods private void UpdateCanvas() { if (Width == 0 || Double.IsNaN(Width)) return; image.Children.Clear(); double maxHeight = Double.IsNaN(Max) ? Range.Max : Max; double minHeight = Double.IsNaN(Min) ? Range.Min : Min; double visHeight = Math.Min(maxHeight, MaxHeight); image.Width = Width; axis.Width = Width; image.Height = visHeight; PathFigure pathFigure = new PathFigure(); pathFigure.StartPoint = new Point(0, maxHeight); LineSegment lineSegment1 = new LineSegment(); lineSegment1.Point = new Point(Width, maxHeight); LineSegment lineSegment2 = new LineSegment(); lineSegment2.Point = new Point(Width, 0); LineSegment lineSegment3 = new LineSegment(); lineSegment3.Point = new Point(0, maxHeight - minHeight); LineSegment lineSegment4 = new LineSegment(); lineSegment4.Point = new Point(0, maxHeight); PathSegmentCollection pathSegmentCollection = new PathSegmentCollection(); pathSegmentCollection.Add(lineSegment1); pathSegmentCollection.Add(lineSegment2); pathSegmentCollection.Add(lineSegment3); pathSegmentCollection.Add(lineSegment4); pathFigure.Segments = pathSegmentCollection; PathFigureCollection pathFigureCollection = new PathFigureCollection(); pathFigureCollection.Add(pathFigure); PathGeometry pathGeometry = new PathGeometry(); pathGeometry.Figures = pathFigureCollection; Path path = new Path(); // TODO: Make it dependency property of SizeControl path.Fill = new SolidColorBrush(Colors.LightGray); path.Data = pathGeometry; path.Stroke = new SolidColorBrush(Color); if (!Double.IsNaN(MaxHeight)) { RectangleGeometry clip = new RectangleGeometry(); clip.Rect = new Rect(0, maxHeight - this.MaxHeight, Width, this.MaxHeight); path.Clip = clip; } Canvas.SetTop(path, image.Height - maxHeight); image.Children.Add(path); if (visHeight < maxHeight) { Line top; if (minHeight >= visHeight) top = new Line { X1 = 0, Y1 = 0, X2 = Width, Y2 = 0 }; else top = new Line { X1 = Width * (visHeight - minHeight) / (maxHeight - minHeight), Y1 = 0, X2 = Width, Y2 = 0 }; top.Stroke = new SolidColorBrush(Colors.Black); top.StrokeDashArray = new DoubleCollection(); top.StrokeDashArray.Add(5); top.StrokeDashArray.Add(5); image.Children.Add(top); } } private static void OnRangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SizeLegendControl control = (SizeLegendControl)d; control.OnRangeChanged(); } private void OnRangeChanged() { axis.Range = Range; UpdateCanvas(); } private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SizeLegendControl control = (SizeLegendControl)d; control.OnColorChanged(); } private void OnColorChanged() { if (image.Children.Count > 0) ((Path)image.Children[0]).Fill = new SolidColorBrush(Color); } private static void OnMinMaxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SizeLegendControl control = (SizeLegendControl)d; control.UpdateCanvas(); } #endregion } }
using System; using System.Web; using System.Web.Caching; using System.IO; using System.Text; using System.Collections.Generic; using System.Reflection; using Nohros; using Nohros.Data; using Nohros.Configuration; using Nohros.Logging; namespace Nohros.Net { /// <summary> /// This handler is used to handle files with the pattern "*.[CONTENT-GROUP-NAME].nohrosnet.[js|css|...] /// The [CONTENT-GROUP-NAME] part of the requested file name must be a name of a content group /// defined into the application configuration file for the requested HTTP content-type. /// </summary> public class MergeHttpHandler : IHttpHandler { #region FileCacheItem class /// <summary> /// A cached version of the merged content group. /// </summary> internal class FileCacheItem { public string Content; public DateTime DateEntered = DateTime.Now; public FileCacheItem(string content) { Content = content; } } #endregion const int kResourceNotFoundCode = 404; const string kVirtualFilePathSuffix = ".nohrosnet."; const string kVirtualFilePathExtension = ".ashx"; const string kKeyPrefix = "merger-"; #if DEBUG const string kBuildVersion = "release"; #else const string kBuildVersion = "debug"; #endif HttpContext context_; NohrosConfiguration settings_; private FileCacheItem UpdateFileCache(ContentGroupNode content_group, string cache_key) { CacheDependency cd; StringBuilder merged = new StringBuilder(); List<string> merged_files = new List<string>(content_group.Files.Count); // the embedded resource must be readed from the resource assembly. Assembly assembly = Assembly.GetExecutingAssembly(); foreach (string file_name in content_group.Files) { string file_path = Path.Combine(content_group.BasePath, file_name); // sanity check file existence if (File.Exists(file_path)) { using (StreamReader stream = new StreamReader(file_path)) { string content = stream.ReadToEnd().Trim(); if (content.Length > 0) { merged.Append(content).Append("\r\n"); merged_files.Add(file_path); } stream.Close(); } } } if (merged.Length > 0) { FileCacheItem ci = new FileCacheItem(merged.ToString()); // add the the application configuration file to the CacheDependency merged_files.Add(Utility.BaseDirectory + "web.config"); cd = new CacheDependency(merged_files.ToArray()); // Store the FileCacheItem in cache w/ a dependency on the merged files changing context_.Cache.Insert(cache_key, ci, cd); return ci; } return null; } /// <summary> /// Merges a collection of files into a single one and output its content to the requestor. /// </summary> /// <param name="files_to_merge">The files</param> /// <param name="content_group_name">The name of the content group.</param> /// <param name="content_type">The MIME type of content that will be merged.</param> void GetMergedContent(string content_group_name, string mime_type) { string modified_since = context_.Request.Headers["If-Modified-Since"]; string cache_key = string.Concat(kKeyPrefix, content_group_name, ".", mime_type, ".", kBuildVersion); // check if this group is defined ContentGroupNode content_group = settings_.WebNode.GetContentGroup(content_group_name, kBuildVersion, mime_type); if (content_group == null) { context_.Response.StatusCode = kResourceNotFoundCode; context_.Response.End(); return; } // attempt to retrieve the merged content from the cache FileCacheItem cached_file = (FileCacheItem)context_.Cache[cache_key]; if (cached_file != null) { if (modified_since != null) { DateTime last_client_update; DateTime.TryParseExact(context_.Request.Headers["If-Modified-Since"], "yyyyMMdd HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out last_client_update); if (cached_file.DateEntered <= last_client_update) { // don't do anything, nothing has changed since last request. context_.Response.StatusCode = 304; context_.Response.StatusDescription = "Not Modified"; context_.Response.End(); return; } } else { // In the event that the browser does not automatically have this header, add it context_.Response.AddHeader("If-Modified-Since", cached_file.DateEntered.ToString("yyyyMMdd HH:mm:ss")); } } else { // cache item not found, update cache cached_file = UpdateFileCache(content_group, cache_key); if (cached_file == null) { // the files to merge are not found FileLogger.ForCurrentProcess.Logger.Error("[GetMergedContent Nohros.Net.MergeHttpHandler] The files to merge are not found."); context_.Response.StatusCode = kResourceNotFoundCode; context_.Response.End(); } } context_.Response.Cache.SetLastModified(cached_file.DateEntered); context_.Response.ContentType = mime_type; context_.Response.Write(cached_file.Content); context_.Response.End(); } #region IHttpHandler /// <summary> /// Process the HTTP request. /// </summary> /// <param name="context">An HttpContext object that provides references to the intrinsic server objects /// used to service HTTP request</param> public void ProcessRequest(HttpContext context) { string content_type; string content_group_name; string requested_file_path; string requested_file_extentsion; int position; context_ = context; content_type = "text/html"; try { settings_ = NohrosConfiguration.DefaultConfiguration; } catch (System.Configuration.ConfigurationErrorsException exception) { FileLogger.ForCurrentProcess.Logger.Error("[GetMergedContent Nohros.Net.MergeHttpHandler]", exception); // the configuration file was not defined. we cant do nothing. context.Response.StatusCode = kResourceNotFoundCode; context.Response.End(); return; } requested_file_path = context.Request.FilePath; // attempt to get the content type from the requested file estension requested_file_extentsion = Path.GetExtension(requested_file_path); switch (requested_file_extentsion) { case ".js": content_type = "application/x-javascript"; break; case ".css": content_type = "text/css"; break; default: context.Response.StatusCode = kResourceNotFoundCode; context.Response.End(); break; } // attempt to get the content group name from the virtual path. position = requested_file_path.IndexOf(kVirtualFilePathSuffix); if(position == -1) { // the handler is configured incorrectly. FileLogger.ForCurrentProcess.Logger.Error("[ProcessRequest Nohros.Net.MergeHttpHandler] The handler is configured incorrectly. Check handlers session of the the web.config file"); context_.Response.StatusCode = kResourceNotFoundCode; context_.Response.End(); return; } content_group_name = Path.GetFileNameWithoutExtension( requested_file_path.Substring(0, position)); GetMergedContent(content_group_name, content_type); } /// <summary> /// Gets a value indicating whether another request can use the <see cref="IHttpHandler"/> instance_. /// <remarks> /// Our <see cref="IHttpHandler"/> implementation doesn't do expensive initializations. So, the /// value returned by this property doesn't really matter(since simple object allocation is fairly inexpensive). /// </remarks> /// </summary> public bool IsReusable { get { return false; } } #endregion } }
namespace Nancy.ViewEngines.DotLiquid.Tests { using System.IO; using System.Collections.Generic; using FakeItEasy; using global::DotLiquid; using global::DotLiquid.Exceptions; using Nancy.Tests; using Xunit; using Xunit.Extensions; public class LiquidNancyFileSystemFixture { [Fact] public void Should_locate_template_with_single_quoted_name() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, "'views/partial'"); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_locate_template_with_double_quoted_name() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, @"""views/partial"""); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_locate_template_with_unquoted_name() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, "views/partial"); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_not_locate_templates_that_does_not_have_liquid_extension() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "cshtml", () => null)); // When var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, "views/partial")); // Then exception.ShouldBeOfType<FileSystemException>(); } [Theory] [InlineData("partial")] [InlineData("paRTial")] [InlineData("PARTIAL")] public void Should_ignore_casing_of_template_name(string templateName) { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, string.Concat("views/", templateName)); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_support_locating_template_when_template_name_contains_liquid_extension() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, "views/partial.liquid"); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_support_locating_template_when_template_name_does_not_contains_liquid_extension() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, "views/partial"); // Then result.ShouldEqual("The correct view"); } [Theory] [InlineData("liquid")] [InlineData("liqUID")] [InlineData("LIQUID")] public void Should_ignore_extension_casing_when_template_name_contains_liquid_extension(string extension) { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, string.Concat("views/partial.", extension)); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_not_locate_view_when_template_location_not_specified() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult("views", "partial", "liquid", () => null)); // When var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, "partial")); // Then exception.ShouldBeOfType<FileSystemException>(); } [Theory] [InlineData("views", "Located in views/")] [InlineData("views/shared", "Located in views/shared")] public void Should_locate_templates_with_correct_location_specified(string location, string expectedResult) { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult(location, "partial", "liquid", () => new StringReader(expectedResult))); // When var result = fileSystem.ReadTemplateFile(context, string.Concat(location, "/partial")); // Then result.ShouldEqual(expectedResult); } [Theory] [InlineData("views")] [InlineData("viEws")] [InlineData("VIEWS")] public void Should_ignore_case_of_location_when_locating_template(string location) { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult(location, "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, string.Concat(location, "/partial")); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_support_backslashes_as_location_seperator() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult(@"views/shared", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, @"views\shared\partial"); // Then result.ShouldEqual("The correct view"); } [Fact] public void Should_support_forward_slashes_as_location_seperator() { // Given Context context; var fileSystem = CreateFileSystem(out context, new ViewLocationResult(@"views/shared", "partial", "liquid", () => new StringReader("The correct view"))); // When var result = fileSystem.ReadTemplateFile(context, @"views/shared/partial"); // Then result.ShouldEqual("The correct view"); } private LiquidNancyFileSystem CreateFileSystem(out Context context, params ViewLocationResult[] viewLocationResults) { var viewLocationProvider = A.Fake<IViewLocationProvider>(); A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._)) .Returns(viewLocationResults); var viewEngine = A.Fake<IViewEngine>(); A.CallTo(() => viewEngine.Extensions).Returns(new[] { "liquid" }); var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }); var startupContext = new ViewEngineStartupContext( null, viewLocator); var renderContext = A.Fake<IRenderContext>(); A.CallTo(() => renderContext.LocateView(A<string>.Ignored, A<object>.Ignored)) .ReturnsLazily(x => viewLocator.LocateView(x.Arguments.Get<string>(0), null)); context = new Context(new List<Hash>(), new Hash(), Hash.FromAnonymousObject(new { nancy = renderContext }), false); return new LiquidNancyFileSystem(startupContext, new[] { "liquid" }); } } }
//----------------------------------------------------------------------- // <copyright file="NetworkManagerUIController.cs" company="Google LLC"> // // Copyright 2018 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.CloudAnchors { using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Networking.Match; using UnityEngine.Networking.Types; using UnityEngine.SceneManagement; using UnityEngine.UI; /// <summary> /// Controller managing UI for joining and creating rooms. /// </summary> #pragma warning disable 618 [RequireComponent(typeof(CloudAnchorsNetworkManager))] #pragma warning restore 618 public class NetworkManagerUIController : MonoBehaviour { /// <summary> /// The snackbar text. /// </summary> public Text SnackbarText; /// <summary> /// The Label showing the current active room. /// </summary> public GameObject CurrentRoomLabel; /// <summary> /// The return to lobby button in AR Scene. /// </summary> public GameObject ReturnButton; /// <summary> /// The Cloud Anchors Example Controller. /// </summary> public CloudAnchorsExampleController CloudAnchorsExampleController; /// <summary> /// The Panel containing the list of available rooms to join. /// </summary> public GameObject RoomListPanel; /// <summary> /// Text indicating that no previous rooms exist. /// </summary> public Text NoPreviousRoomsText; /// <summary> /// The prefab for a row in the available rooms list. /// </summary> public GameObject JoinRoomListRowPrefab; /// <summary> /// The number of matches that will be shown. /// </summary> private const int k_MatchPageSize = 5; /// <summary> /// The Network Manager. /// </summary> #pragma warning disable 618 private CloudAnchorsNetworkManager m_Manager; #pragma warning restore 618 /// <summary> /// The current room number. /// </summary> private string m_CurrentRoomNumber; /// <summary> /// The Join Room buttons. /// </summary> private List<GameObject> m_JoinRoomButtonsPool = new List<GameObject>(); /// <summary> /// The Unity Awake() method. /// </summary> public void Awake() { // Initialize the pool of Join Room buttons. for (int i = 0; i < k_MatchPageSize; i++) { GameObject button = Instantiate(JoinRoomListRowPrefab); button.transform.SetParent(RoomListPanel.transform, false); button.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -(100 * i)); button.SetActive(true); button.GetComponentInChildren<Text>().text = string.Empty; m_JoinRoomButtonsPool.Add(button); } #pragma warning disable 618 m_Manager = GetComponent<CloudAnchorsNetworkManager>(); #pragma warning restore 618 m_Manager.StartMatchMaker(); m_Manager.matchMaker.ListMatches( startPageNumber: 0, resultPageSize: k_MatchPageSize, matchNameFilter: string.Empty, filterOutPrivateMatchesFromResults: false, eloScoreTarget: 0, requestDomain: 0, callback: _OnMatchList); _ChangeLobbyUIVisibility(true); } /// <summary> /// Handles the user intent to create a new room. /// </summary> public void OnCreateRoomClicked() { m_Manager.matchMaker.CreateMatch(m_Manager.matchName, m_Manager.matchSize, true, string.Empty, string.Empty, string.Empty, 0, 0, _OnMatchCreate); } /// <summary> /// Handles a user intent to return to the lobby. /// </summary> public void OnReturnToLobbyClick() { ReturnButton.GetComponent<Button>().interactable = false; if (m_Manager.matchInfo == null) { _OnMatchDropped(true, null); return; } m_Manager.matchMaker.DropConnection(m_Manager.matchInfo.networkId, m_Manager.matchInfo.nodeId, m_Manager.matchInfo.domain, _OnMatchDropped); } /// <summary> /// Handles the user intent to refresh the room list. /// </summary> public void OnRefhreshRoomListClicked() { m_Manager.matchMaker.ListMatches( startPageNumber: 0, resultPageSize: k_MatchPageSize, matchNameFilter: string.Empty, filterOutPrivateMatchesFromResults: false, eloScoreTarget: 0, requestDomain: 0, callback: _OnMatchList); } /// <summary> /// Callback indicating that the Cloud Anchor was instantiated and the host request was /// made. /// </summary> /// <param name="isHost">Indicates whether this player is the host.</param> public void OnAnchorInstantiated(bool isHost) { if (isHost) { SnackbarText.text = "Hosting Cloud Anchor..."; } else { SnackbarText.text = "Cloud Anchor added to session! Attempting to resolve anchor..."; } } /// <summary> /// Callback indicating that the Cloud Anchor was hosted. /// </summary> /// <param name="success">If set to <c>true</c> indicates the Cloud Anchor was hosted /// successfully.</param> /// <param name="response">The response string received.</param> public void OnAnchorHosted(bool success, string response) { if (success) { SnackbarText.text = "Cloud Anchor successfully hosted! Tap to place more stars."; } else { SnackbarText.text = "Cloud Anchor could not be hosted. " + response; } } /// <summary> /// Callback indicating that the Cloud Anchor was resolved. /// </summary> /// <param name="success">If set to <c>true</c> indicates the Cloud Anchor was resolved /// successfully.</param> /// <param name="response">The response string received.</param> public void OnAnchorResolved(bool success, string response) { if (success) { SnackbarText.text = "Cloud Anchor successfully resolved! Tap to place more stars."; } else { SnackbarText.text = "Cloud Anchor could not be resolved. Will attempt again. " + response; } } /// <summary> /// Use the snackbar to display the error message. /// </summary> /// <param name="debugMessage">The debug message to be displayed on the snackbar.</param> public void ShowDebugMessage(string debugMessage) { SnackbarText.text = debugMessage; } /// <summary> /// Handles the user intent to join the room associated with the button clicked. /// </summary> /// <param name="match">The information about the match that the user intents to /// join.</param> #pragma warning disable 618 private void _OnJoinRoomClicked(MatchInfoSnapshot match) #pragma warning restore 618 { m_Manager.matchName = match.name; m_Manager.matchMaker.JoinMatch(match.networkId, string.Empty, string.Empty, string.Empty, 0, 0, _OnMatchJoined); } /// <summary> /// Callback that happens when a <see cref="NetworkMatch.ListMatches"/> request has been /// processed on the server. /// </summary> /// <param name="success">Indicates if the request succeeded.</param> /// <param name="extendedInfo">A text description for the error if success is false.</param> /// <param name="matches">A list of matches corresponding to the filters set in the initial /// list request.</param> #pragma warning disable 618 private void _OnMatchList( bool success, string extendedInfo, List<MatchInfoSnapshot> matches) #pragma warning restore 618 { if (!success) { SnackbarText.text = "Could not list matches: " + extendedInfo; return; } m_Manager.OnMatchList(success, extendedInfo, matches); if (m_Manager.matches != null) { // Reset all buttons in the pool. foreach (GameObject button in m_JoinRoomButtonsPool) { button.SetActive(false); button.GetComponentInChildren<Button>().onClick.RemoveAllListeners(); button.GetComponentInChildren<Text>().text = string.Empty; } NoPreviousRoomsText.gameObject.SetActive(m_Manager.matches.Count == 0); // Add buttons for each existing match. int i = 0; #pragma warning disable 618 foreach (var match in m_Manager.matches) #pragma warning restore 618 { if (i >= k_MatchPageSize) { break; } var text = "Room " + _GetRoomNumberFromNetworkId(match.networkId); GameObject button = m_JoinRoomButtonsPool[i++]; button.GetComponentInChildren<Text>().text = text; button.GetComponentInChildren<Button>().onClick.AddListener(() => _OnJoinRoomClicked(match)); button.GetComponentInChildren<Button>().onClick.AddListener( CloudAnchorsExampleController.OnEnterResolvingModeClick); button.SetActive(true); } } } /// <summary> /// Callback that happens when a <see cref="NetworkMatch.CreateMatch"/> request has been /// processed on the server. /// </summary> /// <param name="success">Indicates if the request succeeded.</param> /// <param name="extendedInfo">A text description for the error if success is false.</param> /// <param name="matchInfo">The information about the newly created match.</param> #pragma warning disable 618 private void _OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) #pragma warning restore 618 { if (!success) { SnackbarText.text = "Could not create match: " + extendedInfo; return; } m_Manager.OnMatchCreate(success, extendedInfo, matchInfo); m_CurrentRoomNumber = _GetRoomNumberFromNetworkId(matchInfo.networkId); SnackbarText.text = "Connecting to server..."; _ChangeLobbyUIVisibility(false); CurrentRoomLabel.GetComponentInChildren<Text>().text = "Room: " + m_CurrentRoomNumber; } /// <summary> /// Callback that happens when a <see cref="NetworkMatch.JoinMatch"/> request has been /// processed on the server. /// </summary> /// <param name="success">Indicates if the request succeeded.</param> /// <param name="extendedInfo">A text description for the error if success is false.</param> /// <param name="matchInfo">The info for the newly joined match.</param> #pragma warning disable 618 private void _OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo) #pragma warning restore 618 { if (!success) { SnackbarText.text = "Could not join to match: " + extendedInfo; return; } m_Manager.OnMatchJoined(success, extendedInfo, matchInfo); m_CurrentRoomNumber = _GetRoomNumberFromNetworkId(matchInfo.networkId); SnackbarText.text = "Connecting to server..."; _ChangeLobbyUIVisibility(false); CurrentRoomLabel.GetComponentInChildren<Text>().text = "Room: " + m_CurrentRoomNumber; } /// <summary> /// Callback that happens when a <see cref="NetworkMatch.DropConnection"/> request has been /// processed on the server. /// </summary> /// <param name="success">Indicates if the request succeeded.</param> /// <param name="extendedInfo">A text description for the error if success is false. /// </param> private void _OnMatchDropped(bool success, string extendedInfo) { ReturnButton.GetComponent<Button>().interactable = true; if (!success) { SnackbarText.text = "Could not drop the match: " + extendedInfo; return; } m_Manager.OnDropConnection(success, extendedInfo); #pragma warning disable 618 NetworkManager.Shutdown(); #pragma warning restore 618 SceneManager.LoadScene("CloudAnchors"); } /// <summary> /// Changes the lobby UI Visibility by showing or hiding the buttons. /// </summary> /// <param name="visible">If set to <c>true</c> the lobby UI will be visible. It will be /// hidden otherwise.</param> private void _ChangeLobbyUIVisibility(bool visible) { foreach (GameObject button in m_JoinRoomButtonsPool) { bool active = visible && button.GetComponentInChildren<Text>().text != string.Empty; button.SetActive(active); } CloudAnchorsExampleController.OnLobbyVisibilityChanged(visible); } private string _GetRoomNumberFromNetworkId(NetworkID networkID) { return (System.Convert.ToInt64(networkID.ToString()) % 10000).ToString(); } } }
/* * 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 log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class GridUserServicesConnector : IGridUserService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public GridUserServicesConnector() { } public GridUserServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public GridUserServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["GridUserService"]; if (gridConfig == null) { m_log.Error("[GRID USER CONNECTOR]: GridUserService missing from OpenSim.ini"); throw new Exception("GridUser connector init error"); } string serviceURI = gridConfig.GetString("GridUserServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[GRID USER CONNECTOR]: No Server URI named in section GridUserService"); throw new Exception("GridUser connector init error"); } m_ServerURI = serviceURI; } #region IGridUserService public GridUserInfo LoggedIn(string userID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "loggedin"; sendData["UserID"] = userID; return Get(sendData); } public bool LoggedOut(string userID, UUID region, Vector3 position, Vector3 lookat) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "loggedout"; return Set(sendData, userID, region, position, lookat); } public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "sethome"; return Set(sendData, userID, regionID, position, lookAt); } public bool SetLastPosition(string userID, UUID regionID, Vector3 position, Vector3 lookAt) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "setposition"; return Set(sendData, userID, regionID, position, lookAt); } public GridUserInfo GetGridUserInfo(string userID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getgriduserinfo"; sendData["UserID"] = userID; return Get(sendData); } #endregion protected bool Set(Dictionary<string, object> sendData, string userID, UUID regionID, Vector3 position, Vector3 lookAt) { sendData["UserID"] = userID; sendData["RegionID"] = regionID.ToString(); sendData["Position"] = position.ToString(); sendData["LookAt"] = lookAt.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/griduser", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition reply data does not contain result field"); } else m_log.DebugFormat("[GRID USER CONNECTOR]: SetPosition received empty reply"); } catch (Exception e) { m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server: {0}", e.Message); } return false; } protected GridUserInfo Get(Dictionary<string, object> sendData) { string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[GRID USER CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/griduser", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); GridUserInfo guinfo = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) { guinfo = new GridUserInfo((Dictionary<string, object>)replyData["result"]); } } return guinfo; } else m_log.DebugFormat("[GRID USER CONNECTOR]: Loggedin received empty reply"); } catch (Exception e) { m_log.DebugFormat("[GRID USER CONNECTOR]: Exception when contacting grid user server: {0}", e.Message); } return null; } } }
using System; using System.Drawing; using System.IO; using bv.common.Core; using bv.common.Diagnostics; namespace bv.common.Configuration { public class SettingName { public const string ShowWarningForFinalCaseClassification = "ShowWarningForFinalCaseClassification"; public const string FilterSamplesByDiagnosis = "FilterSamplesByDiagnosis"; public const string WebAvrDataLifeTime = "WebAvrDataLifeTime"; public const string WebAvrDataCheckInterval = "WebAvrDataCheckInterval"; } public class BaseSettings { //private const int DefaultSqlTimeout = 200; //Possible values: Default, ClientID, User private static string m_SystemFontName; private static string m_GGSystemFontName = ""; private static string m_THSystemFontName = ""; private static string m_THReportsFontName = ""; private static float m_SystemFontSize; private static float m_GGSystemFontSize; private static float m_THSystemFontSize; private static float m_THReportsDeltaFontSize = -1; public const string Asterisk = "*"; public static bool DebugOutput { get { return Config.GetBoolSetting("DebugOutput", true); } } public static string DebugLogFile { get { return Config.GetSetting("DebugLogFile", null); } } public static bool TranslationMode { get { return Config.GetBoolSetting("TranslationMode"); } } public static bool ShowCBT { get { return Config.GetBoolSetting("ShowCBT"); } } public static int DebugDetailLevel { get { int level; if (Int32.TryParse(Config.GetSetting("DebugDetailLevel", "0"), out level)) { return level; } return 0; } } public static string ObjectsSchemaPath { get { string path = Config.GetSetting("SchemaPath", "..\\..\\Schema") + "\\Objects\\"; Dbg.Assert(Directory.Exists(path), "objects schema path <{0}> doesn\'t exists", path); return path; } } public static string ConnectionString { get { return Config.GetSetting("SQLConnectionString", "Persist Security Info=False;User ID={0};Password={1};Initial Catalog={2};Data Source={3};Asynchronous Processing=True;"); } } public static int SqlCommandTimeout { get { return Config.GetIntSetting("SqlCommandTimeout", 200); } } public static bool UseDefaultLogin { get { return Config.GetBoolSetting("UseDefaultLogin"); } } public static string DefaultOrganization { get { return Config.GetSetting("DefaultOrganization", null); } } public static string DefaultUser { get { return Config.GetSetting("DefaultUser", null); } } public static string DefaultPassword { get { return Config.GetSetting("DefaultPassword", null); } } public static string SqlServer { get { return Config.GetSetting("SQLServer", "(local)"); } } public static string SqlDatabase { get { return Config.GetSetting("SQLDatabase", "eidss"); } } public static string SqlUser { get { return Config.GetSetting("SQLUser", null); } } public static string SqlPassword { get { return Config.GetSetting("SQLPassword", null); } } public static string InplaceShowDropDown { get { return Config.GetSetting("InplaceShowDropDown", null); } } public static string ShowDropDown { get { return Config.GetSetting("ShowDropDown", null); } } public static int LookupCacheRefreshInterval { get { return Config.GetIntSetting("LookupCacheRefreshInterval", 500); } } public static int LookupCacheIdleRefreshInterval { get { return Config.GetIntSetting("LookupCacheIdleRefreshInterval", 500); } } public static bool ForceMemoryFlush { get { return Config.GetBoolSetting("ForceMemoryFlush", true); } } public static bool ForceFormsDisposing { get { return Config.GetBoolSetting("ForceFormsDisposing", true); } } public static int PagerPageSize { get { return Config.GetIntSetting("PagerPageSize", 50); } } public static int WebBarcodePageWidth { get { return Config.GetIntSetting("WebBarcodePageWidth", 150); } } public static int WebBarcodePageHeight { get { return Config.GetIntSetting("WebBarcodePageHeight", 50); } } public static int PagerPageCount { get { return Config.GetIntSetting("PagerPageCount", 10); } } public static bool DontStartClient { get { return Config.GetBoolSetting("DontStartClient"); } } public static int ConnectionSource { get { return Config.GetIntSetting("ConnectionSource", 0); } } public static int TcpPort { get { return Config.GetIntSetting("TcpPort", 4005); } } public static string SystemFontName { get { if (Utils.Str(m_SystemFontName) == "") { m_SystemFontName = Config.GetSetting("SystemFontName", FontFamily.GenericSansSerif.Name); } return m_SystemFontName; } } public static string GGSystemFontName { get { if (Utils.Str(m_GGSystemFontName) == "") { m_GGSystemFontName = Config.GetSetting("GeorgianSystemFontName", "Sylfaen"); } return m_GGSystemFontName; } } public static float SystemFontSize { get { if (m_SystemFontSize < 1) { string fontSizeStr = Config.GetSetting("SystemFontSize", null); if (fontSizeStr != null) { Single.TryParse(fontSizeStr, out m_SystemFontSize); } } if (m_SystemFontSize < 1) { m_SystemFontSize = (float) (8.25); } return m_SystemFontSize; } } public static float GGSystemFontSize { get { if (m_GGSystemFontSize < 1) { string fontSizeStr = Config.GetSetting("GeorgianSystemFontSize", null); if (fontSizeStr != null) { Single.TryParse(fontSizeStr, out m_GGSystemFontSize); } } if (m_GGSystemFontSize < 1) { m_GGSystemFontSize = (float) (8.25); } return m_GGSystemFontSize; } } public static string THReportsFontName { get { if (Utils.Str(m_THReportsFontName) == "") { m_THReportsFontName = Config.GetSetting("ThaiReportsFontName"); } if (Utils.Str(m_THReportsFontName) == "") { m_THReportsFontName = THSystemFontName; } return m_THReportsFontName; } } public static float THReportsDeltaFontSize { get { if (m_THReportsDeltaFontSize < 0) { string fontSizeStr = Config.GetSetting("ThaiReportsDeltaFontSize", null); if (fontSizeStr != null) { Single.TryParse(fontSizeStr, out m_THReportsDeltaFontSize); } } if (m_THReportsDeltaFontSize < 0) { m_THReportsDeltaFontSize = 2; } return m_THReportsDeltaFontSize; } } public static string THSystemFontName { get { if (Utils.Str(m_THSystemFontName) == "") { m_THSystemFontName = Config.GetSetting("ThaiSystemFontName"); } if (Utils.Str(m_THSystemFontName) == "") { m_THSystemFontName = SystemFontName; } return m_THSystemFontName; } } public static float THSystemFontSize { get { if (m_THSystemFontSize < 1) { string fontSizeStr = Config.GetSetting("ThaiSystemFontSize", null); if (fontSizeStr != null) { Single.TryParse(fontSizeStr, out m_THSystemFontSize); } } if (m_THSystemFontSize < 1) { m_THSystemFontSize = (float) (8.25); } return m_THSystemFontSize; } } public static string DefaultLanguage { get { return Config.GetSetting("DefaultLanguage", "en"); } } public static string BarcodePrinter { get { return Config.GetSetting("BarcodePrinter", null); } } public static string DocumentPrinter { get { return Config.GetSetting("DocumentPrinter", null); } } public static int LookupCacheTimeout { get { return Config.GetIntSetting("LookupTimeout", 300); } } public static bool IgnoreAbsentResources { get { return Config.GetBoolSetting("IgnoreAbsentResources"); } } public static bool ShowClearLookupButton { get { return Config.GetBoolSetting("ShowClearLookupButton", true); } } public static bool ShowClearRepositoryLookupButton { get { return Config.GetBoolSetting("ShowClearRepositoryLookupButton"); } } public static string DetailFormType { get { return Config.GetSetting("DetailFormType", "Normal"); } } public static bool ShowDeleteButtonOnDetailForm { get { return Config.GetBoolSetting("ShowDeleteButtonOnDetailForm"); } } public static bool ShowSaveButtonOnDetailForm { get { return Config.GetBoolSetting("ShowSaveButtonOnDetailForm"); } } public static bool ShowNewButtonOnDetailForm { get { return Config.GetBoolSetting("ShowNewButtonOnDetailForm"); } } public static bool DirectDataAccess { get { return Config.GetBoolSetting("DirectDataAccess", true); } } public static string OneInstanceMethod { get { return Config.GetSetting("OneInstanceMethod"); } } public static bool ShowCaptionOnToolbar { get { return Config.GetBoolSetting("ShowCaptionOnToolbar"); } } public static bool ShowEmptyListOnSearch { get { return Config.GetBoolSetting("ShowEmptyListOnSearch", true); } } public static bool ShowAvrAsterisk { get { return Config.GetBoolSetting("ShowAvrAsterisk", true); } } public static bool ShowBigLayoutWarning { get { return Config.GetBoolSetting("ShowBigLayoutWarning"); } } public static int AvrWarningMemoryLimit { get { return Config.GetIntSetting("AvrWarningMemoryLimit", 2048); } } public static int AvrErrorMemoryLimit { get { return Math.Max(AvrWarningMemoryLimit, Config.GetIntSetting("AvrErrorMemoryLimit", 4096)); } } public static int AvrWarningCellCountLimit { get { return Config.GetIntSetting("AvrWarningCellCountLimit", 1000000); } } public static int AvrErrorCellCountLimit { get { return Config.GetIntSetting("AvrErrorCellCountLimit", 2000000); } } public static int AvrWarningLayoutComplexity { get { return Config.GetIntSetting("AvrWarningLayoutComplexity", 60); } } public static int AvrErrorLayoutComplexity { get { return Config.GetIntSetting("AvrErrorLayoutComplexity", 180); } } public static string AvrExportUtilX86 { get { return Config.GetSetting("AvrExportUtilX86", "eidss.avr.export.x86.exe"); } } public static string AvrExportUtilX64 { get { return Config.GetSetting("AvrExportUtilX64", "eidss.avr.export.x64.exe"); } } public static string AvrServiceHostURL { get { return Config.GetSetting("AVRServiceHostURL", "http://localhost:8071/"); } } public static string ReportServiceHostURL { get { return Config.GetSetting("ReportServiceHostURL", "http://localhost:8097/"); } } public static int AvrRowsPerPage { get { return Config.GetIntSetting("AvrRowsPerPage", 20); } } public static bool ThrowExceptionOnError { get { bool fromUnitTest = Utils.IsCalledFromUnitTest(); return Config.GetBoolSetting("ThrowExceptionOnError", fromUnitTest); } } public static bool PrintMapInVetReports { get { return Config.GetBoolSetting("PrintMapInVetReports", true); } } public static bool ShowDateTimeFormatAsNullText { get { return Config.GetBoolSetting("ShowDateTimeFormatAsNullText", true); } } public static bool ShowSaveDataPrompt { get { return Config.GetBoolSetting("ShowSaveDataPrompt", true); } } public static bool ShowNavigatorInH02Form { get { return Config.GetBoolSetting("ShowNavigatorInH02Form"); } } public static bool SaveOnCancel { get { return Config.GetBoolSetting("SaveOnCancel", true); } } public static bool ShowDeletePrompt { get { return Config.GetBoolSetting("ShowDeletePrompt", true); } } public static bool ShowRecordsFromCurrentSiteForNewCase { get { return Config.GetBoolSetting("ShowRecordsFromCurrentSiteForNewCase", true); } } public static bool AutoClickDuplicateSearchButton { get { return Config.GetBoolSetting("AutoClickDuplicateSearchButton", true); } } public static string SkinName { get { return Config.GetSetting("SkinName", "eidss money twins"); } } public static string ServerPath { get { return Config.GetSetting("ServerPath"); } } public static string SkinAssembly { get { return Config.GetSetting("SkinAssembly"); } } public static bool IgnoreTopMaxCount { get { return Config.GetBoolSetting("IgnoreTopMaxCount"); } } public static bool AsSessionTableView { get { return Config.GetBoolSetting("AsSessionTableView"); } } public static string ArchiveConnectionString { get { return Config.GetSetting("ArchiveConnectionString"); } } public static bool WarnIfResourceEmpty { get { return Config.GetBoolSetting("WarnIfResourceEmpty"); } } public static bool LabSimplifiedMode { get { return Config.GetBoolSetting("LabSimplifiedMode"); } } public static string EpiInfoPath { get { return Config.GetSetting("EpiInfoPath"); } } public static int CheckNotificationSeconds { get { return Config.GetIntSetting("CheckNotificationSeconds", 10); } } public static int AutoHideNotificationSeconds { get { return Config.GetIntSetting("AutoHideNotificationSeconds", 1200); } } public static int SelectTopMaxCount { get { return Config.GetIntSetting("SelectTopMaxCount", 10000); } } public static int DefaultDateFilter { get { return Config.GetIntSetting("DefaultDateFilter", 14); } } public static bool ScanFormsMode { get { return Config.GetBoolSetting("ScanFormsMode"); } } public static bool UpdateConnectionInfo { get { return Config.GetBoolSetting("UpdateConnectionInfo", true); } } public static bool PlaySoundForAlerts { get { return Config.GetBoolSetting("PlaySoundForAlerts"); } } public static bool DefaultRegionInSearch { get { return Config.GetBoolSetting("DefaultRegionInSearch", true); } } public static bool RecalcFiltration { get { return Config.GetBoolSetting("RecalcFiltration"); } } public static string DefaultMapProject { get { return Config.GetSetting("DefaultMapProject"); } } public static int TicketExpiration { get { return Config.GetIntSetting("TicketExpiration", 30); } } public static int EventLogListenInterval { get { return Config.GetIntSetting("EventLogListenInterval", 500); } } public static int DelayedReplicationPeriod { get { return Config.GetIntSetting("DelayedReplicationPeriod", 60000); } } public static bool UseOrganizationInLogin { get { return Config.GetBoolSetting("UseOrganizationInLogin"); } } public static int LabSectionPageSize { get { int ret = Config.GetIntSetting("LabSectionPageSize", 50); if (ret > 200) { ret = 200; } return ret; } } public static int ListGridPageSize { get { return Config.GetIntSetting("ListGridPageSize", 50); } } public static int PopupGridPageSize { get { return Config.GetIntSetting("PopupGridPageSize", 50); } } public static int DetailGridPageSize { get { return Config.GetIntSetting("DetailGridPageSize", 10); } } public static bool CollectUsedXtraResources { get { return Config.GetBoolSetting("CollectUsedXtraResources"); } } public static bool ShowAllLoginTabs { get { return Config.GetBoolSetting("ShowAllLoginTabs"); } } public static bool ForceLeftToRight { get { return Config.GetBoolSetting("ForceLeftToRight"); } } public static bool ForceRightToLeft { get { return Config.GetBoolSetting("ForceRightToLeft"); } } public static string ErrorLogPath { get { return Config.GetSetting("ErrorLogPath", "ErrorLog"); } } public static bool DoNotShowSplash { get { return Config.GetBoolSetting("DoNotShowSplash"); } } public static int DeadlockDelay { get { return Config.GetIntSetting("DeadlockDelay ", 2000); } } public static int DeadlockAttemptsCount { get { return Config.GetIntSetting("DeadlockAttemptsCount", 2); } } public static bool ValidateObject { get { return Config.GetBoolSetting("ValidateObject"); } } public static bool UseDebugTimer { get { return Config.GetBoolSetting("UseDebugTimer"); } } public static bool SuppressGettingModifiedLookupTables { get { return Config.GetBoolSetting("SuppressGettingModifiedLookupTables"); } } public static bool SearchDuplicatesAutomatically { get { return Config.GetBoolSetting("SearchDuplicatesAutomatically", true); } } public static bool LanguageMenuWithoutFlags { get { return Config.GetBoolSetting("LangMenuWithoutFlags", true); } } public static bool ShowWarningForFinalCaseClassification { get { return Config.GetBoolSetting(SettingName.ShowWarningForFinalCaseClassification, false); } } public static bool FilterSamplesByDiagnosis { get { return Config.GetBoolSetting(SettingName.FilterSamplesByDiagnosis); } } public static int WebAvrDataLifeTime { get { return Config.GetIntSetting(SettingName.WebAvrDataLifeTime, 3); } } public static int WebAvrDataCheckInterval { get { return Config.GetIntSetting(SettingName.WebAvrDataCheckInterval, 5); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text.RegularExpressions; using Xunit; public partial class RegexMatchTests { /* Tested Methods: public static Match Match(string input); Noncapturing group : Actual - "(a+)(?:b*)(ccc)" "aaabbbccc" public static Match Match(string input); Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+" "abcXXXdef" public static Match Match(string input); Zero-width negative lookahead assertion: Actual - "abc(?!XXX)\\w+" "abcXXXdef" - Negative public static Match Match(string input); Zero-width positive lookbehind assertion: Actual - "(\\w){6}(?< = XXX ) def " " abcXXXdef " public static Match Match ( string input ) ; Zero-width negative lookbehind assertion : Actual - " ( \ \ w ) { 6 } ( ? < ! XXX ) def " " XXXabcdef " public static Match Match ( string input ) ; Nonbacktracking subexpression : Actual - " [ ^ 0 - 9 ] + ( ?>[0-9]+)3" "abc123" */ [Fact] public static void RegexMatchTestCase4() { //////////// Global Variables used for all tests String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Regex r; Match match; String strMatch1 = "aaabbbccc"; Int32[] iMatch1 = { 0, 9 } ; String[] strGroup1 = { "aaabbbccc", "aaa", "ccc" } ; Int32[,] iGroup1 = { { 0, 9 } , { 0, 3 } , { 6, 3 } } ; String[][] strGrpCap1 = new String[3][]; strGrpCap1[0] = new String[] { "aaabbbccc" } ; strGrpCap1[1] = new String[] { "aaa" } ; strGrpCap1[2] = new String[] { "ccc" } ; Int32[][] iGrpCap1 = new Int32[3][]; iGrpCap1[0] = new Int32[] { 5, 9 } ; //This is ignored iGrpCap1[1] = new Int32[] { 0, 3 } ; //The first half contains the Index and the latter half the Lengths iGrpCap1[2] = new Int32[] { 6, 3 } ; //The first half contains the Index and the latter half the Lengths String strMatch2 = "abcXXXdef"; Int32[] iMatch2 = { 0, 9 } ; String[] strGroup2 = { "abcXXXdef" } ; Int32[,] iGroup2 = { { 0, 9 } } ; String[][] strGrpCap2 = new String[1][]; strGrpCap2[0] = new String[] { "abcXXXdef" } ; Int32[][] iGrpCap2 = new Int32[1][]; iGrpCap2[0] = new Int32[] { 0, 9 } ; //This is ignored try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// // [] public static Match Match(string input); Noncapturing group : Actual - "(a+)(?:b*)(ccc)" //"aaabbbccc" //----------------------------------------------------------------- strLoc = "Loc_498yg"; iCountTestcases++; r = new Regex("(a+)(?:b*)(ccc)"); match = r.Match("aaabbbccc"); if (!match.Success) { iCountErrors++; Console.WriteLine("Err_78653refgs! doesnot match"); } else { if (!match.Value.Equals(strMatch1) || (match.Index != iMatch1[0]) || (match.Length != iMatch1[1]) || (match.Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_98275dsg: unexpected return result"); } //Match.Captures always is Match if (!match.Captures[0].Value.Equals(strMatch1) || (match.Captures[0].Index != iMatch1[0]) || (match.Captures[0].Length != iMatch1[1])) { iCountErrors++; Console.WriteLine("Err_2046gsg! unexpected return result"); } if (match.Groups.Count != 3) { iCountErrors++; Console.WriteLine("Err_75324sg! unexpected return result"); } //Group 0 always is the Match if (!match.Groups[0].Value.Equals(strMatch1) || (match.Groups[0].Index != iMatch1[0]) || (match.Groups[0].Length != iMatch1[1]) || (match.Groups[0].Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_2046gsg! unexpected return result"); } //Group 0's Capture is always the Match if (!match.Groups[0].Captures[0].Value.Equals(strMatch1) || (match.Groups[0].Captures[0].Index != iMatch1[0]) || (match.Groups[0].Captures[0].Length != iMatch1[1])) { iCountErrors++; Console.WriteLine("Err_2975edg!! unexpected return result"); } for (int i = 1; i < match.Groups.Count; i++) { if (!match.Groups[i].Value.Equals(strGroup1[i]) || (match.Groups[i].Index != iGroup1[i, 0]) || (match.Groups[i].Length != iGroup1[i, 1]) || (match.Groups[i].Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_1954eg_" + i + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>", match.Groups[i].Value, match.Groups[i].Index, match.Groups[i].Length, strGroup1[i], iGroup1[i, 0], iGroup1[i, 1]); } for (int j = 0; j < match.Groups[i].Captures.Count; j++) { if (!match.Groups[i].Captures[j].Value.Equals(strGrpCap1[i][j]) || (match.Groups[i].Captures[j].Index != iGrpCap1[i][j]) || (match.Groups[i].Captures[j].Length != iGrpCap1[i][match.Groups[i].Captures.Count + j])) { iCountErrors++; Console.WriteLine("Err_5072dn_" + i + "_" + j + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>", match.Groups[i].Captures[j].Value, match.Groups[i].Captures[j].Index, match.Groups[i].Captures[j].Length, strGrpCap1[i][j], iGrpCap1[i][j], iGrpCap1[i][match.Groups[i].Captures.Count + j]); } } } } // [] public static Match Match(string input); Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+" //"abcXXXdef" //----------------------------------------------------------------- strLoc = "Loc_298vy"; iCountTestcases++; r = new Regex(@"abc(?=XXX)\w+"); match = r.Match("abcXXXdef"); if (!match.Success) { iCountErrors++; Console.WriteLine("Err_7453efg! doesnot match"); } else { if (!match.Value.Equals(strMatch2) || (match.Index != iMatch2[0]) || (match.Length != iMatch2[1]) || (match.Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_827345sdf! unexpected return result"); } //Match.Captures always is Match if (!match.Captures[0].Value.Equals(strMatch2) || (match.Captures[0].Index != iMatch2[0]) || (match.Captures[0].Length != iMatch2[1])) { iCountErrors++; Console.WriteLine("Err_1074sf! unexpected return result"); } if (match.Groups.Count != 1) { iCountErrors++; Console.WriteLine("Err_2175sgg! unexpected return result"); } //Group 0 always is the Match if (!match.Groups[0].Value.Equals(strMatch2) || (match.Groups[0].Index != iMatch2[0]) || (match.Groups[0].Length != iMatch2[1]) || (match.Groups[0].Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_68217fdgs! unexpected return result"); } //Group 0's Capture is always the Match if (!match.Groups[0].Captures[0].Value.Equals(strMatch2) || (match.Groups[0].Captures[0].Index != iMatch2[0]) || (match.Groups[0].Captures[0].Length != iMatch2[1])) { iCountErrors++; Console.WriteLine("Err_139wn!! unexpected return result"); } for (int i = 1; i < match.Groups.Count; i++) { if (!match.Groups[i].Value.Equals(strGroup2[i]) || (match.Groups[i].Index != iGroup2[i, 0]) || (match.Groups[i].Length != iGroup2[i, 1]) || (match.Groups[i].Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_107vxg_" + i + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>", match.Groups[i].Value, match.Groups[i].Index, match.Groups[i].Length, strGroup2[i], iGroup2[i, 0], iGroup2[i, 1]); } for (int j = 0; j < match.Groups[i].Captures.Count; j++) { if (!match.Groups[i].Captures[j].Value.Equals(strGrpCap2[i][j]) || (match.Groups[i].Captures[j].Index != iGrpCap2[i][j]) || (match.Groups[i].Captures[j].Length != iGrpCap2[i][match.Groups[i].Captures.Count + j])) { iCountErrors++; Console.WriteLine("Err_745dsgg_" + i + "_" + j + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>", match.Groups[i].Captures[j].Value, match.Groups[i].Captures[j].Index, match.Groups[i].Captures[j].Length, strGrpCap2[i][j], iGrpCap2[i][j], iGrpCap2[i][match.Groups[i].Captures.Count + j]); } } } } // [] public static Match Match(string input); Zero-width negative lookahead assertion: Actual - "abc(?!XXX)\\w+" //"abcXXXdef" - Negative //----------------------------------------------------------------- strLoc = "Loc_746tegd"; iCountTestcases++; r = new Regex(@"abc(?!XXX)\w+"); match = r.Match("abcXXXdef"); if (match.Success) { iCountErrors++; Console.WriteLine("Err_756tdfg! doesnot match"); } // [] public static Match Match(string input); Zero-width positive lookbehind assertion: Actual - "(\\w){6}(?<=XXX)def" //"abcXXXdef" //----------------------------------------------------------------- strLoc = "Loc_563rfg"; iCountTestcases++; r = new Regex(@"(\w){6}(?<=XXX)def"); match = r.Match("abcXXXdef"); if (!match.Success) { iCountErrors++; Console.WriteLine("Err_1072gdg! doesnot match"); } // [] public static Match Match(string input); Zero-width negative lookbehind assertion: Actual - "(\\w){6}(?<!XXX)def" //"XXXabcdef" //----------------------------------------------------------------- strLoc = "Loc_563rfg"; iCountTestcases++; r = new Regex(@"(\w){6}(?<!XXX)def"); match = r.Match("XXXabcdef"); if (!match.Success) { iCountErrors++; Console.WriteLine("Err_532resgf! doesnot match"); } // [] public static Match Match(string input); Nonbacktracking subexpression: Actual - "[^0-9]+(?>[0-9]+)3" //"abc123" //----------------------------------------------------------------- strLoc = "Loc_563rfg"; iCountTestcases++; r = new Regex("[^0-9]+(?>[0-9]+)3"); //The last 3 causes the match to fail, since the non backtracking subexpression does not give up the last digit it matched //for it to be a success. For a correct match, remove the last character, '3' from the pattern match = r.Match("abc123"); if (match.Success) { iCountErrors++; Console.WriteLine("Err_234fsadg! doesnot match"); } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics Assert.Equal(0, iCountErrors); } }
//! \file ImageGRP.cs //! \date Wed Jun 24 22:14:41 2015 //! \brief Cherry Soft compressed image format. // // Copyright (C) 2015 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Compression; using GameRes.Utility; namespace GameRes.Formats.Cherry { internal class GrpMetaData : ImageMetaData { public int PackedSize; public int UnpackedSize; public int Offset; public int HeaderSize; public bool AlphaChannel; } [Export(typeof(ImageFormat))] public class GrpFormat : ImageFormat { public override string Tag { get { return "GRP/CHERRY"; } } public override string Description { get { return "Cherry Soft compressed image format"; } } public override uint Signature { get { return 0; } } public GrpFormat () { Extensions = new string[] { "grp" }; } public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[0x18]; if (header.Length != stream.Read (header, 0, header.Length)) return null; uint width = LittleEndian.ToUInt32 (header, 0); uint height = LittleEndian.ToUInt32 (header, 4); int bpp = LittleEndian.ToInt32 (header, 8); int packed_size = LittleEndian.ToInt32 (header, 0x0C); int unpacked_size = LittleEndian.ToInt32 (header, 0x10); if (0 == width || 0 == height || width > 0x7fff || height > 0x7fff || (bpp != 24 && bpp != 8) || unpacked_size <= 0 || packed_size < 0) return null; return new GrpMetaData { Width = width, Height = height, BPP = bpp, PackedSize = packed_size, UnpackedSize = unpacked_size, Offset = LittleEndian.ToInt32 (header, 0x14), HeaderSize = 0x18, AlphaChannel = false, }; } public override ImageData Read (Stream stream, ImageMetaData info) { var meta = (GrpMetaData)info; var reader = new GrpReader (stream, meta); return reader.CreateImage(); } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("GrpFormat.Write not implemented"); } } [Export(typeof(ImageFormat))] public class Grp3Format : GrpFormat { public override string Tag { get { return "GRP/CHERRY3"; } } public override string Description { get { return "Cherry Soft compressed image format"; } } public override uint Signature { get { return 0; } } public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[0x28]; if (header.Length != stream.Read (header, 0, header.Length)) return null; if (0xFFFF != LittleEndian.ToInt32 (header, 8)) return null; int packed_size = LittleEndian.ToInt32 (header, 0); int unpacked_size = LittleEndian.ToInt32 (header, 4); uint width = LittleEndian.ToUInt32 (header, 0x10); uint height = LittleEndian.ToUInt32 (header, 0x14); int bpp = LittleEndian.ToInt32 (header, 0x18); if (0 == width || 0 == height || width > 0x7fff || height > 0x7fff || (bpp != 32 && bpp != 24 && bpp != 8) || unpacked_size <= 0 || packed_size < 0) return null; return new GrpMetaData { Width = width, Height = height, BPP = bpp, PackedSize = packed_size, UnpackedSize = unpacked_size, Offset = 0xFFFF, HeaderSize = 0x28, AlphaChannel = LittleEndian.ToInt32 (header, 0x24) != 0, }; } } internal class GrpReader { GrpMetaData m_info; Stream m_input; byte[] m_image_data; int m_stride; public PixelFormat Format { get; private set; } public BitmapPalette Palette { get; private set; } public byte[] Pixels { get { return m_image_data; } } public GrpReader (Stream input, GrpMetaData info) { m_info = info; m_input = input; if (8 == info.BPP) Format = PixelFormats.Indexed8; else if (24 == info.BPP) Format = PixelFormats.Bgr24; else if (32 == info.BPP) Format = m_info.AlphaChannel ? PixelFormats.Bgra32 : PixelFormats.Bgr32; else throw new NotSupportedException ("Not supported GRP image depth"); m_stride = (int)m_info.Width*((Format.BitsPerPixel+7)/8); } public ImageData CreateImage () { m_input.Position = m_info.HeaderSize; int data_size = m_info.UnpackedSize; if (m_info.PackedSize != 0) data_size = m_info.PackedSize; if (0x0f0f0f0f == m_info.Offset && 0x18 + data_size == m_input.Length) return ReadV2(); else if (8 == m_info.BPP && 0x418 == m_info.Offset || 24 == m_info.BPP && 0x018 == m_info.Offset) return ReadV1(); else if (true) // FIXME return ReadV3 (0xFFFF != m_info.Offset); else throw new InvalidFormatException(); } private ImageData ReadV1 () { if (8 == m_info.BPP) { var palette_data = new byte[0x400]; if (palette_data.Length != m_input.Read (palette_data, 0, palette_data.Length)) throw new InvalidFormatException ("Unexpected end of file"); SetPalette (palette_data); } var packed = new byte[m_info.PackedSize]; if (packed.Length != m_input.Read (packed, 0, packed.Length)) throw new InvalidFormatException ("Unexpected end of file"); for (int i = 0; i < packed.Length; ++i) packed[i] ^= (byte)i; using (var input = new MemoryStream (packed)) using (var reader = new LzssReader (input, packed.Length, m_info.UnpackedSize)) { reader.Unpack(); m_image_data = new byte[m_info.UnpackedSize]; // flip pixels vertically int dst = 0; for (int src = m_stride * ((int)m_info.Height-1); src >= 0; src -= m_stride) { Buffer.BlockCopy (reader.Data, src, m_image_data, dst, m_stride); dst += m_stride; } } return ImageData.Create (m_info, Format, Palette, m_image_data); } // DOUBLE private ImageData ReadV2 () { if (0 != m_info.PackedSize) { using (var reader = new LzssReader (m_input, m_info.PackedSize, m_info.UnpackedSize)) { reader.Unpack(); m_image_data = reader.Data; } } else { m_image_data = new byte[m_info.UnpackedSize]; if (m_image_data.Length != m_input.Read (m_image_data, 0, m_image_data.Length)) throw new InvalidFormatException ("Unexpected end of file"); } int pixels_offset = 0; if (8 == m_info.BPP) { SetPalette (m_image_data); pixels_offset += 0x400; } if (0 == pixels_offset) return ImageData.Create (m_info, Format, Palette, m_image_data); if (pixels_offset + m_stride*(int)m_info.Height > m_image_data.Length) throw new InvalidFormatException(); unsafe { fixed (byte* pixels = &m_image_data[pixels_offset]) { var bitmap = BitmapSource.Create ((int)m_info.Width, (int)m_info.Height, ImageData.DefaultDpiX, ImageData.DefaultDpiY, Format, Palette, (IntPtr)pixels, m_image_data.Length-pixels_offset, m_stride); bitmap.Freeze(); return new ImageData (bitmap, m_info); } } } // Exile ~Blood Royal 2~ : flipped == true // Gakuen ~Nerawareta Chitai~ : flipped == false private ImageData ReadV3 (bool flipped) { using (var lzs = new LzssStream (m_input, LzssMode.Decompress, true)) { if (8 == m_info.BPP) { var palette_data = new byte[0x400]; if (palette_data.Length != lzs.Read (palette_data, 0, palette_data.Length)) throw new InvalidFormatException ("Unexpected end of file"); SetPalette (palette_data); } m_image_data = new byte[m_stride * (int)m_info.Height]; if (m_image_data.Length != lzs.Read (m_image_data, 0, m_image_data.Length)) throw new InvalidFormatException(); if (flipped) return ImageData.CreateFlipped (m_info, Format, Palette, m_image_data, m_stride); else return ImageData.Create (m_info, Format, Palette, m_image_data, m_stride); } } private void SetPalette (byte[] palette_data) { if (palette_data.Length < 0x400) throw new InvalidFormatException(); var palette = new Color[0x100]; for (int i = 0; i < palette.Length; ++i) { int c = i * 4; palette[i] = Color.FromRgb (palette_data[c+2], palette_data[c+1], palette_data[c]); } Palette = new BitmapPalette (palette); } } }
// 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. /*============================================================ ** ** Classes: Object Security family of classes ** ** ===========================================================*/ using Microsoft.Win32; using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading; namespace System.Security.AccessControl { public enum AccessControlModification { Add = 0, Set = 1, Reset = 2, Remove = 3, RemoveAll = 4, RemoveSpecific = 5, } public abstract class ObjectSecurity { #region Private Members private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); internal CommonSecurityDescriptor _securityDescriptor; private bool _ownerModified = false; private bool _groupModified = false; private bool _saclModified = false; private bool _daclModified = false; // only these SACL control flags will be automatically carry forward // when update with new security descriptor. static private readonly ControlFlags SACL_CONTROL_FLAGS = ControlFlags.SystemAclPresent | ControlFlags.SystemAclAutoInherited | ControlFlags.SystemAclProtected; // only these DACL control flags will be automatically carry forward // when update with new security descriptor static private readonly ControlFlags DACL_CONTROL_FLAGS = ControlFlags.DiscretionaryAclPresent | ControlFlags.DiscretionaryAclAutoInherited | ControlFlags.DiscretionaryAclProtected; #endregion #region Constructors protected ObjectSecurity() { } protected ObjectSecurity( bool isContainer, bool isDS ) : this() { // we will create an empty DACL, denying anyone any access as the default. 5 is the capacity. DiscretionaryAcl dacl = new DiscretionaryAcl(isContainer, isDS, 5); _securityDescriptor = new CommonSecurityDescriptor( isContainer, isDS, ControlFlags.None, null, null, null, dacl ); } protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor) : this() { if ( securityDescriptor == null ) { throw new ArgumentNullException( nameof(securityDescriptor)); } Contract.EndContractBlock(); _securityDescriptor = securityDescriptor; } #endregion #region Private methods private void UpdateWithNewSecurityDescriptor( RawSecurityDescriptor newOne, AccessControlSections includeSections ) { Debug.Assert( newOne != null, "Must not supply a null parameter here" ); if (( includeSections & AccessControlSections.Owner ) != 0 ) { _ownerModified = true; _securityDescriptor.Owner = newOne.Owner; } if (( includeSections & AccessControlSections.Group ) != 0 ) { _groupModified = true; _securityDescriptor.Group = newOne.Group; } if (( includeSections & AccessControlSections.Audit ) != 0 ) { _saclModified = true; if ( newOne.SystemAcl != null ) { _securityDescriptor.SystemAcl = new SystemAcl( IsContainer, IsDS, newOne.SystemAcl, true ); } else { _securityDescriptor.SystemAcl = null; } // carry forward the SACL related control flags _securityDescriptor.UpdateControlFlags(SACL_CONTROL_FLAGS, (ControlFlags)(newOne.ControlFlags & SACL_CONTROL_FLAGS)); } if (( includeSections & AccessControlSections.Access ) != 0 ) { _daclModified = true; if ( newOne.DiscretionaryAcl != null ) { _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl( IsContainer, IsDS, newOne.DiscretionaryAcl, true ); } else { _securityDescriptor.DiscretionaryAcl = null; } // by the following property set, the _securityDescriptor's control flags // may contains DACL present flag. That needs to be carried forward! Therefore, we OR // the current _securityDescriptor.s DACL present flag. ControlFlags daclFlag = (_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent); _securityDescriptor.UpdateControlFlags(DACL_CONTROL_FLAGS, (ControlFlags)((newOne.ControlFlags | daclFlag) & DACL_CONTROL_FLAGS)); } } #endregion #region Protected Properties and Methods protected void ReadLock() { _lock.EnterReadLock(); } protected void ReadUnlock() { _lock.ExitReadLock(); } protected void WriteLock() { _lock.EnterWriteLock(); } protected void WriteUnlock() { _lock.ExitWriteLock(); } protected bool OwnerModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _ownerModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _ownerModified = value; } } protected bool GroupModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _groupModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _groupModified = value; } } protected bool AuditRulesModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _saclModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _saclModified = value; } } protected bool AccessRulesModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _daclModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _daclModified = value; } } protected bool IsContainer { get { return _securityDescriptor.IsContainer; } } protected bool IsDS { get { return _securityDescriptor.IsDS; } } // // Persists the changes made to the object // // This overloaded method takes a name of an existing object // protected virtual void Persist( string name, AccessControlSections includeSections ) { throw NotImplemented.ByDesign; } // // if Persist (by name) is implemented, then this function will also try to enable take ownership // privilege while persisting if the enableOwnershipPrivilege is true. // Integrators can override it if this is not desired. // protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections ) { Privilege ownerPrivilege = null; try { if (enableOwnershipPrivilege) { ownerPrivilege = new Privilege(Privilege.TakeOwnership); try { ownerPrivilege.Enable(); } catch (PrivilegeNotHeldException) { // we will ignore this exception and press on just in case this is a remote resource } } Persist(name, includeSections); } catch { // protection against exception filter-based luring attacks if ( ownerPrivilege != null ) { ownerPrivilege.Revert(); } throw; } finally { if (ownerPrivilege != null) { ownerPrivilege.Revert(); } } } // // Persists the changes made to the object // // This overloaded method takes a handle to an existing object // protected virtual void Persist( SafeHandle handle, AccessControlSections includeSections ) { throw NotImplemented.ByDesign; } #endregion #region Public Methods // // Sets and retrieves the owner of this object // public IdentityReference GetOwner( System.Type targetType ) { ReadLock(); try { if ( _securityDescriptor.Owner == null ) { return null; } return _securityDescriptor.Owner.Translate( targetType ); } finally { ReadUnlock(); } } public void SetOwner( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.Owner = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier; _ownerModified = true; } finally { WriteUnlock(); } } // // Sets and retrieves the group of this object // public IdentityReference GetGroup( System.Type targetType ) { ReadLock(); try { if ( _securityDescriptor.Group == null ) { return null; } return _securityDescriptor.Group.Translate( targetType ); } finally { ReadUnlock(); } } public void SetGroup( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.Group = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier; _groupModified = true; } finally { WriteUnlock(); } } public virtual void PurgeAccessRules( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.PurgeAccessControl( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier ); _daclModified = true; } finally { WriteUnlock(); } } public virtual void PurgeAuditRules(IdentityReference identity) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } Contract.EndContractBlock(); WriteLock(); try { _securityDescriptor.PurgeAudit( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier ); _saclModified = true; } finally { WriteUnlock(); } } public bool AreAccessRulesProtected { get { ReadLock(); try { return (( _securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected ) != 0 ); } finally { ReadUnlock(); } } } public void SetAccessRuleProtection( bool isProtected, bool preserveInheritance ) { WriteLock(); try { _securityDescriptor.SetDiscretionaryAclProtection( isProtected, preserveInheritance ); _daclModified = true; } finally { WriteUnlock(); } } public bool AreAuditRulesProtected { get { ReadLock(); try { return (( _securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected ) != 0 ); } finally { ReadUnlock(); } } } public void SetAuditRuleProtection( bool isProtected, bool preserveInheritance ) { WriteLock(); try { _securityDescriptor.SetSystemAclProtection( isProtected, preserveInheritance ); _saclModified = true; } finally { WriteUnlock(); } } public bool AreAccessRulesCanonical { get { ReadLock(); try { return _securityDescriptor.IsDiscretionaryAclCanonical; } finally { ReadUnlock(); } } } public bool AreAuditRulesCanonical { get { ReadLock(); try { return _securityDescriptor.IsSystemAclCanonical; } finally { ReadUnlock(); } } } public static bool IsSddlConversionSupported() { return true; // SDDL to binary conversions are supported on Windows 2000 and higher } public string GetSecurityDescriptorSddlForm( AccessControlSections includeSections ) { ReadLock(); try { return _securityDescriptor.GetSddlForm( includeSections ); } finally { ReadUnlock(); } } public void SetSecurityDescriptorSddlForm( string sddlForm ) { SetSecurityDescriptorSddlForm( sddlForm, AccessControlSections.All ); } public void SetSecurityDescriptorSddlForm( string sddlForm, AccessControlSections includeSections ) { if ( sddlForm == null ) { throw new ArgumentNullException( nameof(sddlForm)); } if (( includeSections & AccessControlSections.All ) == 0 ) { throw new ArgumentException( SR.Arg_EnumAtLeastOneFlag, nameof(includeSections)); } Contract.EndContractBlock(); WriteLock(); try { UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( sddlForm ), includeSections ); } finally { WriteUnlock(); } } public byte[] GetSecurityDescriptorBinaryForm() { ReadLock(); try { byte[] result = new byte[_securityDescriptor.BinaryLength]; _securityDescriptor.GetBinaryForm( result, 0 ); return result; } finally { ReadUnlock(); } } public void SetSecurityDescriptorBinaryForm( byte[] binaryForm ) { SetSecurityDescriptorBinaryForm( binaryForm, AccessControlSections.All ); } public void SetSecurityDescriptorBinaryForm( byte[] binaryForm, AccessControlSections includeSections ) { if ( binaryForm == null ) { throw new ArgumentNullException( nameof(binaryForm)); } if (( includeSections & AccessControlSections.All ) == 0 ) { throw new ArgumentException( SR.Arg_EnumAtLeastOneFlag, nameof(includeSections)); } Contract.EndContractBlock(); WriteLock(); try { UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( binaryForm, 0 ), includeSections ); } finally { WriteUnlock(); } } public abstract Type AccessRightType { get; } public abstract Type AccessRuleType { get; } public abstract Type AuditRuleType { get; } protected abstract bool ModifyAccess( AccessControlModification modification, AccessRule rule, out bool modified); protected abstract bool ModifyAudit( AccessControlModification modification, AuditRule rule, out bool modified ); public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified) { if ( rule == null ) { throw new ArgumentNullException( nameof(rule)); } if ( !this.AccessRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) ) { throw new ArgumentException( SR.AccessControl_InvalidAccessRuleType, nameof(rule)); } Contract.EndContractBlock(); WriteLock(); try { return ModifyAccess(modification, rule, out modified); } finally { WriteUnlock(); } } public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified) { if ( rule == null ) { throw new ArgumentNullException( nameof(rule)); } if ( !this.AuditRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) ) { throw new ArgumentException( SR.AccessControl_InvalidAuditRuleType, nameof(rule)); } Contract.EndContractBlock(); WriteLock(); try { return ModifyAudit(modification, rule, out modified); } finally { WriteUnlock(); } } public abstract AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type ); public abstract AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags ); #endregion } }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; public class FContainer : FNode { protected List<FNode> _childNodes = new List<FNode>(5); private int _oldChildNodesHash = 0; private bool _shouldSortByZ = false; //don't turn this on unless you really need it, it'll do a sort every redraw public FContainer () : base() { } override public void Redraw(bool shouldForceDirty, bool shouldUpdateDepth) { bool wasMatrixDirty = _isMatrixDirty; bool wasAlphaDirty = _isAlphaDirty; UpdateDepthMatrixAlpha(shouldForceDirty, shouldUpdateDepth); int childCount = _childNodes.Count; for(int c = 0; c<childCount; c++) { _childNodes[c].Redraw(shouldForceDirty || wasMatrixDirty || wasAlphaDirty, shouldUpdateDepth); //if the matrix was dirty or we're supposed to force it, do it! } } override public void HandleAddedToStage() { if(!_isOnStage) { base.HandleAddedToStage(); int childCount = _childNodes.Count; for(int c = 0; c<childCount; c++) { FNode childNode = _childNodes[c]; childNode.stage = _stage; childNode.HandleAddedToStage(); } if(_shouldSortByZ) { Futile.instance.SignalUpdate += HandleUpdateAndSort; } } } override public void HandleRemovedFromStage() { if(_isOnStage) { base.HandleRemovedFromStage(); int childCount = _childNodes.Count; for(int c = 0; c<childCount; c++) { FNode childNode = _childNodes[c]; childNode.HandleRemovedFromStage(); childNode.stage = null; } if(_shouldSortByZ) { Futile.instance.SignalUpdate -= HandleUpdateAndSort; } } } private void HandleUpdateAndSort() { bool didChildOrderChangeAfterSort = SortByZ(); if(didChildOrderChangeAfterSort) //sort the order, and then if the child order was changed, repopulate the renderlayer { if(_isOnStage) _stage.HandleFacetsChanged(); } } public void AddChild(FNode node) { int nodeIndex = _childNodes.IndexOf(node); if(nodeIndex == -1) //add it if it's not a child { node.HandleAddedToContainer(this); _childNodes.Add(node); if(_isOnStage) { node.stage = _stage; node.HandleAddedToStage(); } } else if(nodeIndex != _childNodes.Count-1) //if node is already a child, put it at the top of the children if it's not already { _childNodes.RemoveAt(nodeIndex); _childNodes.Add(node); if(_isOnStage) _stage.HandleFacetsChanged(); } } public void AddChildAtIndex(FNode node, int newIndex) { int nodeIndex = _childNodes.IndexOf(node); if(newIndex > _childNodes.Count) //if it's past the end, make it at the end { newIndex = _childNodes.Count; } if(nodeIndex == newIndex) return; //if it's already at the right index, just leave it there if(nodeIndex == -1) //add it if it's not a child { node.HandleAddedToContainer(this); _childNodes.Insert(newIndex, node); if(_isOnStage) { node.stage = _stage; node.HandleAddedToStage(); } } else //if node is already a child, move it to the desired index { _childNodes.RemoveAt(nodeIndex); if(nodeIndex < newIndex) { _childNodes.Insert(newIndex-1, node); //gotta subtract 1 to account for it moving in the order } else { _childNodes.Insert(newIndex, node); } if(_isOnStage) _stage.HandleFacetsChanged(); } } public void RemoveChild(FNode node) { if(node.container != this) return; //I ain't your daddy node.HandleRemovedFromContainer(); if(_isOnStage) { node.HandleRemovedFromStage(); node.stage = null; } _childNodes.Remove(node); } public void RemoveAllChildren() { int childCount = _childNodes.Count; for(int c = 0; c<childCount; c++) { FNode node = _childNodes[c]; node.HandleRemovedFromContainer(); if(_isOnStage) { node.HandleRemovedFromStage(); node.stage = null; } } _childNodes.Clear(); } public int GetChildCount() { return _childNodes.Count; } public FNode GetChildAt(int childIndex) { return _childNodes[childIndex]; } public bool shouldSortByZ { get {return _shouldSortByZ;} set { if(_shouldSortByZ != value) { _shouldSortByZ = value; if(_shouldSortByZ) { if(_isOnStage) { Futile.instance.SignalUpdate += HandleUpdateAndSort; } } else { if(_isOnStage) { Futile.instance.SignalUpdate -= HandleUpdateAndSort; } } } } } private static int ZComparison(FNode a, FNode b) { float delta = a.sortZ - b.sortZ; if(delta < 0) return -1; if(delta > 0) return 1; return 0; } private bool SortByZ() //returns true if the childNodes changed, false if they didn't { //using InsertionSort because it's stable (meaning equal values keep the same order) //this is unlike List.Sort, which is unstable, so things would constantly shift if equal. _childNodes.InsertionSort(ZComparison); //check if the order has changed, and if it has, update the quads/depth order //http://stackoverflow.com/questions/3030759/arrays-lists-and-computing-hashvalues-vb-c int hash = 269; unchecked //don't throw int overflow exceptions { int childCount = _childNodes.Count; for(int c = 0; c<childCount; c++) { hash = (hash * 17) + _childNodes[c].GetHashCode(); } } if(hash != _oldChildNodesHash) { _oldChildNodesHash = hash; return true; //order has changed } return false; //order hasn't changed } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Umbraco.Core; using Umbraco.Core.Dictionary; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; using umbraco; namespace Umbraco.Web.Models.Mapping { /// <summary> /// Creates the tabs collection with properties assigned for display models /// </summary> internal class TabsAndPropertiesResolver : ValueResolver<IContentBase, IEnumerable<Tab<ContentPropertyDisplay>>> { private ICultureDictionary _cultureDictionary; protected IEnumerable<string> IgnoreProperties { get; set; } public TabsAndPropertiesResolver() { IgnoreProperties = new List<string>(); } public TabsAndPropertiesResolver(IEnumerable<string> ignoreProperties) { if (ignoreProperties == null) throw new ArgumentNullException("ignoreProperties"); IgnoreProperties = ignoreProperties; } /// <summary> /// Maps properties on to the generic properties tab /// </summary> /// <param name="content"></param> /// <param name="display"></param> /// <param name="customProperties"> /// Any additional custom properties to assign to the generic properties tab. /// </param> /// <remarks> /// The generic properties tab is mapped during AfterMap and is responsible for /// setting up the properties such as Created date, updated date, template selected, etc... /// </remarks> public static void MapGenericProperties<TPersisted>( TPersisted content, ContentItemDisplayBase<ContentPropertyDisplay, TPersisted> display, params ContentPropertyDisplay[] customProperties) where TPersisted : IContentBase { var genericProps = display.Tabs.Single(x => x.Id == 0); //store the current props to append to the newly inserted ones var currProps = genericProps.Properties.ToArray(); var labelEditor = PropertyEditorResolver.Current.GetByAlias(Constants.PropertyEditors.NoEditAlias).ValueEditor.View; var contentProps = new List<ContentPropertyDisplay> { new ContentPropertyDisplay { Alias = string.Format("{0}id", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = "Id", Value = Convert.ToInt32(display.Id).ToInvariantString(), View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}creator", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "createBy"), Description = ui.Text("content", "createByDesc"), //TODO: Localize this Value = display.Owner.Name, View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}createdate", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "createDate"), Description = ui.Text("content", "createDateDesc"), Value = display.CreateDate.ToIsoString(), View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}updatedate", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "updateDate"), Description = ui.Text("content", "updateDateDesc"), Value = display.UpdateDate.ToIsoString(), View = labelEditor }, new ContentPropertyDisplay { Alias = string.Format("{0}doctype", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = ui.Text("content", "documentType"), Value = TranslateItem(display.ContentTypeName, CreateDictionary()), View = labelEditor } }; //add the custom ones contentProps.AddRange(customProperties); //now add the user props contentProps.AddRange(currProps); //re-assign genericProps.Properties = contentProps; } /// <summary> /// Adds the container (listview) tab to the document /// </summary> /// <typeparam name="TPersisted"></typeparam> /// <param name="display"></param> /// <param name="entityType">This must be either 'content' or 'media'</param> /// <param name="dataTypeService"></param> internal static void AddListView<TPersisted>(TabbedContentItem<ContentPropertyDisplay, TPersisted> display, string entityType, IDataTypeService dataTypeService) where TPersisted : IContentBase { int dtdId; var customDtdName = Constants.Conventions.DataTypes.ListViewPrefix + display.ContentTypeAlias; switch (entityType) { case "content": dtdId = Constants.System.DefaultContentListViewDataTypeId; break; case "media": dtdId = Constants.System.DefaultMediaListViewDataTypeId; break; case "member": dtdId = Constants.System.DefaultMembersListViewDataTypeId; break; default: throw new ArgumentOutOfRangeException("entityType does not match a required value"); } //first try to get the custom one if there is one var dt = dataTypeService.GetDataTypeDefinitionByName(customDtdName) ?? dataTypeService.GetDataTypeDefinitionById(dtdId); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dt.Id); var editor = PropertyEditorResolver.Current.GetByAlias(dt.PropertyEditorAlias); if (editor == null) { throw new NullReferenceException("The property editor with alias " + dt.PropertyEditorAlias + " does not exist"); } var listViewTab = new Tab<ContentPropertyDisplay>(); listViewTab.Alias = Constants.Conventions.PropertyGroups.ListViewGroupName; listViewTab.Label = ui.Text("content", "childItems"); listViewTab.Id = 25; listViewTab.IsActive = true; var listViewConfig = editor.PreValueEditor.ConvertDbToEditor(editor.DefaultPreValues, preVals); //add the entity type to the config listViewConfig["entityType"] = entityType; var listViewProperties = new List<ContentPropertyDisplay>(); listViewProperties.Add(new ContentPropertyDisplay { Alias = string.Format("{0}containerView", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = "", Value = null, View = editor.ValueEditor.View, HideLabel = true, Config = listViewConfig }); listViewTab.Properties = listViewProperties; //Is there a better way? var tabs = new List<Tab<ContentPropertyDisplay>>(); tabs.Add(listViewTab); tabs.AddRange(display.Tabs); display.Tabs = tabs; } protected override IEnumerable<Tab<ContentPropertyDisplay>> ResolveCore(IContentBase content) { var aggregateTabs = new List<Tab<ContentPropertyDisplay>>(); //now we need to aggregate the tabs and properties since we might have duplicate tabs (based on aliases) because // of how content composition works. foreach (var propertyGroups in content.PropertyGroups.OrderBy(x => x.SortOrder).GroupBy(x => x.Name)) { var aggregateProperties = new List<ContentPropertyDisplay>(); //add the properties from each composite property group foreach (var current in propertyGroups) { var propsForGroup = content.GetPropertiesForGroup(current) .Where(x => IgnoreProperties.Contains(x.Alias) == false); //don't include ignored props aggregateProperties.AddRange( Mapper.Map<IEnumerable<Property>, IEnumerable<ContentPropertyDisplay>>( propsForGroup)); } if (aggregateProperties.Count == 0) continue; TranslateProperties(aggregateProperties); //then we'll just use the root group's data to make the composite tab var rootGroup = propertyGroups.First(x => x.ParentId == null); aggregateTabs.Add(new Tab<ContentPropertyDisplay> { Id = rootGroup.Id, Alias = rootGroup.Name, Label = TranslateItem(rootGroup.Name), Properties = aggregateProperties, IsActive = false }); } //now add the generic properties tab for any properties that don't belong to a tab var orphanProperties = content.GetNonGroupedProperties() .Where(x => IgnoreProperties.Contains(x.Alias) == false); //don't include ignored props //now add the generic properties tab var genericproperties = Mapper.Map<IEnumerable<Property>, IEnumerable<ContentPropertyDisplay>>(orphanProperties).ToList(); TranslateProperties(genericproperties); aggregateTabs.Add(new Tab<ContentPropertyDisplay> { Id = 0, Label = ui.Text("general", "properties"), Alias = "Generic properties", Properties = genericproperties }); //set the first tab to active aggregateTabs.First().IsActive = true; return aggregateTabs; } private void TranslateProperties(IEnumerable<ContentPropertyDisplay> properties) { // Not sure whether it's a good idea to add this to the ContentPropertyDisplay mapper foreach (var prop in properties) { prop.Label = TranslateItem(prop.Label); prop.Description = TranslateItem(prop.Description); } } // TODO: This should really be centralized and used anywhere globalization applies. internal string TranslateItem(string text) { var cultureDictionary = CultureDictionary; return TranslateItem(text, cultureDictionary); } private static string TranslateItem(string text, ICultureDictionary cultureDictionary) { if (text == null) { return null; } if (text.StartsWith("#") == false) return text; text = text.Substring(1); return cultureDictionary[text].IfNullOrWhiteSpace(text); } private ICultureDictionary CultureDictionary { get { return _cultureDictionary ?? (_cultureDictionary = CreateDictionary()); } } private static ICultureDictionary CreateDictionary() { return CultureDictionaryFactoryResolver.Current.Factory.CreateDictionary(); } } }
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 LunchBox.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .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.Text.RegularExpressions; using Xunit; public class RightToLeftMatchStartAtTests { /* Tested Methods: public static Boolean RightToLeft; public static Match Match(string input, Int32 startat); "aaa" "aaabbb", 3 public static Match Match(string input, Int32 startat); "aaa", "r" "aaabbb", 3 public static Match Match(string input, Int32 startat); "AAA", "i" "aaabbb", 3 */ [Fact] public static void RightToLeftMatchStartAt() { //////////// Global Variables used for all tests String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Regex r; String s; Match m; Match match; String strMatch1 = "aaa"; Int32[] iMatch1 = { 0, 3 } ; String[] strGroup1 = { "aaa" } ; Int32[,] iGroup1 = { { 0, 3 } } ; String[][] strGrpCap1 = new String[1][]; strGrpCap1[0] = new String[] { "aaa" } ; Int32[][] iGrpCap1 = new Int32[1][]; iGrpCap1[0] = new Int32[] { 5, 9, 3, 3 } ; //This is ignored Int32[] iGrpCapCnt1 = { 1, 1 } ; //0 is ignored try { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// // [] public static Boolean RightToLeft; //----------------------------------------------------------------- strLoc = "Loc_498yg"; iCountTestcases++; r = new Regex("aaa"); if (r.RightToLeft) { iCountErrors++; Console.WriteLine("Err_234fsadg! doesnot match"); } // [] public static Boolean RightToLeft //----------------------------------------------------------------- strLoc = "Loc_746tegd"; iCountTestcases++; r = new Regex("aaa", RegexOptions.RightToLeft); if (!r.RightToLeft) { iCountErrors++; Console.WriteLine("Err_452wfdf! doesnot match"); } // [] public static Match Match(string input, Int32 startat); "aaa" //"aaabbb", 3 //----------------------------------------------------------------- strLoc = "Loc_298vy"; iCountTestcases++; s = "aaabbb"; r = new Regex("aaa"); m = r.Match(s, 3); if (m.Success) { iCountErrors++; Console.WriteLine("Err_87543! doesnot match"); } // [] public static Match Match(string input, Int32 startat); "aaa", "r" //"aaabbb", 3 //----------------------------------------------------------------- strLoc = "Loc_563rfg"; iCountTestcases++; s = "aaabbb"; r = new Regex("aaa", RegexOptions.RightToLeft); match = r.Match(s, 3); if (!match.Success) { iCountErrors++; Console.WriteLine("Err_865rfsg! doesnot match"); } else { if (!match.Value.Equals(strMatch1) || (match.Index != iMatch1[0]) || (match.Length != iMatch1[1]) || (match.Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_98275dsg: unexpected return result"); } //Match.Captures always is Match if (!match.Captures[0].Value.Equals(strMatch1) || (match.Captures[0].Index != iMatch1[0]) || (match.Captures[0].Length != iMatch1[1])) { iCountErrors++; Console.WriteLine("Err_2046gsg! unexpected return result"); } if (match.Groups.Count != 1) { iCountErrors++; Console.WriteLine("Err_75324sg! unexpected return result"); } //Group 0 always is the Match if (!match.Groups[0].Value.Equals(strMatch1) || (match.Groups[0].Index != iMatch1[0]) || (match.Groups[0].Length != iMatch1[1]) || (match.Groups[0].Captures.Count != 1)) { iCountErrors++; Console.WriteLine("Err_2046gsg! unexpected return result"); } //Group 0's Capture is always the Match if (!match.Groups[0].Captures[0].Value.Equals(strMatch1) || (match.Groups[0].Captures[0].Index != iMatch1[0]) || (match.Groups[0].Captures[0].Length != iMatch1[1])) { iCountErrors++; Console.WriteLine("Err_2975edg!! unexpected return result"); } for (int i = 1; i < match.Groups.Count; i++) { if (!match.Groups[i].Value.Equals(strGroup1[i]) || (match.Groups[i].Index != iGroup1[i, 0]) || (match.Groups[i].Length != iGroup1[i, 1]) || (match.Groups[i].Captures.Count != iGrpCapCnt1[i])) { iCountErrors++; Console.WriteLine("Err_1954eg_" + i + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>, CaptureCount = <{6}:{7}>", match.Groups[i].Value, match.Groups[i].Index, match.Groups[i].Length, strGroup1[i], iGroup1[i, 0], iGroup1[i, 1], match.Groups[i].Captures.Count, iGrpCapCnt1[i]); } for (int j = 0; j < match.Groups[i].Captures.Count; j++) { if (!match.Groups[i].Captures[j].Value.Equals(strGrpCap1[i][j]) || (match.Groups[i].Captures[j].Index != iGrpCap1[i][j]) || (match.Groups[i].Captures[j].Length != iGrpCap1[i][match.Groups[i].Captures.Count + j])) { iCountErrors++; Console.WriteLine("Err_5072dn_" + i + "_" + j + "! unexpected return result, Value = <{0}:{3}>, Index = <{1}:{4}>, Length = <{2}:{5}>", match.Groups[i].Captures[j].Value, match.Groups[i].Captures[j].Index, match.Groups[i].Captures[j].Length, strGrpCap1[i][j], iGrpCap1[i][j], iGrpCap1[i][match.Groups[i].Captures.Count + j]); } } } } // [] public static Match Match(string input); "AAA", "i" //"aaabbb", 3 //----------------------------------------------------------------- strLoc = "Loc_3452sdg"; iCountTestcases++; s = "aaabbb"; r = new Regex("AAA", RegexOptions.IgnoreCase); m = r.Match(s); if (!m.Success) { iCountErrors++; Console.WriteLine("Err_fsdfxcvz! doesnot match"); } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics Assert.Equal(0, iCountErrors); } }
using UnityEngine; using System.Collections; public class OTScale9Sprite : OTSprite { public enum SideFillType { Scale, Repeat }; public OTScale9Margins _margins = new OTScale9Margins(); // public SideFillType _fillSide = SideFillType.Scale; //----------------------------------------------------------------------------- // public attributes (get/set) //----------------------------------------------------------------------------- /* public SideFillType fillSide { get { return _fillSide; } set { if (value!=_fillSide) { _fillSide = value; meshDirty = true; } } } */ public OTScale9Margins margins { get { return _margins; } set { _margins = value; meshDirty = true; } } private OTScale9Margins _margins_; // private SideFillType _fillSide_ = SideFillType.Scale; Vector3[] verts = new Vector3[]{}; Vector2[] _uv = new Vector2[]{}; int[] tris = new int[]{}; int Scale9Verts(int idx, float yp, float uvp) { int ix = 100; if (image!=null) ix = image.width; float maLeft = (_meshsize_.x * ((margins.left>=1)?(margins.left/ix):margins.left)) * (ix/_size.x) * OT.view.sizeFactor; float maRight = (_meshsize_.x * ((margins.right>=1)?(margins.right/ix):margins.right)) * (ix/_size.x) * OT.view.sizeFactor; float uvLeft = ((margins.left>=1)?(margins.left/ix):margins.left); float uvRight = ((margins.right>=1)?(margins.right/ix):margins.right); _uv[idx] = new Vector2(0, uvp); verts[idx++] = new Vector3(mLeft, yp, 0); _uv[idx] = new Vector2(uvLeft, uvp); verts[idx++] = new Vector3(mLeft + maLeft , yp, 0); _uv[idx] = new Vector2(1-uvRight, uvp); verts[idx++] = new Vector3(mRight - maRight, yp, 0); _uv[idx] = new Vector2(1, uvp); verts[idx++] = new Vector3(mRight, yp, 0); return idx; } int Scale9Face(int idx, int start, int vcount) { tris[idx++] = start; tris[idx++] = start+1; tris[idx++] = start+vcount; tris[idx++] = start+1; tris[idx++] = start+vcount+1; tris[idx++] = start+vcount; return idx; } protected override Mesh GetMesh() { Mesh mesh =InitMesh(); int iy = 100; if (image!=null) iy = image.height; float maTop = (_meshsize_.y * ((margins.top>=1)?(margins.top/iy):margins.top)) * (iy/_size.y)* OT.view.sizeFactor; float maBottom = (_meshsize_.y * ((margins.bottom>=1)?(margins.bottom/iy):margins.bottom)) * (iy/_size.y) * OT.view.sizeFactor; float uvTop = ((margins.top>=1)?(margins.top/iy):margins.top); float uvBottom = ((margins.bottom>=1)?(margins.bottom/iy):margins.bottom); verts = new Vector3[16]; _uv = new Vector2[16]; tris = new int[ 9 * 6 ]; int idx = 0; idx = Scale9Verts(idx, mTop, 1); idx = Scale9Verts(idx, mTop - maTop, 1-uvTop); idx = Scale9Verts(idx, mBottom + maBottom, uvBottom); idx = Scale9Verts(idx, mBottom, 0); idx = 0; idx = Scale9Face(idx,0,4); idx = Scale9Face(idx,1,4); idx = Scale9Face(idx,2,4); idx = Scale9Face(idx,4,4); idx = Scale9Face(idx,5,4); idx = Scale9Face(idx,6,4); idx = Scale9Face(idx,8,4); idx = Scale9Face(idx,9,4); idx = Scale9Face(idx,10,4); mesh.vertices = verts; mesh.uv = _uv; mesh.triangles = tris; mesh.RecalculateBounds(); mesh.RecalculateNormals(); return mesh; } //----------------------------------------------------------------------------- // overridden subclass methods //----------------------------------------------------------------------------- protected override void CheckSettings() { Vector2 loc = otTransform.localScale; if (!_size.Equals(_size_) || !_size.Equals(loc)) meshDirty = true; base.CheckSettings(); if (MarginsChanged() /* || _fillSide != _fillSide_ */ ) { meshDirty = true; _margins_ = _margins; // _fillSide_ = _fillSide; } } protected override string GetTypeName() { return "Scale9"; } protected override void HandleUV() { if (spriteContainer != null && spriteContainer.isReady) { OTContainer.Frame frame = spriteContainer.GetFrame(frameIndex); // adjust this sprites UV coords if (frame.uv != null && mesh != null) { // splice UV that we got from the container. mesh.uv = frame.uv; } } } protected override void Clean() { base.Clean(); } //----------------------------------------------------------------------------- // class methods //----------------------------------------------------------------------------- bool MarginsChanged() { return (!margins.Equals(_margins_)); } protected override void Awake() { base.Awake(); _margins_ = _margins; // _fillSide_ = _fillSide; } public void Rebuild() { meshDirty = true; } new void Start() { base.Start(); } // Update is called once per frame new void Update() { base.Update(); } } [System.Serializable] public class OTScale9Margins { public float top = 25; public float bottom = 25; public float left = 25; public float right = 25; public bool Equals(OTScale9Margins other) { return (top==other.top && bottom == other.bottom && left == other.left && right == other.right); } }
using System; using System.Collections.Generic; using System.Linq; using InAudioSystem.ExtensionMethods; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; using InAudioSystem.InAudioEditor; namespace InAudioSystem.InAudioEditor { public static class AudioEventWorker { private static InAudioEventNode CreateRoot(GameObject go, int guid) { var node = go.AddComponentUndo<InAudioEventNode>(); node._type = EventNodeType.Root; node._guid = guid; node.EditorSettings.IsFoldedOut = true; node.Name = "Event Root"; return node; } private static InAudioEventNode CreateFolder(GameObject go, int guid, InAudioEventNode parent) { var node = go.AddComponentUndo<InAudioEventNode>(); node._type = EventNodeType.Folder; node._guid = guid; node.Name = parent.Name + " Child"; node.AssignParent(parent); return node; } public static void DeleteNodeNoGroup(InAudioEventNode node) { InUndoHelper.RegisterUndo(node._parent, "Event Deletion"); node._parent._children.Remove(node); DeleteNodeRec(node); } public static void DeleteNode(InAudioEventNode node) { InUndoHelper.DoInGroup(() => { InUndoHelper.RegisterUndo(node._parent, "Event Deletion"); node._parent._children.Remove(node); DeleteNodeRec(node); }); } private static void DeleteNodeRec(InAudioEventNode node) { for (int i = 0; i < node._actionList.Count; i++) { InUndoHelper.Destroy(node._actionList[i]); } for (int i = 0; i < node._children.Count; ++i) { DeleteNodeRec(node._children[i]); } InUndoHelper.Destroy(node); } private static InAudioEventNode CreateEvent(GameObject go, InAudioEventNode parent, int guid, EventNodeType type) { var node = go.AddComponentUndo<InAudioEventNode>(); node._type = type; node._guid = guid; node.Name = parent.Name + " Child"; InUndoHelper.RecordObject(parent, "Parrent asign"); node.AssignParent(parent); return node; } public static InAudioEventNode CreateTree(GameObject go, int levelSize) { var tree = CreateRoot(go, GUIDCreator.Create()); for (int i = 0; i < levelSize; ++i) { var eventNode = CreateFolder(go, GUIDCreator.Create(), tree); eventNode.Name = "Event Folder " + i; } return tree; } public static InAudioEventNode CreateNode(InAudioEventNode parent, EventNodeType type, string name) { var node = CreateNode(parent, type); node.Name = name; return node; } public static InAudioEventNode CreateNode(InAudioEventNode parent, EventNodeType type) { var child = CreateEvent(parent.gameObject, parent, GUIDCreator.Create(), type); child.EditorSettings.IsFoldedOut = true; return child; } public static InAudioEventNode CreateNode(InAudioEventNode parent, GameObject go, EventNodeType type) { var child = CreateEvent(go, parent, GUIDCreator.Create(), type); child.EditorSettings.IsFoldedOut = true; return child; } public static void ReplaceActionDestructiveAt(InAudioEventNode audioEvent, EventActionTypes enumType, int toRemoveAndInsertAt) { //A reel mess this function. //It adds a new component of the specied type, replaces the current at the toRemoveAndInsertAt index, and then deletes the old one float delay = audioEvent._actionList[toRemoveAndInsertAt].Delay; Object target = audioEvent._actionList[toRemoveAndInsertAt].Target; var newActionType = AudioEventAction.ActionEnumToType(enumType); InUndoHelper.Destroy(audioEvent._actionList[toRemoveAndInsertAt]); //UndoHelper.RecordObject(audioEvent, "Event Action Creation"); audioEvent._actionList.RemoveAt(toRemoveAndInsertAt); var added = AddEventAction(audioEvent, newActionType, enumType); added.Delay = delay; added.Target = target; //Attempt to set the new value, will only work if it is the same type audioEvent._actionList.Insert(toRemoveAndInsertAt, added); audioEvent._actionList.RemoveLast(); } public static T AddEventAction<T>(InAudioEventNode audioevent, EventActionTypes enumType) where T : AudioEventAction { var eventAction = audioevent.gameObject.AddComponentUndo<T>(); audioevent._actionList.Add(eventAction); eventAction._eventActionType = enumType; return eventAction; } public static AudioEventAction AddEventAction(InAudioEventNode audioevent, Type eventActionType, EventActionTypes enumType) { InUndoHelper.RecordObject(audioevent, "Event Action Creation"); var eventAction = audioevent.gameObject.AddComponentUndo(eventActionType) as AudioEventAction; audioevent._actionList.Add(eventAction); eventAction._eventActionType = enumType; return eventAction; } public static InAudioEventNode DeleteActionAtIndex(InAudioEventNode audioevent, int index) { InUndoHelper.RecordObject(audioevent, "Event Action Creation"); InUndoHelper.Destroy(audioevent._actionList[index]); audioevent._actionList.RemoveAt(index); return audioevent; } public static InAudioEventNode CopyTo(InAudioEventNode audioEvent, InAudioEventNode newParent) { return NodeWorker.DuplicateHierarchy(audioEvent, newParent, newParent.gameObject, (@oldNode, newNode) => { newNode._actionList.Clear(); for (int i = 0; i < oldNode._actionList.Count; i++) { newNode._actionList.Add(NodeWorker.CopyComponent(oldNode._actionList[i])); } }); } public static InAudioEventNode Duplicate(InAudioEventNode audioEvent) { return NodeWorker.DuplicateHierarchy(audioEvent, (@oldNode, newNode) => { newNode._actionList.Clear(); for (int i = 0; i < oldNode._actionList.Count; i++) { newNode._actionList.Add(NodeWorker.CopyComponent(oldNode._actionList[i])); } }); } public static bool CanDropObjects(InAudioEventNode audioEvent, Object[] objects) { if (objects.Length == 0 || audioEvent == null) return false; if (audioEvent._type == EventNodeType.Event) { var nonEventDrop = CanDropNonEvent(objects); return nonEventDrop; } else if (audioEvent._type == EventNodeType.Folder || audioEvent._type == EventNodeType.Root) { var draggingEvent = objects[0] as InAudioEventNode; if (draggingEvent != null) { if (draggingEvent._type == EventNodeType.Event) return true; if ((draggingEvent._type == EventNodeType.Folder && !NodeWorker.IsChildOf(draggingEvent, audioEvent)) || draggingEvent._type == EventNodeType.EventGroup) return true; } else { var nonEventDrop = CanDropNonEvent(objects) && !audioEvent.IsRootOrFolder; return nonEventDrop; } } else if (audioEvent._type == EventNodeType.EventGroup) { var draggingEvent = objects[0] as InAudioEventNode; if (draggingEvent == null) return false; if (draggingEvent._type == EventNodeType.Event) return true; } return false; } private static bool CanDropNonEvent(Object[] objects) { var audioNodes = GetConvertedList<InAudioNode>(objects.ToList()); bool audioNodeDrop = audioNodes.TrueForAll(node => node != null && node.IsPlayable); var musicLinks = GetConvertedList<InMusicGroup>(objects.ToList()); bool musicDrop = musicLinks.TrueForAll(node => node != null && node._type == MusicNodeType.Music); return audioNodeDrop | musicDrop; } private static List<T> GetConvertedList<T>(List<Object> toConvert) where T : class { return toConvert.ConvertAll(obj => obj as T); } public static bool OnDrop(InAudioEventNode audioevent, Object[] objects) { InUndoHelper.DoInGroup(() => { //if (audioevent.Type == EventNodeType.Folder) //{ // UndoHelper.RecordObjectInOld(audioevent, "Created event"); // audioevent = CreateNode(audioevent, EventNodeType.Event); //} if (objects[0] as InAudioEventNode) { var movingEvent = objects[0] as InAudioEventNode; if (movingEvent.gameObject != audioevent.gameObject) { if (EditorUtility.DisplayDialog("Move?", "Warning, this will break all external references to this and all child nodes!\n" + "Move node from\"" + movingEvent.gameObject.name + "\" to \"" + audioevent.gameObject.name + "\"?", "Ok", "Cancel")) { InUndoHelper.DoInGroup(() => { CopyTo(movingEvent, audioevent); DeleteNodeNoGroup(movingEvent); }); } } else { InUndoHelper.RecordObjectFull(new Object[] { audioevent, movingEvent, movingEvent._parent }, "Event Move"); NodeWorker.ReasignNodeParent(movingEvent, audioevent); audioevent.EditorSettings.IsFoldedOut = true; } } var audioNode = objects[0] as InAudioNode; if (audioNode != null && audioNode.IsPlayable) { InUndoHelper.RecordObjectFull(audioevent, "Adding of Audio Action"); var action = AddEventAction<InEventAudioAction>(audioevent, EventActionTypes.Play); action.Node = audioNode; } var musicGroup = objects[0] as InMusicGroup; if (musicGroup != null) { InUndoHelper.RecordObjectFull(audioevent, "Adding of Music Action"); var action = AddEventAction<InEventMusicControl>(audioevent, EventActionTypes.PlayMusic); action.MusicGroup = musicGroup; } Event.current.UseEvent(); }); return true; } } }
using System; using System.Collections.Generic; using Palaso.WritingSystems.Collation; namespace Palaso.WritingSystems { public interface IWritingSystemDefinition { /// <summary> /// True when the validity of the writing system defn's tag is being enforced. This is the normal and default state. /// Setting this true will throw unless the tag has previously been put into a valid state. /// Attempting to Save the writing system defn will set this true (and may throw). /// </summary> bool RequiresValidTag { get; set; } ///<summary> ///This is the version of the locale data contained in this writing system. ///This should not be confused with the version of our writingsystemDefinition implementation which is mostly used for migration purposes. ///That information is stored in the "LatestWritingSystemDefinitionVersion" property. ///</summary> string VersionNumber { get; set; } string VersionDescription { get; set; } DateTime DateModified { get; set; } IEnumerable<Iso639LanguageCode> ValidLanguages { get; } IEnumerable<Iso15924Script> ValidScript { get; } IEnumerable<IanaSubtag> ValidRegions { get; } IEnumerable<IanaSubtag> ValidVariants { get; } /// <summary> /// Adjusts the BCP47 tag to indicate the desired form of Ipa by inserting fonipa in the variant and emic or etic in private use where necessary. /// </summary> IpaStatusChoices IpaStatus { get; set; } /// <summary> /// Adjusts the BCP47 tag to indicate that this is an "audio writing system" by inserting "audio" in the private use and "Zxxx" in the script /// </summary> bool IsVoice { get; set; } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// Note that the variant also includes the private use subtags. These are appended to the variant subtags seperated by "-x-" /// Also note the convenience methods "SplitVariantAndPrivateUse" and "ConcatenateVariantAndPrivateUse" for easier /// variant/ private use handling /// </summary> // Todo: this could/should become an ordered list of variant tags string Variant { get; set; } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// </summary> string Region { get; set; } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// </summary> string Language { get; set; } /// <summary> /// The desired abbreviation for the writing system /// </summary> string Abbreviation { get; set; } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// </summary> string Script { get; set; } /// <summary> /// The language name to use. Typically this is the language name associated with the BCP47 language subtag as defined by the IANA subtag registry /// </summary> string LanguageName { get; set; } /// <summary> /// Used by IWritingSystemRepository to identify writing systems. Only change this if you would like to replace a writing system with the same StoreId /// already contained in the repo. This is useful creating a temporary copy of a writing system that you may or may not care to persist to the /// IWritingSystemRepository. /// Typical use would therefor be: /// ws.Clone(wsorig); /// ws.StoreId=wsOrig.StoreId; /// **make changes to ws** /// repo.Set(ws); /// </summary> string StoreID { get; set; } /// <summary> /// A automatically generated descriptive label for the writing system definition. /// </summary> string DisplayLabel { get; } string ListLabel { get; } /// <summary> /// The current BCP47 tag which is a concatenation of the Language, Script, Region and Variant properties. /// </summary> string Bcp47Tag { get; } /// <summary> /// The identifier for this writing system definition. Use this in files and as a key to the IWritingSystemRepository. /// Note that this is usually identical to the Bcp47 tag and should rarely differ. /// </summary> /// <remarks> /// StoreID is the actual key for IWritingSystemRepository methods. It is usually the same as Id, but not always. /// </remarks> string Id { get; } /// <summary> /// Indicates whether the writing system definition has been modified. /// Note that this flag is automatically set by all methods that cause a modification and is reset by the IwritingSystemRepository.Save() method /// </summary> bool Modified { get; set; } bool MarkedForDeletion { get; set; } /// <summary> /// The font used to display data encoded in this writing system /// </summary> string DefaultFontName { get; set; } /// <summary> /// the preferred font size to use for data encoded in this writing system. /// </summary> float DefaultFontSize { get; set; } /// <summary> /// This tracks the keyboard that should be used for this writing system on this computer. /// It is not shared with other users of the project. /// </summary> IKeyboardDefinition LocalKeyboard { get; set; } /// <summary> /// Keyboards known to have been used with this writing system. Not all may be available on this system. /// Enhance: document (or add to this interface?) a way of getting available keyboards. /// </summary> IEnumerable<IKeyboardDefinition> KnownKeyboards { get; } /// <summary> /// Note that a new keyboard is known to be used for this writing system. /// </summary> /// <param name="newKeyboard"></param> void AddKnownKeyboard(IKeyboardDefinition newKeyboard); /// <summary> /// Returns the available keyboards (known to Keyboard.Controller) that are not KnownKeyboards for this writing system. /// </summary> IEnumerable<IKeyboardDefinition> OtherAvailableKeyboards { get; } /// <summary> /// Indicates whether this writing system is read and written from left to right or right to left /// </summary> bool RightToLeftScript { get; set; } /// <summary> /// The windows "NativeName" from the Culture class /// </summary> string NativeName { get; set; } /// <summary> /// Indicates the type of sort rules used to encode the sort order. /// Note that the actual sort rules are contained in the SortRules property /// </summary> WritingSystemDefinition.SortRulesType SortUsing { get; set; } /// <summary> /// The sort rules that efine the sort order. /// Note that you must indicate the type of sort rules used by setting the "SortUsing" property /// </summary> string SortRules { get; set; } /// <summary> /// The id used to select the spell checker. /// </summary> string SpellCheckingId { get; set; } /// <summary> /// Returns an ICollator interface that can be used to sort strings based /// on the custom collation rules. /// </summary> ICollator Collator { get; } /// <summary> /// Indicates whether this writing system is unicode encoded or legacy encoded /// </summary> bool IsUnicodeEncoded { get; set; } /// <summary> /// Adds a valid BCP47 registered variant subtag to the variant. Any other tag is inserted as private use. /// </summary> /// <param name="registeredVariantOrPrivateUseSubtag">A valid variant tag or another tag which will be inserted into private use.</param> void AddToVariant(string registeredVariantOrPrivateUseSubtag); /// <summary> /// Sets all BCP47 language tag components at once. /// This method is useful for avoiding invalid intermediate states when switching from one valid tag to another. /// </summary> /// <param name="language">A valid BCP47 language subtag.</param> /// <param name="script">A valid BCP47 script subtag.</param> /// <param name="region">A valid BCP47 region subtag.</param> /// <param name="variant">A valid BCP47 variant subtag.</param> void SetAllComponents(string language, string script, string region, string variant); /// <summary> /// enforcing a minimum on _defaultFontSize, while reasonable, just messed up too many IO unit tests /// </summary> /// <returns></returns> float GetDefaultFontSizeOrMinimum(); /// <summary> /// A convenience method for sorting like anthoer language /// </summary> /// <param name="languageCode">A valid language code</param> void SortUsingOtherLanguage(string languageCode); /// <summary> /// A convenience method for sorting with custom ICU rules /// </summary> /// <param name="sortRules">custom ICU sortrules</param> void SortUsingCustomICU(string sortRules); /// <summary> /// A convenience method for sorting with "shoebox" style rules /// </summary> /// <param name="sortRules">"shoebox" style rules</param> void SortUsingCustomSimple(string sortRules); /// <summary> /// Tests whether the current custom collation rules are valid. /// </summary> /// <param name="message">Used for an error message if rules do not validate.</param> /// <returns>True if rules are valid, false otherwise.</returns> bool ValidateCollationRules(out string message); string ToString(); /// <summary> /// Creates a clone of the current writing system. /// Note that this excludes the properties: Modified, MarkedForDeletion and StoreID /// </summary> /// <returns></returns> WritingSystemDefinition Clone(); bool Equals(Object obj); bool Equals(WritingSystemDefinition other); /// <summary> /// Parses the supplied BCP47 tag and sets the Language, Script, Region and Variant properties accordingly /// </summary> /// <param name="completeTag">A valid BCP47 tag</param> void SetTagFromString(string completeTag); } /// <summary> /// An additional interface that is typically implemented along with IWritingSystemDefinition. This interface gives access to two pieces of /// information which may be present in an older LDML file, especially one which does not have KnownKeyboards, and which may be used /// to determine a keyboard to be used when KnownKeyboards and LocalKeyboard are not set. /// </summary> public interface ILegacyWritingSystemDefinition { /// <summary> /// This field retrieves the value obtained from the FieldWorks LDML extension fw:windowsLCID. /// This is used only when current information in LocalKeyboard or KnownKeyboards is not useable. /// It is not useful to modify this or set it in new LDML files; however, we need a public setter /// because FieldWorks overrides the code that normally reads this from the LDML file. /// </summary> string WindowsLcid { get; set; } /// <summary> /// Legacy keyboard information. Current code should use LocalKeyboard or KnownKeyboards. /// This field is kept because it is useful in figuring out a keyboard to use when importing an old LDML file. /// </summary> string Keyboard { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Serialization; using Microsoft.VisualStudio.TestTools.UnitTesting; using Nmap.Internal; using Testing.Common; namespace Nmap.Testing { [TestClass] public partial class MapperTesting { private sealed class MapperTester : Mapper<MapperTesting.MapperTester> { } private sealed class CustomMappingContext : MappingContext { public string Data { get; set; } } private MainEntityModel[] ActMapping(MainEntity entity, MappingContext context) { var mainEntityModel = Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel>(entity, context); var mainEntityModel2 = Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel>(entity, new MainEntityModel(), context); var mainEntityModel3 = Mapper<MapperTesting.MapperTester>.Instance.Map(entity, typeof(MainEntityModel), context) as MainEntityModel; return new MainEntityModel[] { mainEntityModel, mainEntityModel2, mainEntityModel3 }; } private IEnumerable<MainEntityModel>[] ActEnumerableMapping(MainEntity[] entities, MappingContext context) { var enumerable = Mapper<MapperTesting.MapperTester>.Instance.Map<IEnumerable<MainEntityModel>>(entities, context); var array = Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel[]>(entities, context); var list = Mapper<MapperTesting.MapperTester>.Instance.Map<List<MainEntityModel>>(entities, new List<MainEntityModel>(), context); var array2 = Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel[]>(entities, new MainEntityModel[2], context); var enumerable2 = Mapper<MapperTesting.MapperTester>.Instance.Map(entities, typeof(List<MainEntityModel>), context) as IEnumerable<MainEntityModel>; var enumerable3 = Mapper<MapperTesting.MapperTester>.Instance.Map(entities, typeof(MainEntityModel[]), context) as IEnumerable<MainEntityModel>; return new IEnumerable<MainEntityModel>[] { enumerable, array, list, array2, enumerable2, enumerable3 }; } private MainEntity[] ActUnmapping(MainEntity entity, MappingContext context) { var mainEntity = Mapper<MapperTesting.MapperTester>.Instance.Unmap<MainEntity>( Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel>(entity, context), context); var mainEntity2 = Mapper<MapperTesting.MapperTester>.Instance.Unmap<MainEntity>( Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel>(entity, new MainEntityModel(), context), new MainEntity(), context); var mainEntity3 = Mapper<MapperTesting.MapperTester>.Instance.Unmap( Mapper<MapperTesting.MapperTester>.Instance.Map(entity, typeof(MainEntityModel), context), typeof(MainEntity), context) as MainEntity; return new MainEntity[] { mainEntity, mainEntity2, mainEntity3 }; } private IEnumerable<MainEntity>[] ActEnumerableUnmapping(MainEntity[] entities, MappingContext context) { var array = Mapper<MapperTesting.MapperTester>.Instance.Unmap<MainEntity[]>( Mapper<MapperTesting.MapperTester>.Instance.Map<IEnumerable<MainEntityModel>>(entities, context), context); var array2 = Mapper<MapperTesting.MapperTester>.Instance.Unmap<MainEntity[]>( Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel[]>(entities, context), context); var array3 = Mapper<MapperTesting.MapperTester>.Instance.Unmap<MainEntity[]>( Mapper<MapperTesting.MapperTester>.Instance.Map<List<MainEntityModel>>(entities, new List<MainEntityModel>(), context), new MainEntity[2], context); var array4 = Mapper<MapperTesting.MapperTester>.Instance.Unmap<MainEntity[]>( Mapper<MapperTesting.MapperTester>.Instance.Map<MainEntityModel[]>( entities, new MainEntityModel[2], context), new MainEntity[2], context); var array5 = Mapper<MapperTesting.MapperTester>.Instance.Unmap( Mapper<MapperTesting.MapperTester>.Instance.Map(entities, typeof(List<MainEntityModel>), context), typeof(MainEntity[]), context) as MainEntity[]; var array6 = Mapper<MapperTesting.MapperTester>.Instance.Unmap(Mapper<MapperTesting.MapperTester> .Instance.Map(entities, typeof(MainEntityModel[]), context), typeof(MainEntity[]), context) as MainEntity[]; return new IEnumerable<MainEntity>[] { array, array2, array3, array4, array5, array6 }; } private void AssertEntity(Entity expected, Entity actual) { var xmlSerializer = new XmlSerializer(expected.GetType(), new Type[] { typeof(DerivedMainEntity), typeof(DerivedSubEntity), typeof(DerivedSubSubEntity) }); var memoryStream = new MemoryStream(); xmlSerializer.Serialize(memoryStream, expected); memoryStream.Seek(0L, SeekOrigin.Begin); string expected2 = new StreamReader(memoryStream).ReadToEnd(); memoryStream.Close(); xmlSerializer = new XmlSerializer(actual.GetType(), new Type[] { typeof(DerivedMainEntity), typeof(DerivedSubEntity), typeof(DerivedSubSubEntity) }); memoryStream = new MemoryStream(); xmlSerializer.Serialize(memoryStream, actual); memoryStream.Seek(0L, SeekOrigin.Begin); string actual2 = new StreamReader(memoryStream).ReadToEnd(); memoryStream.Close(); Assert.AreEqual<string>(expected2, actual2); } private void AssertEntityModel(Entity entity, EntityModel model) { Type type = model.GetType(); var properties = entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < properties.Length; i++) { var propertyInfo = properties[i]; var property = type.GetProperty("Entity" + propertyInfo.Name); if (property == null) { property = type.GetProperty(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public); } if (propertyInfo.GetValue(entity, null) == null) { Assert.IsNull(property.GetValue(model, null)); } else { if (ReflectionHelper.IsSimple(propertyInfo.PropertyType)) { Assert.AreEqual<string>(propertyInfo.GetValue(entity, null).ToString(), property.GetValue(model, null).ToString()); } else { if (ReflectionHelper.IsSimpleEnumerable(propertyInfo.PropertyType)) { object[] array = ((IEnumerable)propertyInfo.GetValue(entity, null)).Cast<object>().ToArray<object>(); object[] array2 = ((IEnumerable)property.GetValue(model, null)).Cast<object>().ToArray<object>(); Assert.AreEqual<int>(array.Length, array2.Length); for (int j = 0; j < array.Length; j++) { Assert.AreEqual<string>(array[j].ToString(), array2[j].ToString()); } } else { if (ReflectionHelper.IsComplex(propertyInfo.PropertyType)) { AssertEntityModel(propertyInfo.GetValue(entity, null) as Entity, property.GetValue(model, null) as EntityModel); } else { if (ReflectionHelper.IsComplexEnumerable(propertyInfo.PropertyType)) { var list = ((IEnumerable)propertyInfo.GetValue(entity, null)).Cast<object>().ToList<object>(); var list2 = ((IEnumerable)property.GetValue(model, null)).Cast<object>().ToList<object>(); Assert.AreEqual<int>(list.Count, list2.Count); for (int j = 0; j < list.Count; j++) { if (list[j] == null) { Assert.IsNull(list2[j]); } AssertEntityModel(list[j] as Entity, list2[j] as EntityModel); } } } } } } } } private void AssertSimpleFlattenedEntityModel(Entity entity, object model, string contextualName) { Type type = model.GetType(); var properties = entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < properties.Length; i++) { var propertyInfo = properties[i]; var property = type.GetProperty("Entity" + contextualName + propertyInfo.Name); if (property == null) { property = type.GetProperty(contextualName + propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public); } if (property != null && propertyInfo.GetValue(entity, null) == null) { Assert.IsNull(property.GetValue(model, null)); } else { if (ReflectionHelper.IsSimple(propertyInfo.PropertyType)) { Assert.AreEqual<string>(propertyInfo.GetValue(entity, null).ToString(), property.GetValue(model, null).ToString()); } else { if (ReflectionHelper.IsSimpleEnumerable(propertyInfo.PropertyType)) { object[] array = ((IEnumerable)propertyInfo.GetValue(entity, null)).Cast<object>().ToArray<object>(); object[] array2 = ((IEnumerable)property.GetValue(model, null)).Cast<object>().ToArray<object>(); Assert.AreEqual<int>(array.Length, array2.Length); for (int j = 0; j < array.Length; j++) { Assert.AreEqual<string>(array[j].ToString(), array2[j].ToString()); } } } } } } [TestInitialize] public void TestInitialize() { Mapper<MapperTesting.MapperTester>.Instance.ClearMaps(); Mapper<MapperTesting.MapperTester>.Instance.ClearConverters(); Mapper<MapperTesting.MapperTester>.Instance.SetObjectFactory(new ObjectFactory()); Mapper<MapperTesting.MapperTester>.Instance.Setup(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Numerics; using Xunit; namespace Tools { public class StackCalc { public string[] input; public Stack<BigInteger> myCalc; public Stack<BigInteger> snCalc; public Queue<string> operators; private BigInteger _snOut = 0; private BigInteger _myOut = 0; public StackCalc(string _input) { myCalc = new Stack<System.Numerics.BigInteger>(); snCalc = new Stack<System.Numerics.BigInteger>(); string delimStr = " "; char[] delimiter = delimStr.ToCharArray(); input = _input.Split(delimiter); operators = new Queue<string>(input); } public bool DoNextOperation() { string op = ""; bool ret = false; bool checkValues = false; BigInteger snnum1 = 0; BigInteger snnum2 = 0; BigInteger snnum3 = 0; BigInteger mynum1 = 0; BigInteger mynum2 = 0; BigInteger mynum3 = 0; if (operators.Count == 0) { return false; } op = operators.Dequeue(); if (op.StartsWith("u")) { checkValues = true; snnum1 = snCalc.Pop(); snCalc.Push(DoUnaryOperatorSN(snnum1, op)); mynum1 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoUnaryOperatorMine(mynum1, op)); ret = true; } else if (op.StartsWith("b")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snCalc.Push(DoBinaryOperatorSN(snnum1, snnum2, op)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoBinaryOperatorMine(mynum1, mynum2, op)); ret = true; } else if (op.StartsWith("t")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snnum3 = snCalc.Pop(); snCalc.Push(DoTertanaryOperatorSN(snnum1, snnum2, snnum3, op)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); mynum3 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoTertanaryOperatorMine(mynum1, mynum2, mynum3, op)); ret = true; } else { if (op.Equals("make")) { snnum1 = DoConstruction(); snCalc.Push(snnum1); myCalc.Push(snnum1); } else if (op.Equals("Corruption")) { snCalc.Push(-33); myCalc.Push(-555); } else if (BigInteger.TryParse(op, out snnum1)) { snCalc.Push(snnum1); myCalc.Push(snnum1); } else { Console.WriteLine("Failed to parse string {0}", op); } ret = true; } if (checkValues) { if ((snnum1 != mynum1) || (snnum2 != mynum2) || (snnum3 != mynum3)) { operators.Enqueue("Corruption"); } } return ret; } private BigInteger DoConstruction() { List<byte> bytes = new List<byte>(); BigInteger ret = new BigInteger(0); string op = operators.Dequeue(); while (String.CompareOrdinal(op, "endmake") != 0) { bytes.Add(byte.Parse(op)); op = operators.Dequeue(); } try { ret = new BigInteger(bytes.ToArray()); } catch (IndexOutOfRangeException) { Assert.True(false, Print(bytes.ToArray())); throw; } return ret; } private BigInteger DoUnaryOperatorSN(BigInteger num1, string op) { switch (op) { case "uSign": return new BigInteger(num1.Sign); case "u~": return (~(num1)); case "uLog10": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(num1)); case "uLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1)); case "uAbs": return BigInteger.Abs(num1); case "uNegate": return BigInteger.Negate(num1); case "u--": return (--(num1)); case "u++": return (++(num1)); case "u-": return (-(num1)); case "u+": return (+(num1)); case "uMultiply": return BigInteger.Multiply(num1, num1); case "u*": return num1 * num1; default: Assert.True(false, String.Format("Invalid operation found: {0}", op)); break; } return new BigInteger(); } private BigInteger DoBinaryOperatorSN(BigInteger num1, BigInteger num2, string op) { switch (op) { case "bMin": return BigInteger.Min(num1, num2); case "bMax": return BigInteger.Max(num1, num2); case "b>>": return num1 >> (int)num2; case "b<<": return num1 << (int)num2; case "b^": return num1 ^ num2; case "b|": return num1 | num2; case "b&": return num1 & num2; case "b%": return num1 % num2; case "b/": return num1 / num2; case "b*": return num1 * num2; case "b-": return num1 - num2; case "b+": return num1 + num2; case "bLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1, (double)num2)); case "bGCD": return BigInteger.GreatestCommonDivisor(num1, num2); case "bPow": int arg2 = (int)num2; return BigInteger.Pow(num1, arg2); case "bDivRem": BigInteger num3; BigInteger ret = BigInteger.DivRem(num1, num2, out num3); SetSNOutCheck(num3); return ret; case "bRemainder": return BigInteger.Remainder(num1, num2); case "bDivide": return BigInteger.Divide(num1, num2); case "bMultiply": return BigInteger.Multiply(num1, num2); case "bSubtract": return BigInteger.Subtract(num1, num2); case "bAdd": return BigInteger.Add(num1, num2); default: Assert.True(false, String.Format("Invalid operation found: {0}", op)); break; } return new BigInteger(); } private BigInteger DoTertanaryOperatorSN(BigInteger num1, BigInteger num2, BigInteger num3, string op) { switch (op) { case "tModPow": return BigInteger.ModPow(num1, num2, num3); default: Assert.True(false, String.Format("Invalid operation found: {0}", op)); break; } return new BigInteger(); } private void SetSNOutCheck(BigInteger value) { _snOut = value; } public void VerifyOutParameter() { Assert.True(_snOut == MyBigIntImp.outParam, "Out parameters not matching"); _snOut = 0; MyBigIntImp.outParam = 0; } private static String Print(byte[] bytes) { return MyBigIntImp.PrintFormatX(bytes); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Settings; using osu.Game.Rulesets; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osuTK; namespace osu.Game.Tournament.Screens.Editors { public class RoundEditorScreen : TournamentEditorScreen<RoundEditorScreen.RoundRow, TournamentRound> { protected override BindableList<TournamentRound> Storage => LadderInfo.Rounds; public class RoundRow : CompositeDrawable, IModelBacked<TournamentRound> { public TournamentRound Model { get; } [Resolved] private LadderInfo ladderInfo { get; set; } public RoundRow(TournamentRound round) { Model = round; Masking = true; CornerRadius = 10; RoundBeatmapEditor beatmapEditor = new RoundBeatmapEditor(round) { Width = 0.95f }; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.1f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Full, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SettingsTextBox { LabelText = "Name", Width = 0.33f, Current = Model.Name }, new SettingsTextBox { LabelText = "Description", Width = 0.33f, Current = Model.Description }, new DateTextBox { LabelText = "Start Time", Width = 0.33f, Current = Model.StartDate }, new SettingsSlider<int> { LabelText = "Best of", Width = 0.33f, Current = Model.BestOf }, new SettingsButton { Width = 0.2f, Margin = new MarginPadding(10), Text = "Add beatmap", Action = () => beatmapEditor.CreateNew() }, beatmapEditor } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Round", Action = () => { Expire(); ladderInfo.Rounds.Remove(Model); }, } }; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } public class RoundBeatmapEditor : CompositeDrawable { private readonly TournamentRound round; private readonly FillFlowContainer flow; public RoundBeatmapEditor(TournamentRound round) { this.round = round; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = flow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, ChildrenEnumerable = round.Beatmaps.Select(p => new RoundBeatmapRow(round, p)) }; } public void CreateNew() { var user = new RoundBeatmap(); round.Beatmaps.Add(user); flow.Add(new RoundBeatmapRow(round, user)); } public class RoundBeatmapRow : CompositeDrawable { public RoundBeatmap Model { get; } [Resolved] protected IAPIProvider API { get; private set; } private readonly Bindable<int?> beatmapId = new Bindable<int?>(); private readonly Bindable<string> mods = new Bindable<string>(string.Empty); private readonly Container drawableContainer; public RoundBeatmapRow(TournamentRound team, RoundBeatmap beatmap) { Model = beatmap; Margin = new MarginPadding(10); RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.2f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsNumberBox { LabelText = "Beatmap ID", RelativeSizeAxes = Axes.None, Width = 200, Current = beatmapId, }, new SettingsTextBox { LabelText = "Mods", RelativeSizeAxes = Axes.None, Width = 200, Current = mods, }, drawableContainer = new Container { Size = new Vector2(100, 70), }, } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Beatmap", Action = () => { Expire(); team.Beatmaps.Remove(beatmap); }, } }; } [BackgroundDependencyLoader] private void load(RulesetStore rulesets) { beatmapId.Value = Model.ID; beatmapId.BindValueChanged(id => { Model.ID = id.NewValue ?? 0; if (id.NewValue != id.OldValue) Model.BeatmapInfo = null; if (Model.BeatmapInfo != null) { updatePanel(); return; } var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = Model.ID }); req.Success += res => { Model.BeatmapInfo = res.ToBeatmapInfo(rulesets); updatePanel(); }; req.Failure += _ => { Model.BeatmapInfo = null; updatePanel(); }; API.Queue(req); }, true); mods.Value = Model.Mods; mods.BindValueChanged(modString => Model.Mods = modString.NewValue); } private void updatePanel() { drawableContainer.Clear(); if (Model.BeatmapInfo != null) { drawableContainer.Child = new TournamentBeatmapPanel(Model.BeatmapInfo, Model.Mods) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 300 }; } } } } } protected override RoundRow CreateDrawable(TournamentRound model) => new RoundRow(model); } }
using GerberLibrary.Core; using GerberLibrary.Core.Primitives; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GerberLibrary { public class ExcellonTool { public int ID; public double Radius; public List<PointD> Drills = new List<PointD>(); public class SlotInfo { public PointD Start = new PointD(); public PointD End = new PointD(); public override string ToString() { return $"({Start.X:N2},{Start.Y:N2})-({End.X:N2},{End.X:N2})"; } } public List<SlotInfo> Slots = new List<SlotInfo>(); }; public class ExcellonFile { public void Load(ProgressLog log, string filename, double drillscaler = 1.0) { var Load = log.PushActivity("Loading Excellon"); var lines = File.ReadAllLines(filename); ParseExcellon(lines.ToList(), drillscaler,log); log.PopActivity(Load); } public void Load(ProgressLog log, StreamReader stream, double drillscaler = 1.0) { List<string> lines = new List<string>(); while (!stream.EndOfStream) { lines.Add(stream.ReadLine()); } ParseExcellon(lines, drillscaler, log); } public static void MergeAll(List<string> Files, string output, ProgressLog Log) { var LogDepth = Log.PushActivity("Excellon MergeAll"); if (Files.Count >= 2) { MultiMerge(Files[0], Files.Skip(1).ToList(), output, Log); Log.PopActivity(LogDepth); return; } if (Files.Count < 2) { if (Files.Count == 1) { Log.AddString("Merging 1 file is copying... doing so..."); if (File.Exists(output)) File.Delete(output); File.Copy(Files[0], output); } else { Log.AddString("Need files to do anything??"); } Log.PopActivity(LogDepth); return; } string LastFile = Files[0]; List<string> TempFiles = new List<string>(); for (int i = 1; i < Files.Count - 1; i++) { string NewFile = Path.GetTempFileName(); TempFiles.Add(NewFile); Merge(LastFile, Files[i], NewFile, Log); LastFile = NewFile; } Merge(LastFile, Files.Last(), output, Log); Log.AddString("Removing merge tempfiles"); foreach (string s in TempFiles) { File.Delete(s); } Log.PopActivity(LogDepth); } private static void MultiMerge(string file1, List<string> otherfiles, string output, ProgressLog Log) { int MM = Log.PushActivity("Excellon MultiMerge"); if (File.Exists(file1) == false) { Log.AddString(String.Format("{0} not found! stopping process!", file1)); Log.PopActivity(MM); return; } foreach (var otherfile in otherfiles) { if (File.Exists(otherfile) == false) { Log.AddString(String.Format("{0} not found! stopping process!", otherfile)); Log.PopActivity(MM); return; } } Log.AddString(String.Format("Reading {0}:", file1)); ExcellonFile File1Parsed = new ExcellonFile(); File1Parsed.Load(Log, file1); List<ExcellonFile> OtherFilesParsed = new List<ExcellonFile>(); foreach (var otherfile in otherfiles) { Log.AddString(String.Format("Reading {0}:", otherfile)); ExcellonFile OtherFileParsed = new ExcellonFile(); OtherFileParsed.Load(Log, otherfile); OtherFilesParsed.Add(OtherFileParsed); } int MaxID = 0; foreach (var D in File1Parsed.Tools) { if (D.Value.ID > MaxID) MaxID = D.Value.ID + 1; } foreach (var F in OtherFilesParsed) { foreach (var D in F.Tools) { File1Parsed.AddToolWithHoles(D.Value); ; // D.Value.ID += MaxID; // File1Parsed.Tools[D.Value.ID] = D.Value; } } File1Parsed.Write(output, 0, 0, 0, 0); Log.PopActivity(MM); } private void AddToolWithHoles(ExcellonTool d) { ExcellonTool T = FindMatchingTool(d); foreach(var a in d.Drills) { T.Drills.Add(new PointD(a.X, a.Y)); } foreach(var s in d.Slots) { T.Slots.Add(new ExcellonTool.SlotInfo() { Start = new PointD(s.Start.X, s.Start.Y), End = new PointD(s.End.X, s.End.Y) }); } } private ExcellonTool FindMatchingTool(ExcellonTool d) { int freeid = 10; foreach(var t in Tools) { if (d.Radius == t.Value.Radius) return t.Value; if (t.Key >= freeid) freeid = t.Key + 1; } var T = new ExcellonTool() { Radius = d.Radius , ID = freeid}; Tools[T.ID] = T; return T; } public static void Merge(string file1, string file2, string outputfile, ProgressLog Log) { Log.PushActivity("Excellon Merge"); if (File.Exists(file1) == false) { Log.AddString(String.Format("{0} not found! stopping process!", file1)); Log.PopActivity(); return; } if (File.Exists(file2) == false) { Log.AddString(String.Format("{0} not found! stopping process!", file2)); Log.PopActivity(); return; } Log.AddString(String.Format("Reading {0}:", file1)); ExcellonFile File1Parsed = new ExcellonFile(); File1Parsed.Load(Log, file1); Log.AddString(String.Format("Reading {0}:", file2)); ExcellonFile File2Parsed = new ExcellonFile(); File2Parsed.Load(Log, file2); Log.AddString(String.Format("Merging {0} with {1}", file1, file2)); int MaxID = 0; foreach (var D in File1Parsed.Tools) { if (D.Value.ID > MaxID) MaxID = D.Value.ID + 1; } foreach (var D in File2Parsed.Tools) { D.Value.ID += MaxID; File1Parsed.Tools[D.Value.ID] = D.Value; } File1Parsed.Write(outputfile, 0, 0, 0, 0); Log.PopActivity(); } public void Write(string filename, double DX, double DY, double DXp, double DYp, double AngleInDeg = 0) { double Angle = AngleInDeg * (Math.PI * 2.0) / 360.0; double CA = Math.Cos(Angle); double SA = Math.Sin(Angle); List<string> lines = new List<string>(); lines.Add("%"); lines.Add("M48"); lines.Add("METRIC,000.000"); //lines.Add("M71"); foreach (var a in Tools) { lines.Add(String.Format("T{0}C{1}", a.Key.ToString("D2"), (a.Value.Radius * 2).ToString("N2").Replace(',', '.'))); } lines.Add("%"); GerberNumberFormat GNF = new GerberNumberFormat(); GNF.SetMetricMode(); GNF.OmitLeading = true; GNF.DigitsAfter = 3; GNF.DigitsBefore = 3; foreach (var a in Tools) { lines.Add(String.Format("T{0}", a.Key.ToString("D2"))); double coordmultiplier = 1; foreach (var d in a.Value.Drills) { double X = (d.X * coordmultiplier + DXp) / coordmultiplier; double Y = (d.Y * coordmultiplier + DYp) / coordmultiplier; if (Angle != 0) { double nX = X * CA - Y * SA; double nY = X * SA + Y * CA; X = nX; Y = nY; } X = (X * coordmultiplier + DX) / coordmultiplier; Y = (Y * coordmultiplier + DY) / coordmultiplier; lines.Add(string.Format("X{0}Y{1}", GNF.Format(X), GNF.Format(Y).Replace(',', '.'))); } foreach(var s in a.Value.Slots) { double XS = (s.Start.X * coordmultiplier + DXp) / coordmultiplier; double YS = (s.Start.Y * coordmultiplier + DYp) / coordmultiplier; double XE = (s.End.X * coordmultiplier + DXp) / coordmultiplier; double YE = (s.End.Y * coordmultiplier + DYp) / coordmultiplier; if (Angle != 0) { double nX = XS * CA - YS * SA; double nY = XS * SA + YS * CA; XS = nX; YS = nY; double neX = XE * CA - YE * SA; double neY = XE * SA + YE * CA; XE = neX; YE = neY; } XS = (XS * coordmultiplier + DX) / coordmultiplier; YS = (YS * coordmultiplier + DY) / coordmultiplier; XE = (XE * coordmultiplier + DX) / coordmultiplier; YE = (YE * coordmultiplier + DY) / coordmultiplier; lines.Add(string.Format("X{0}Y{1}G85X{2}Y{3}", GNF.Format(XS), GNF.Format(YS).Replace(',', '.'),GNF.Format(XE), GNF.Format(YE).Replace(',', '.'))); } } lines.Add("M30"); Gerber.WriteAllLines(filename, lines); } public Dictionary<int, ExcellonTool> Tools = new Dictionary<int, ExcellonTool>(); public int TotalDrillCount() { int T = 0; foreach(var Tool in Tools) { T += Tool.Value.Drills.Count; } return T; } private enum CutterCompensation { None = 0, Left, Right } private List<PointD> CutCompensation(List<PointD> path, CutterCompensation compensation, double offset) { if (compensation == CutterCompensation.None) return path; if (path.Count < 2) return path; /* remove contiguous duplicates */ var unique = new List<PointD>(path.Count); PointD prev = null; foreach (var point in path) { if (prev == point) continue; prev = point; unique.Add(point); } path = unique; /* create offset segments */ var SegmentsOffset = path.Zip(path.Skip(1), (A, B) => { var angle = A.Angle(B); if (compensation == CutterCompensation.Left) angle += Math.PI / 2; else angle -= Math.PI / 2; A += new PointD(offset * Math.Cos(angle), offset * Math.Sin(angle)); B += new PointD(offset * Math.Cos(angle), offset * Math.Sin(angle)); return new { A, B }; }); /* create segment pairs */ var SegmentPairs = SegmentsOffset .Zip(SegmentsOffset.Skip(1), (First, Second) => new { First, Second }) .Zip(path.Skip(1), (pair, Center) => new { pair.First, pair.Second, Center }); var Path = new PolyLine(); Path.Vertices.Add(SegmentsOffset.First().A); foreach (var segment in SegmentPairs) { /* segments are colinear */ if (segment.First.B == segment.Second.A) continue; var intersection = Helpers.SegmentSegmentIntersect(segment.First.A, segment.First.B, segment.Second.A, segment.Second.B); /* if segments intersect, */ if (intersection != null) { /* the intersection point is what connects first and second segments */ Path.Vertices.Add(intersection); } else { /* otherwise connect segments with an arc */ var Center = segment.Center - segment.First.B; var arc = Gerber.CreateCurvePoints( segment.First.B.X, segment.First.B.Y, segment.Second.A.X, segment.Second.A.Y, Center.X, Center.Y, compensation == CutterCompensation.Left ? InterpolationMode.ClockWise : InterpolationMode.CounterClockwise, GerberQuadrantMode.Multi); Path.Vertices.AddRange(arc); } } Path.Vertices.Add(SegmentsOffset.Last().B); return Path.Vertices; } bool ParseExcellon(List<string> lines, double drillscaler,ProgressLog log ) { var LogID = log.PushActivity("Parse Excellon"); Tools.Clear(); bool headerdone = false; int currentline = 0; ExcellonTool CurrentTool = null; GerberNumberFormat GNF = new GerberNumberFormat(); GNF.DigitsBefore = 3; GNF.DigitsAfter = 3; GNF.OmitLeading = true; double Scaler = 1.0f; bool FormatSpecified = false; bool NumberSpecHad = false; double LastX = 0; double LastY = 0; CutterCompensation Compensation = CutterCompensation.None; List<PointD> PathCompensation = new List<PointD>(); bool WarnIntersections = true; while (currentline < lines.Count) { switch(lines[currentline]) { // case "M70": GNF.Multiplier = 25.4; break; // inch mode case "INCH": if (Gerber.ExtremelyVerbose) log.AddString("Out of header INCH found!"); GNF.SetImperialMode(); break; // inch mode case "METRIC": if (Gerber.ExtremelyVerbose) log.AddString("Out of header METRIC found!"); GNF.SetMetricMode(); break; case "M72": if (Gerber.ExtremelyVerbose) log.AddString("Out of header M72 found!"); GNF.SetImperialMode(); break; // inch mode case "M71": if (Gerber.ExtremelyVerbose) log.AddString("Out of header M71 found!"); GNF.SetMetricMode(); break; // metric mode } if (lines[currentline] == "M48") { //Console.WriteLine("Excellon header starts at line {0}", currentline); currentline++; while ((lines[currentline] != "%" && lines[currentline] != "M95")) { headerdone = true; //double InchMult = 1;// 0.010; switch (lines[currentline]) { // case "M70": GNF.Multiplier = 25.4; break; // inch mode case "INCH": GNF.SetImperialMode(); //Scaler = 0.01; break; // inch mode case "METRIC": GNF.SetMetricMode(); break; case "M72": //GNF.Multiplier = 25.4 * InchMult; GNF.SetImperialMode(); // Scaler = 0.01; break; // inch mode case "M71": //GNF.Multiplier = 1.0; GNF.SetMetricMode(); break; // metric mode default: { var S = lines[currentline].Split(','); if (S[0].IndexOf("INCH") == 0 || S[0].IndexOf("METRIC") == 0) { if (S[0].IndexOf("INCH") ==0) { GNF.SetImperialMode(); } else { GNF.SetMetricMode(); } if (S.Count() > 1) { for (int i = 1; i < S.Count(); i++) {if (S[i][0] == '0') { log.AddString(String.Format("Number spec reading!: {0}", S[i])); var A = S[i].Split('.'); if (A.Length == 2) { GNF.DigitsBefore = A[0].Length; GNF.DigitsAfter = A[1].Length; NumberSpecHad = true; } } if (S[i] == "LZ") { GNF.OmitLeading = false; } if (S[i] == "TZ") { GNF.OmitLeading = true; } } } } else { if (lines[currentline][0] == ';') { if (Gerber.ShowProgress) log.AddString(lines[currentline]); if (lines[currentline].Contains(";FILE_FORMAT=")) { var N = lines[currentline].Substring(13).Split(':'); GNF.DigitsBefore = int.Parse(N[0]); GNF.DigitsAfter = int.Parse(N[1]); FormatSpecified = true; } } else { GCodeCommand GCC = new GCodeCommand(); GCC.Decode(lines[currentline], GNF); if (GCC.charcommands.Count > 0) switch (GCC.charcommands[0]) { case 'T': { ExcellonTool ET = new ExcellonTool(); ET.ID = (int)GCC.numbercommands[0]; ET.Radius = GNF.ScaleFileToMM(GCC.GetNumber('C')) / 2.0f; Tools[ET.ID] = ET; } break; } } } } break; } currentline++; } // Console.WriteLine("Excellon header stops at line {0}", currentline); if (FormatSpecified == false && NumberSpecHad == false) { if (GNF.CurrentNumberScale == GerberNumberFormat.NumberScale.Imperial) { // GNF.OmitLeading = true; GNF.DigitsBefore = 2; GNF.DigitsAfter = 4; } else { GNF.DigitsAfter = 3; GNF.DigitsBefore = 3; } } } else { if (headerdone) { GCodeCommand GCC = new GCodeCommand(); GCC.Decode(lines[currentline], GNF); if (GCC.charcommands.Count > 0) { switch (GCC.charcommands[0]) { case 'T': if ((int)GCC.numbercommands[0] > 0) { CurrentTool = Tools[(int)GCC.numbercommands[0]]; } else { CurrentTool = null; } break; case 'M': default: { GerberSplitter GS = new GerberSplitter(); GS.Split(GCC.originalline, GNF, true); if (GS.Has("G") && GS.Get("G") == 85 && (GS.Has("X") || GS.Has("Y"))) { GerberListSplitter GLS = new GerberListSplitter(); GLS.Split(GCC.originalline, GNF, true); double x1 = LastX; double y1 = LastY; if (GLS.HasBefore("G", "X")) {x1 = GNF.ScaleFileToMM(GLS.GetBefore("G", "X") * Scaler);LastX = x1;} if (GLS.HasBefore("G", "Y")) {y1 = GNF.ScaleFileToMM(GLS.GetBefore("G", "Y") * Scaler); LastY = y1; } double x2 = LastX; double y2 = LastY; if (GLS.HasAfter("G", "X")) { x2 = GNF.ScaleFileToMM(GLS.GetAfter("G", "X") * Scaler); LastX = x2; } if (GLS.HasAfter("G", "Y")) { y2 = GNF.ScaleFileToMM(GLS.GetAfter("G", "Y") * Scaler); LastY = y2; } CurrentTool.Slots.Add(new ExcellonTool.SlotInfo() { Start = new PointD(x1 * drillscaler, y1 * drillscaler), End = new PointD(x2 * drillscaler, y2 * drillscaler) }); LastX = x2; LastY = y2; } else if (GS.Has("G") && GS.Get("G") == 00 && (GS.Has("X") || GS.Has("Y"))) { GerberListSplitter GLS = new GerberListSplitter(); GLS.Split(GCC.originalline, GNF, true); double x1 = LastX; double y1 = LastY; if (GLS.HasAfter("G", "X")) { x1 = GNF.ScaleFileToMM(GLS.GetAfter("G", "X") * Scaler); LastX = x1; } if (GLS.HasAfter("G", "Y")) { y1 = GNF.ScaleFileToMM(GLS.GetAfter("G", "Y") * Scaler); LastY = y1; } /* cancel cutter compensation */ Compensation = CutterCompensation.None; PathCompensation.Clear(); } else if (GS.Has("G") && GS.Get("G") == 01 && (GS.Has("X") || GS.Has("Y"))) { GerberListSplitter GLS = new GerberListSplitter(); GLS.Split(GCC.originalline, GNF, true); double x1 = LastX; double y1 = LastY; double x2 = LastX; double y2 = LastY; if (GLS.HasAfter("G", "X")) { x2 = GNF.ScaleFileToMM(GLS.GetAfter("G", "X") * Scaler); LastX = x2; } if (GLS.HasAfter("G", "Y")) { y2 = GNF.ScaleFileToMM(GLS.GetAfter("G", "Y") * Scaler); LastY = y2; } if (Compensation == CutterCompensation.None) CurrentTool.Slots.Add(new ExcellonTool.SlotInfo() { Start = new PointD(x1 * drillscaler, y1 * drillscaler), End = new PointD(x2 * drillscaler, y2 * drillscaler) }); else PathCompensation.Add(new PointD(x2 * drillscaler, y2 * drillscaler)); LastX = x2; LastY = y2; } else if (GS.Has("G") && GS.Get("G") == 40) /* cutter compensation off */ { var comp = CutCompensation(PathCompensation, Compensation, CurrentTool.Radius * drillscaler); if (WarnIntersections) { /* warn about path intersections */ for (int i = 0; i < comp.Count - 1; i++) { for (int j = i + 2; j < comp.Count - 1; j++) { var intersection = Helpers.SegmentSegmentIntersect(comp[i], comp[i + 1], comp[j], comp[j + 1]); if (intersection != null) { log.AddString("Path with intersections found on cut compensation! Inspect output for accuracy!"); WarnIntersections = false; break; } } if (!WarnIntersections) break; } } /* create line segments from set of points */ var array = comp.Zip(comp.Skip(1), Tuple.Create); CurrentTool.Slots.AddRange(array.Select(i => new ExcellonTool.SlotInfo() { Start = i.Item1, End = i.Item2 })); Compensation = CutterCompensation.None; PathCompensation.Clear(); } else if (GS.Has("G") && GS.Get("G") == 41) /* cutter compensation left: offset of the cutter radius is to the LEFT of contouring direction */ { if (Compensation != CutterCompensation.None) log.AddString("Unterminated cutter compensation block found! Inspect output for accuracy!"); Compensation = CutterCompensation.Left; PathCompensation.Clear(); PathCompensation.Add(new PointD(LastX * drillscaler, LastY * drillscaler)); } else if (GS.Has("G") && GS.Get("G") == 42) /* cutter compensation right: offset of the cutter radius is to the RIGHT of contouring direction */ { if (Compensation != CutterCompensation.None) log.AddString("Unterminated cutter compensation block found! Inspect output for accuracy!"); Compensation = CutterCompensation.Right; PathCompensation.Clear(); PathCompensation.Add(new PointD(LastX * drillscaler, LastY * drillscaler)); } else { //Deal with the repeat code if (GS.Has("R") && (GS.Has("X") || GS.Has("Y"))) { double repeatX = 0; double repeatY = 0; if (GS.Has("X")) repeatX = GNF.ScaleFileToMM(GS.Get("X") * Scaler); if (GS.Has("Y")) repeatY = GNF.ScaleFileToMM(GS.Get("Y") * Scaler); for (int repeatIndex = 1; repeatIndex <= GS.Get("R"); repeatIndex++) { double X = LastX; if (GS.Has("X")) X += repeatX; double Y = LastY; if (GS.Has("Y")) Y += repeatY; CurrentTool.Drills.Add(new PointD(X * drillscaler, Y * drillscaler)); LastX = X; LastY = Y; } } else if (GS.Has("X") || GS.Has("Y")) { double X = LastX; if (GS.Has("X")) X = GNF.ScaleFileToMM(GS.Get("X") * Scaler); double Y = LastY; if (GS.Has("Y")) Y = GNF.ScaleFileToMM(GS.Get("Y") * Scaler); if (Compensation == CutterCompensation.None) CurrentTool.Drills.Add(new PointD(X * drillscaler, Y * drillscaler)); else PathCompensation.Add(new PointD(X * drillscaler, Y * drillscaler)); LastX = X; LastY = Y; } } } break; } } } } currentline++; } log.PopActivity(LogID); return headerdone; } public static void WriteContainedOnly(string inputfile, PolyLine Boundary, string outputfilename, ProgressLog Log) { Log.PushActivity("Excellon Clipper"); if (File.Exists(inputfile) == false) { Log.AddString(String.Format("{0} not found! stopping process!", Path.GetFileName(inputfile))); Log.PopActivity(); return; } Log.AddString(String.Format("Clipping {0} to {1}", Path.GetFileName(inputfile), Path.GetFileName(outputfilename))); ExcellonFile EF = new ExcellonFile(); EF.Load(Log, inputfile); EF.WriteContained(Boundary, outputfilename, Log); Log.PopActivity(); } private void WriteContained(PolyLine boundary, string outputfilename, ProgressLog log) { ExcellonFile Out = new ExcellonFile(); foreach(var T in Tools) { Out.Tools[T.Key] = new ExcellonTool() { ID = T.Value.ID, Radius = T.Value.Radius }; foreach(var d in T.Value.Drills) { if (boundary.PointInPoly(new PointD(d.X , d.Y))) { Out.Tools[T.Key].Drills.Add(d); } } foreach (var d in T.Value.Slots) { if (boundary.PointInPoly(d.Start) || boundary.PointInPoly(d.End)) { Out.Tools[T.Key].Slots.Add(d); } } } Out.Write(outputfilename, 0, 0, 0, 0); } } }
/* * StrongNameIdentityPermission.cs - Implementation of the * "System.Security.Permissions.StrongNameIdentityPermission" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security.Permissions { #if CONFIG_POLICY_OBJECTS && CONFIG_PERMISSIONS && !ECMA_COMPAT using System; using System.Security; public sealed class StrongNameIdentityPermission : CodeAccessPermission { // Internal state. private StrongNamePublicKeyBlob blob; private String name; private Version version; // Constructor. public StrongNameIdentityPermission(PermissionState state) { if(state != PermissionState.None) { throw new ArgumentException(_("Arg_PermissionState")); } blob = null; name = ""; version = new Version(); } public StrongNameIdentityPermission(StrongNamePublicKeyBlob blob, String name, Version version) { if(blob == null) { throw new ArgumentNullException("blob"); } this.blob = blob; this.name = name; this.version = version; } // Convert an XML value into a permissions value. public override void FromXml(SecurityElement esd) { if(esd == null) { throw new ArgumentNullException("esd"); } if(esd.Attribute("version") != "1") { throw new ArgumentException(_("Arg_PermissionVersion")); } name = esd.Attribute("Name"); String value = esd.Attribute("Version"); if(value != null) { version = new Version(value); } else { version = null; } value = esd.Attribute("PublicKeyBlob"); if(value != null) { blob = new StrongNamePublicKeyBlob(value); } else { blob = null; } } // Convert this permissions object into an XML value. public override SecurityElement ToXml() { SecurityElement element; element = new SecurityElement("IPermission"); element.AddAttribute ("class", SecurityElement.Escape (typeof(StrongNameIdentityPermission). AssemblyQualifiedName)); element.AddAttribute("version", "1"); if(blob != null) { element.AddAttribute("PublicKeyBlob", blob.ToString()); } if(name != null) { element.AddAttribute ("Name", SecurityElement.Escape(name)); } if(version != null) { element.AddAttribute("Version", version.ToString()); } return element; } // Implement the IPermission interface. public override IPermission Copy() { if(blob == null) { return new StrongNameIdentityPermission (PermissionState.None); } else { return new StrongNameIdentityPermission (blob, name, version); } } public override IPermission Intersect(IPermission target) { if(target == null) { return target; } else if(!(target is StrongNameIdentityPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } else if(IsSubsetOf(target)) { return Copy(); } else if(target.IsSubsetOf(this)) { return target.Copy(); } else { return null; } } public override bool IsSubsetOf(IPermission target) { // Handle the easy cases first. if(target == null) { return (blob == null); } else if(!(target is StrongNameIdentityPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } // Check blob subset conditions. StrongNameIdentityPermission t; t = ((StrongNameIdentityPermission)target); if(blob != null && !blob.Equals(t.blob)) { return false; } // Check name subset conditions. if(name != null && name != t.name) { return false; } // Check version subset conditions. if(version != null && version != t.version) { return false; } // It is a subset. return true; } public override IPermission Union(IPermission target) { if(target == null) { return Copy(); } else if(!(target is StrongNameIdentityPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } else if(IsSubsetOf(target)) { return target.Copy(); } else if(target.IsSubsetOf(this)) { return Copy(); } else { return null; } } // Get or set the public key blob value. public StrongNamePublicKeyBlob PublicKey { get { return blob; } set { if(value == null) { throw new ArgumentNullException("value"); } blob = value; } } // Get or set the name. public String Name { get { return name; } set { name = value; } } // Get or set the version. public Version Version { get { return version; } set { version = value; } } }; // class StrongNameIdentityPermission #endif // CONFIG_POLICY_OBJECTS && CONFIG_PERMISSIONS && !ECMA_COMPAT }; // namespace System.Security.Permissions
// <copyright file="ArrayStatistics.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2015 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.Properties; namespace MathNet.Numerics.Statistics { /// <summary> /// Statistics operating on arrays assumed to be unsorted. /// WARNING: Methods with the Inplace-suffix may modify the data array by reordering its entries. /// </summary> /// <seealso cref="SortedArrayStatistics"/> /// <seealso cref="StreamingStatistics"/> /// <seealso cref="Statistics"/> public static partial class ArrayStatistics { // TODO: Benchmark various options to find out the best approach (-> branch prediction) // TODO: consider leveraging MKL /// <summary> /// Returns the smallest value from the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double Minimum(double[] data) { if (data.Length == 0) { return double.NaN; } double min = double.PositiveInfinity; for (int i = 0; i < data.Length; i++) { if (data[i] < min || double.IsNaN(data[i])) { min = data[i]; } } return min; } /// <summary> /// Returns the largest value from the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double Maximum(double[] data) { if (data.Length == 0) { return double.NaN; } double max = double.NegativeInfinity; for (int i = 0; i < data.Length; i++) { if (data[i] > max || double.IsNaN(data[i])) { max = data[i]; } } return max; } /// <summary> /// Returns the smallest absolute value from the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double MinimumAbsolute(double[] data) { if (data.Length == 0) { return double.NaN; } double min = double.PositiveInfinity; for (int i = 0; i < data.Length; i++) { if (Math.Abs(data[i]) < min || double.IsNaN(data[i])) { min = Math.Abs(data[i]); } } return min; } /// <summary> /// Returns the largest absolute value from the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double MaximumAbsolute(double[] data) { if (data.Length == 0) { return double.NaN; } double max = 0.0d; for (int i = 0; i < data.Length; i++) { if (Math.Abs(data[i]) > max || double.IsNaN(data[i])) { max = Math.Abs(data[i]); } } return max; } /// <summary> /// Estimates the arithmetic sample mean from the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double Mean(double[] data) { if (data.Length == 0) { return double.NaN; } double mean = 0; ulong m = 0; for (int i = 0; i < data.Length; i++) { mean += (data[i] - mean)/++m; } return mean; } /// <summary> /// Evaluates the geometric mean of the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double GeometricMean(double[] data) { if (data.Length == 0) { return double.NaN; } double sum = 0; for (int i = 0; i < data.Length; i++) { sum += Math.Log(data[i]); } return Math.Exp(sum/data.Length); } /// <summary> /// Evaluates the harmonic mean of the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double HarmonicMean(double[] data) { if (data.Length == 0) { return double.NaN; } double sum = 0; for (int i = 0; i < data.Length; i++) { sum += 1.0/data[i]; } return data.Length/sum; } /// <summary> /// Estimates the unbiased population variance from the provided samples as unsorted array. /// On a dataset of size N will use an N-1 normalizer (Bessel's correction). /// Returns NaN if data has less than two entries or if any entry is NaN. /// </summary> /// <param name="samples">Sample array, no sorting is assumed.</param> public static double Variance(double[] samples) { if (samples.Length <= 1) { return double.NaN; } double variance = 0; double t = samples[0]; for (int i = 1; i < samples.Length; i++) { t += samples[i]; double diff = ((i + 1)*samples[i]) - t; variance += (diff*diff)/((i + 1.0)*i); } return variance/(samples.Length - 1); } /// <summary> /// Evaluates the population variance from the full population provided as unsorted array. /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset. /// Returns NaN if data is empty or if any entry is NaN. /// </summary> /// <param name="population">Sample array, no sorting is assumed.</param> public static double PopulationVariance(double[] population) { if (population.Length == 0) { return double.NaN; } double variance = 0; double t = population[0]; for (int i = 1; i < population.Length; i++) { t += population[i]; double diff = ((i + 1)*population[i]) - t; variance += (diff*diff)/((i + 1.0)*i); } return variance/population.Length; } /// <summary> /// Estimates the unbiased population standard deviation from the provided samples as unsorted array. /// On a dataset of size N will use an N-1 normalizer (Bessel's correction). /// Returns NaN if data has less than two entries or if any entry is NaN. /// </summary> /// <param name="samples">Sample array, no sorting is assumed.</param> public static double StandardDeviation(double[] samples) { return Math.Sqrt(Variance(samples)); } /// <summary> /// Evaluates the population standard deviation from the full population provided as unsorted array. /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset. /// Returns NaN if data is empty or if any entry is NaN. /// </summary> /// <param name="population">Sample array, no sorting is assumed.</param> public static double PopulationStandardDeviation(double[] population) { return Math.Sqrt(PopulationVariance(population)); } /// <summary> /// Estimates the arithmetic sample mean and the unbiased population variance from the provided samples as unsorted array. /// On a dataset of size N will use an N-1 normalizer (Bessel's correction). /// Returns NaN for mean if data is empty or any entry is NaN and NaN for variance if data has less than two entries or if any entry is NaN. /// </summary> /// <param name="samples">Sample array, no sorting is assumed.</param> public static Tuple<double, double> MeanVariance(double[] samples) { return new Tuple<double, double>(Mean(samples), Variance(samples)); } /// <summary> /// Estimates the arithmetic sample mean and the unbiased population standard deviation from the provided samples as unsorted array. /// On a dataset of size N will use an N-1 normalizer (Bessel's correction). /// Returns NaN for mean if data is empty or any entry is NaN and NaN for standard deviation if data has less than two entries or if any entry is NaN. /// </summary> /// <param name="samples">Sample array, no sorting is assumed.</param> public static Tuple<double, double> MeanStandardDeviation(double[] samples) { return new Tuple<double, double>(Mean(samples), StandardDeviation(samples)); } /// <summary> /// Estimates the unbiased population covariance from the provided two sample arrays. /// On a dataset of size N will use an N-1 normalizer (Bessel's correction). /// Returns NaN if data has less than two entries or if any entry is NaN. /// </summary> /// <param name="samples1">First sample array.</param> /// <param name="samples2">Second sample array.</param> public static double Covariance(double[] samples1, double[] samples2) { if (samples1.Length != samples2.Length) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (samples1.Length <= 1) { return double.NaN; } double mean1 = Mean(samples1); double mean2 = Mean(samples2); double covariance = 0.0; for (int i = 0; i < samples1.Length; i++) { covariance += (samples1[i] - mean1)*(samples2[i] - mean2); } return covariance/(samples1.Length - 1); } /// <summary> /// Evaluates the population covariance from the full population provided as two arrays. /// On a dataset of size N will use an N normalizer and would thus be biased if applied to a subset. /// Returns NaN if data is empty or if any entry is NaN. /// </summary> /// <param name="population1">First population array.</param> /// <param name="population2">Second population array.</param> public static double PopulationCovariance(double[] population1, double[] population2) { if (population1.Length != population2.Length) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (population1.Length == 0) { return double.NaN; } double mean1 = Mean(population1); double mean2 = Mean(population2); double covariance = 0.0; for (int i = 0; i < population1.Length; i++) { covariance += (population1[i] - mean1)*(population2[i] - mean2); } return covariance/population1.Length; } /// <summary> /// Estimates the root mean square (RMS) also known as quadratic mean from the unsorted data array. /// Returns NaN if data is empty or any entry is NaN. /// </summary> /// <param name="data">Sample array, no sorting is assumed.</param> public static double RootMeanSquare(double[] data) { if (data.Length == 0) { return double.NaN; } double mean = 0; ulong m = 0; for (int i = 0; i < data.Length; i++) { mean += (data[i]*data[i] - mean)/++m; } return Math.Sqrt(mean); } /// <summary> /// Returns the order statistic (order 1..N) from the unsorted data array. /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> /// <param name="order">One-based order of the statistic, must be between 1 and N (inclusive).</param> public static double OrderStatisticInplace(double[] data, int order) { if (order < 1 || order > data.Length) { return double.NaN; } if (order == 1) { return Minimum(data); } if (order == data.Length) { return Maximum(data); } return SelectInplace(data, order - 1); } /// <summary> /// Estimates the median value from the unsorted data array. /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> public static double MedianInplace(double[] data) { var k = data.Length/2; return data.Length.IsOdd() ? SelectInplace(data, k) : (SelectInplace(data, k - 1) + SelectInplace(data, k))/2.0; } /// <summary> /// Estimates the p-Percentile value from the unsorted data array. /// If a non-integer Percentile is needed, use Quantile instead. /// Approximately median-unbiased regardless of the sample distribution (R8). /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> /// <param name="p">Percentile selector, between 0 and 100 (inclusive).</param> public static double PercentileInplace(double[] data, int p) { return QuantileInplace(data, p/100d); } /// <summary> /// Estimates the first quartile value from the unsorted data array. /// Approximately median-unbiased regardless of the sample distribution (R8). /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> public static double LowerQuartileInplace(double[] data) { return QuantileInplace(data, 0.25d); } /// <summary> /// Estimates the third quartile value from the unsorted data array. /// Approximately median-unbiased regardless of the sample distribution (R8). /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> public static double UpperQuartileInplace(double[] data) { return QuantileInplace(data, 0.75d); } /// <summary> /// Estimates the inter-quartile range from the unsorted data array. /// Approximately median-unbiased regardless of the sample distribution (R8). /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> public static double InterquartileRangeInplace(double[] data) { return QuantileInplace(data, 0.75d) - QuantileInplace(data, 0.25d); } /// <summary> /// Estimates {min, lower-quantile, median, upper-quantile, max} from the unsorted data array. /// Approximately median-unbiased regardless of the sample distribution (R8). /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> public static double[] FiveNumberSummaryInplace(double[] data) { if (data.Length == 0) { return new[] { double.NaN, double.NaN, double.NaN, double.NaN, double.NaN }; } // TODO: Benchmark: is this still faster than sorting the array then using SortedArrayStatistics instead? return new[] { Minimum(data), QuantileInplace(data, 0.25d), MedianInplace(data), QuantileInplace(data, 0.75d), Maximum(data) }; } /// <summary> /// Estimates the tau-th quantile from the unsorted data array. /// The tau-th quantile is the data value where the cumulative distribution /// function crosses tau. /// Approximately median-unbiased regardless of the sample distribution (R8). /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> /// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive).</param> /// <remarks> /// R-8, SciPy-(1/3,1/3): /// Linear interpolation of the approximate medians for order statistics. /// When tau &lt; (2/3) / (N + 1/3), use x1. When tau &gt;= (N - 1/3) / (N + 1/3), use xN. /// </remarks> public static double QuantileInplace(double[] data, double tau) { if (tau < 0d || tau > 1d || data.Length == 0) { return double.NaN; } double h = (data.Length + 1d/3d)*tau + 1d/3d; var hf = (int)h; if (hf <= 0 || tau == 0d) { return Minimum(data); } if (hf >= data.Length || tau == 1d) { return Maximum(data); } var a = SelectInplace(data, hf - 1); var b = SelectInplace(data, hf); return a + (h - hf)*(b - a); } /// <summary> /// Estimates the tau-th quantile from the unsorted data array. /// The tau-th quantile is the data value where the cumulative distribution /// function crosses tau. The quantile defintion can be specified /// by 4 parameters a, b, c and d, consistent with Mathematica. /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> /// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive)</param> /// <param name="a">a-parameter</param> /// <param name="b">b-parameter</param> /// <param name="c">c-parameter</param> /// <param name="d">d-parameter</param> public static double QuantileCustomInplace(double[] data, double tau, double a, double b, double c, double d) { if (tau < 0d || tau > 1d || data.Length == 0) { return double.NaN; } var x = a + (data.Length + b)*tau - 1; #if PORTABLE var ip = (int)x; #else var ip = Math.Truncate(x); #endif var fp = x - ip; if (Math.Abs(fp) < 1e-9) { return SelectInplace(data, (int)ip); } var lower = SelectInplace(data, (int)Math.Floor(x)); var upper = SelectInplace(data, (int)Math.Ceiling(x)); return lower + (upper - lower)*(c + d*fp); } /// <summary> /// Estimates the tau-th quantile from the unsorted data array. /// The tau-th quantile is the data value where the cumulative distribution /// function crosses tau. The quantile definition can be specified to be compatible /// with an existing system. /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> /// <param name="data">Sample array, no sorting is assumed. Will be reordered.</param> /// <param name="tau">Quantile selector, between 0.0 and 1.0 (inclusive)</param> /// <param name="definition">Quantile definition, to choose what product/definition it should be consistent with</param> public static double QuantileCustomInplace(double[] data, double tau, QuantileDefinition definition) { if (tau < 0d || tau > 1d || data.Length == 0) { return double.NaN; } if (tau == 0d || data.Length == 1) { return Minimum(data); } if (tau == 1d) { return Maximum(data); } switch (definition) { case QuantileDefinition.R1: { double h = data.Length*tau + 0.5d; return SelectInplace(data, (int)Math.Ceiling(h - 0.5d) - 1); } case QuantileDefinition.R2: { double h = data.Length*tau + 0.5d; return (SelectInplace(data, (int)Math.Ceiling(h - 0.5d) - 1) + SelectInplace(data, (int)(h + 0.5d) - 1))*0.5d; } case QuantileDefinition.R3: { double h = data.Length*tau; return SelectInplace(data, (int)Math.Round(h) - 1); } case QuantileDefinition.R4: { double h = data.Length*tau; var hf = (int)h; var lower = SelectInplace(data, hf - 1); var upper = SelectInplace(data, hf); return lower + (h - hf)*(upper - lower); } case QuantileDefinition.R5: { double h = data.Length*tau + 0.5d; var hf = (int)h; var lower = SelectInplace(data, hf - 1); var upper = SelectInplace(data, hf); return lower + (h - hf)*(upper - lower); } case QuantileDefinition.R6: { double h = (data.Length + 1)*tau; var hf = (int)h; var lower = SelectInplace(data, hf - 1); var upper = SelectInplace(data, hf); return lower + (h - hf)*(upper - lower); } case QuantileDefinition.R7: { double h = (data.Length - 1)*tau + 1d; var hf = (int)h; var lower = SelectInplace(data, hf - 1); var upper = SelectInplace(data, hf); return lower + (h - hf)*(upper - lower); } case QuantileDefinition.R8: { double h = (data.Length + 1/3d)*tau + 1/3d; var hf = (int)h; var lower = SelectInplace(data, hf - 1); var upper = SelectInplace(data, hf); return lower + (h - hf)*(upper - lower); } case QuantileDefinition.R9: { double h = (data.Length + 0.25d)*tau + 0.375d; var hf = (int)h; var lower = SelectInplace(data, hf - 1); var upper = SelectInplace(data, hf); return lower + (h - hf)*(upper - lower); } default: throw new NotSupportedException(); } } static double SelectInplace(double[] workingData, int rank) { // Numerical Recipes: select // http://en.wikipedia.org/wiki/Selection_algorithm if (rank <= 0) { return Minimum(workingData); } if (rank >= workingData.Length - 1) { return Maximum(workingData); } double[] a = workingData; int low = 0; int high = a.Length - 1; while (true) { if (high <= low + 1) { if (high == low + 1 && a[high] < a[low]) { var tmp = a[low]; a[low] = a[high]; a[high] = tmp; } return a[rank]; } int middle = (low + high) >> 1; var tmp1 = a[middle]; a[middle] = a[low + 1]; a[low + 1] = tmp1; if (a[low] > a[high]) { var tmp = a[low]; a[low] = a[high]; a[high] = tmp; } if (a[low + 1] > a[high]) { var tmp = a[low + 1]; a[low + 1] = a[high]; a[high] = tmp; } if (a[low] > a[low + 1]) { var tmp = a[low]; a[low] = a[low + 1]; a[low + 1] = tmp; } int begin = low + 1; int end = high; double pivot = a[begin]; while (true) { do { begin++; } while (a[begin] < pivot); do { end--; } while (a[end] > pivot); if (end < begin) { break; } var tmp = a[begin]; a[begin] = a[end]; a[end] = tmp; } a[low + 1] = a[end]; a[end] = pivot; if (end >= rank) { high = end - 1; } if (end <= rank) { low = begin; } } } /// <summary> /// Evaluates the rank of each entry of the unsorted data array. /// The rank definition can be specified to be compatible /// with an existing system. /// WARNING: Works inplace and can thus causes the data array to be reordered. /// </summary> public static double[] RanksInplace(double[] data, RankDefinition definition = RankDefinition.Default) { var ranks = new double[data.Length]; var index = new int[data.Length]; for (int i = 0; i < index.Length; i++) { index[i] = i; } if (definition == RankDefinition.First) { Sorting.SortAll(data, index); for (int i = 0; i < ranks.Length; i++) { ranks[index[i]] = i + 1; } return ranks; } Sorting.Sort(data, index); int previousIndex = 0; for (int i = 1; i < data.Length; i++) { if (Math.Abs(data[i] - data[previousIndex]) <= 0d) { continue; } if (i == previousIndex + 1) { ranks[index[previousIndex]] = i; } else { RanksTies(ranks, index, previousIndex, i, definition); } previousIndex = i; } RanksTies(ranks, index, previousIndex, data.Length, definition); return ranks; } static void RanksTies(double[] ranks, int[] index, int a, int b, RankDefinition definition) { // TODO: potential for PERF optimization double rank; switch (definition) { case RankDefinition.Average: { rank = (b + a - 1)/2d + 1; break; } case RankDefinition.Min: { rank = a + 1; break; } case RankDefinition.Max: { rank = b; break; } default: throw new NotSupportedException(); } for (int k = a; k < b; k++) { ranks[index[k]] = rank; } } } }
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 MyExamination.Web.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; } } }
/*- * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * See the file EXAMPLES-LICENSE for license information. * */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using BerkeleyDB; namespace excs_bulk { public class excs_bulk { private const String dbFileName = "BulkExample.db"; private const String pDbName = "primary"; private const String sDbName = "secondary"; private const String home = "BulkExample"; private const int buffLen = 1024 * 1024; private BTreeDatabase pdb; private DatabaseEnvironment env; private Operations opt = Operations.BULK_READ; private SecondaryBTreeDatabase sdb; private uint cachesize = 0, pagesize = 0; private int num = 1000000, dups = 0; private bool secondary = false; /* Bulk methods demonstrated in the example */ public enum Operations { BULK_DELETE, BULK_READ, BULK_UPDATE } public static void Main(String[] args) { DateTime startTime, endTime; int count; try { String pwd = Environment.CurrentDirectory; pwd = Path.Combine(pwd, ".."); pwd = Path.Combine(pwd, ".."); if (IntPtr.Size == 4) pwd = Path.Combine(pwd, "Win32"); else pwd = Path.Combine(pwd, "x64"); #if DEBUG pwd = Path.Combine(pwd, "Debug"); #else pwd = Path.Combine(pwd, "Release"); #endif pwd += ";" + Environment.GetEnvironmentVariable("PATH"); Environment.SetEnvironmentVariable("PATH", pwd); } catch (Exception e) { Console.WriteLine( "Unable to set the PATH environment variable."); Console.WriteLine(e.Message); return; } excs_bulk app = new excs_bulk(); /* Parse argument */ for (int i = 0; i < args.Length; i++) { if (args[i].CompareTo("-c") == 0) { if (i == args.Length - 1) Usage(); i++; app.cachesize = uint.Parse(args[i]); Console.WriteLine("[CONFIG] cachesize {0}", app.cachesize); } else if (args[i].CompareTo("-d") == 0) { if (i == args.Length - 1) Usage(); i++; app.dups = int.Parse(args[i]); Console.WriteLine("[CONFIG] number of duplicates {0}", app.dups); } else if (args[i].CompareTo("-n") == 0) { if (i == args.Length - 1) Usage(); i++; app.num = int.Parse(args[i]); Console.WriteLine("[CONFIG] number of keys {0}", app.num); } else if (args[i].CompareTo("-p") == 0) { if (i == args.Length - 1) Usage(); i++; app.pagesize = uint.Parse(args[i]); Console.WriteLine("[CONFIG] pagesize {0}", app.pagesize); } else if (args[i].CompareTo("-D") == 0) { app.opt = Operations.BULK_DELETE; } else if (args[i].CompareTo("-R") == 0) { app.opt = Operations.BULK_READ; } else if (args[i].CompareTo("-S") == 0) { app.secondary = true; } else if (args[i].CompareTo("-U") == 0) { app.opt = Operations.BULK_UPDATE; } else Usage(); } /* Open environment and database(s) */ try { /* * If perform bulk update or delete, clean environment * home */ app.CleanHome(app.opt != Operations.BULK_READ); app.InitDbs(); } catch (Exception e) { Console.WriteLine(e.StackTrace); app.CloseDbs(); } try { /* Perform bulk read from existing primary db */ if (app.opt == Operations.BULK_READ) { startTime = DateTime.Now; count = app.BulkRead(); endTime = DateTime.Now; app.PrintBulkOptStat( Operations.BULK_READ, count, startTime, endTime); } else { /* Perform bulk update to populate the db */ startTime = DateTime.Now; app.BulkUpdate(); endTime = DateTime.Now; count = (app.dups == 0) ? app.num : app.num * app.dups; app.PrintBulkOptStat( Operations.BULK_UPDATE, count, startTime, endTime); /* Perform bulk delete in primary db or secondary db */ if (app.opt == Operations.BULK_DELETE) { startTime = DateTime.Now; if (app.secondary == false) { /* * Delete from the first key to a random one in * primary db. */ count = new Random().Next(app.num); app.BulkDelete(count); } else { /* * Delete a set of keys or specified key/data * pairs in secondary db. If delete a set of keys, * delete from the first key to a random one in * secondary db. If delete a set of specified * key/data pairs, delete a random key and all * its duplicate records. */ int deletePair = new Random().Next(1); count = new Random().Next(DataVal.tstring.Length); count = app.BulkSecondaryDelete( ASCIIEncoding.ASCII.GetBytes( DataVal.tstring)[count], deletePair); } endTime = DateTime.Now; app.PrintBulkOptStat(Operations.BULK_DELETE, count, startTime, endTime); } } } catch (DatabaseException e) { Console.WriteLine(e.StackTrace); } catch (IOException e) { Console.WriteLine(e.StackTrace); } finally { /* Close dbs */ app.CloseDbs(); } } /* Perform bulk delete in primary db */ public void BulkDelete(int value) { Transaction txn = env.BeginTransaction(); try { if (dups == 0) { /* Delete a set of key/data pairs */ List<KeyValuePair<DatabaseEntry, DatabaseEntry>> pList = new List<KeyValuePair<DatabaseEntry, DatabaseEntry>>(); for (int i = 0; i < value; i++) pList.Add( new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(getBytes(new DataVal(i))))); MultipleKeyDatabaseEntry pairs = new MultipleKeyDatabaseEntry(pList, false); pdb.Delete(pairs, txn); } else { /* Delete a set of keys */ List<DatabaseEntry> kList = new List<DatabaseEntry>(); for (int i = 0; i < value; i++) kList.Add(new DatabaseEntry( BitConverter.GetBytes(i))); MultipleDatabaseEntry keySet = new MultipleDatabaseEntry(kList, false); pdb.Delete(keySet, txn); } txn.Commit(); } catch (DatabaseException e) { txn.Abort(); throw e; } } /* Perform bulk delete in secondary db */ public int BulkSecondaryDelete(byte value, int deletePair) { DatabaseEntry key, data; byte[] tstrBytes = ASCIIEncoding.ASCII.GetBytes(DataVal.tstring); int i = 0; int count = 0; Transaction txn = env.BeginTransaction(); try { if (deletePair == 1) { /* * Delete the given key and all keys prior to it, * together with their duplicate data. */ List<KeyValuePair<DatabaseEntry, DatabaseEntry>> pList = new List<KeyValuePair<DatabaseEntry, DatabaseEntry>>(); do { int j = 0; int idx = 0; key = new DatabaseEntry(); key.Data = new byte[1]; key.Data[0] = tstrBytes[i]; while (j < this.num / DataVal.tstring.Length) { idx = j * DataVal.tstring.Length + i; data = new DatabaseEntry( getBytes(new DataVal(idx))); pList.Add(new KeyValuePair< DatabaseEntry, DatabaseEntry>(key, data)); j++; } if (i < this.num % DataVal.tstring.Length) { idx = j * DataVal.tstring.Length + i; data = new DatabaseEntry( getBytes(new DataVal(idx))); pList.Add(new KeyValuePair< DatabaseEntry, DatabaseEntry>( key, data)); j++; } count += j; } while (value != tstrBytes[i++]); MultipleKeyDatabaseEntry pairs = new MultipleKeyDatabaseEntry(pList, false); sdb.Delete(pairs, txn); } else { List<DatabaseEntry> kList = new List<DatabaseEntry>(); /* Delete the given key and all keys prior to it */ do { key = new DatabaseEntry(); key.Data = new byte[1]; key.Data[0] = tstrBytes[i]; kList.Add(key); } while (value != tstrBytes[i++]); MultipleDatabaseEntry keySet = new MultipleDatabaseEntry(kList, false); sdb.Delete(keySet, txn); count = this.num / DataVal.tstring.Length * i; if (i < this.num % DataVal.tstring.Length) count += i; } txn.Commit(); return count; } catch (DatabaseException e) { txn.Abort(); throw e; } } /* Perform bulk read in primary db */ public int BulkRead() { BTreeCursor cursor; int count = 0; Transaction txn = env.BeginTransaction(); try { cursor = pdb.Cursor(txn); } catch (DatabaseException e) { txn.Abort(); throw e; } try { if (dups == 0) { /* Get all records in a single key/data buffer */ while (cursor.MoveNextMultipleKey()) { MultipleKeyDatabaseEntry pairs = cursor.CurrentMultipleKey; foreach (KeyValuePair<DatabaseEntry, DatabaseEntry> p in pairs) { count++; } } } else { /* * Get all key/data pairs in two buffers, one for all * keys, the other for all data. */ while (cursor.MoveNextMultiple()) { KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> pairs = cursor.CurrentMultiple; foreach (DatabaseEntry d in pairs.Value) { count++; } } } cursor.Close(); txn.Commit(); return count; } catch (DatabaseException e) { cursor.Close(); txn.Abort(); throw e; } } /* Perform bulk update in primary db */ public void BulkUpdate() { Transaction txn = env.BeginTransaction(); try { if (this.dups == 0) { /* * Bulk insert non-duplicate key/data pairs. Those pairs * are filled into one single buffer. */ List<KeyValuePair<DatabaseEntry, DatabaseEntry>> pList = new List<KeyValuePair<DatabaseEntry, DatabaseEntry>>(); for (int i = 0; i < this.num; i++) { DataVal dataVal = new DataVal(i); pList.Add( new KeyValuePair<DatabaseEntry, DatabaseEntry>( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(getBytes(dataVal)))); } pdb.Put(new MultipleKeyDatabaseEntry(pList, false), txn); } else { /* Bulk insert duplicate key/data pairs. All keys are * filled into a buffer, and their data is filled into * another buffer. */ List<DatabaseEntry> kList = new List<DatabaseEntry>(); List<DatabaseEntry> dList = new List<DatabaseEntry>(); for (int i = 0; i < this.num; i++) { int j = 0; DataVal dataVal = new DataVal(i); do { kList.Add( new DatabaseEntry(BitConverter.GetBytes(i))); dataVal.DataId = j; dList.Add(new DatabaseEntry(getBytes(dataVal))); } while (++j < this.dups); } pdb.Put(new MultipleDatabaseEntry(kList, false), new MultipleDatabaseEntry(dList, false), txn); } txn.Commit(); } catch (DatabaseException e1) { txn.Abort(); throw e1; } catch (IOException e2) { txn.Abort(); throw e2; } } /* Clean the home directory */ public void CleanHome(bool clean) { try { if (!Directory.Exists(home)) { Directory.CreateDirectory(home); } else if (clean == true) { string[] files = Directory.GetFiles(home); for (int i = 0; i < files.Length; i++) File.Delete(files[i]); Directory.Delete(home); Directory.CreateDirectory(home); } } catch (Exception e) { Console.WriteLine(e.StackTrace); System.Environment.Exit(1); } } /* Close database(s) and environment */ public void CloseDbs() { try { if (this.secondary && sdb != null) sdb.Close(); if (pdb != null) pdb.Close(); if (env != null) env.Close(); } catch (DatabaseException e) { Console.WriteLine(e.StackTrace); System.Environment.Exit(1); } } /* Print statistics in bulk operations */ public void PrintBulkOptStat( Operations opt, int count, DateTime startTime, DateTime endTime) { Console.Write("[STAT] "); if (opt == Operations.BULK_DELETE && !secondary) Console.Write("Bulk delete "); else if (opt == Operations.BULK_DELETE && secondary) Console.Write("Bulk secondary delete "); else if (opt == Operations.BULK_READ) Console.Write("Bulk read "); else Console.Write("Bulk update "); Console.Write("{0} records", count); Console.Write(" in {0} ms", ((TimeSpan)(endTime - startTime)).Milliseconds); Console.WriteLine(", that is {0} records/second", (int)((double)1000 / ((TimeSpan)(endTime - startTime)).Milliseconds * (double)count)); } /* Initialize environment and database (s) */ public void InitDbs() { /* Open transactional environment */ DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseMPool = true; envConfig.UseLocking = true; envConfig.UseLogging = true; envConfig.UseTxns = true; envConfig.LockSystemCfg = new LockingConfig(); envConfig.LockSystemCfg.MaxLocks = (this.dups == 0) ? (uint)this.num : (uint)(this.num * this.dups); envConfig.LockSystemCfg.MaxObjects = envConfig.LockSystemCfg.MaxLocks; if (this.cachesize != 0) { envConfig.MPoolSystemCfg = new MPoolConfig(); envConfig.MPoolSystemCfg.CacheSize = new CacheInfo(0, this.cachesize, 1); } try { env = DatabaseEnvironment.Open(home, envConfig); } catch (Exception e) { Console.WriteLine(e.StackTrace); System.Environment.Exit(1); } Transaction txn = env.BeginTransaction(); try { /* Open primary db in transaction */ BTreeDatabaseConfig dbConfig = new BTreeDatabaseConfig(); dbConfig.Env = env; dbConfig.Creation = CreatePolicy.IF_NEEDED; if (this.pagesize != 0) dbConfig.PageSize = this.pagesize; if (this.dups != 0) dbConfig.Duplicates = DuplicatesPolicy.UNSORTED; pdb = BTreeDatabase.Open(dbFileName, pDbName, dbConfig, txn); /* Open secondary db in transaction */ if (this.secondary) { SecondaryBTreeDatabaseConfig sdbConfig = new SecondaryBTreeDatabaseConfig( pdb, new SecondaryKeyGenDelegate(SecondaryKeyGen)); sdbConfig.Creation = CreatePolicy.IF_NEEDED; if (this.pagesize != 0) sdbConfig.PageSize = this.pagesize; sdbConfig.Duplicates = DuplicatesPolicy.SORTED; sdbConfig.Env = env; sdb = SecondaryBTreeDatabase.Open( dbFileName, sDbName, sdbConfig, txn); } txn.Commit(); } catch (DatabaseException e1) { txn.Abort(); throw e1; } catch (FileNotFoundException e2) { txn.Abort(); throw e2; } } /* Usage of BulkExample */ private static void Usage() { Console.WriteLine("Usage: BulkExample \n" + " -c cachesize [1000 * pagesize] \n" + " -d number of duplicates [none] \n" + " -e use environment and transaction \n" + " -i number of read iterations [1000000] \n" + " -n number of keys [1000000] \n" + " -p pagesize [65536] \n" + " -D perform bulk delete \n" + " -I just initialize the environment \n" + " -R perform bulk read \n" + " -S perform bulk read in secondary database \n" + " -U perform bulk update \n"); System.Environment.Exit(1); } public DatabaseEntry SecondaryKeyGen( DatabaseEntry key, DatabaseEntry data) { byte[] firstStr = new byte[1]; DataVal dataVal = getDataVal(data.Data); firstStr[0] = ASCIIEncoding.ASCII.GetBytes(dataVal.DataString)[0]; return new DatabaseEntry(firstStr); } public byte[] getBytes(DataVal dataVal) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); formatter.Serialize(ms, dataVal); return ms.GetBuffer(); } public DataVal getDataVal(byte[] bytes) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(bytes); return (DataVal)formatter.Deserialize(ms); } [Serializable] public class DataVal { /* String template */ public static String tstring = "0123456789abcde"; private String dataString; private int dataId; /* * Construct DataVal with given kid and id. The dataString is the * rotated tstring from the kid position. The dataId is the id. */ public DataVal(int kid) { int rp = kid % tstring.Length; if (rp == 0) this.dataString = tstring; else this.dataString = tstring.Substring(rp) + tstring.Substring(0, rp - 1); this.dataId = 0; } public int DataId { get { return dataId; } set { dataId = value; } } public String DataString { get { return dataString; } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.Json; using Abp.Localization; using Abp.MultiTenancy; using Abp.Organizations; using Abp.Runtime.Caching; using Abp.Runtime.Session; using Abp.UI; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Abp.Authorization.Users { public class AbpUserManager<TRole, TUser> : UserManager<TUser>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { protected IUserPermissionStore<TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TUser>; } } public ILocalizationManager LocalizationManager { get; set; } protected string LocalizationSourceName { get; set; } public IAbpSession AbpSession { get; set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } protected AbpUserStore<TRole, TUser> AbpUserStore { get; } public IMultiTenancyConfig MultiTenancy { get; set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ICacheManager _cacheManager; private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository; private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository; private readonly IOrganizationUnitSettings _organizationUnitSettings; private readonly ISettingManager _settingManager; private readonly IOptions<IdentityOptions> _optionsAccessor; public AbpUserManager( AbpRoleManager<TRole, TUser> roleManager, AbpUserStore<TRole, TUser> userStore, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ISettingManager settingManager) : base( userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _cacheManager = cacheManager; _organizationUnitRepository = organizationUnitRepository; _userOrganizationUnitRepository = userOrganizationUnitRepository; _organizationUnitSettings = organizationUnitSettings; _settingManager = settingManager; _optionsAccessor = optionsAccessor; AbpUserStore = userStore; RoleManager = roleManager; LocalizationManager = NullLocalizationManager.Instance; LocalizationSourceName = AbpZeroConsts.LocalizationSourceName; } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !user.TenantId.HasValue) { user.TenantId = tenantId.Value; } await InitializeOptionsAsync(user.TenantId); return await base.CreateAsync(user); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual bool IsGranted(long userId, string permissionName) { return IsGranted( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual bool IsGranted(TUser user, Permission permission) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return IsGranted(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual bool IsGranted(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!permission.FeatureDependency.IsSatisfied(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = GetUserPermissionCacheItem(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (RoleManager.IsGranted(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public void ResetAllPermissions(TUser user) { UserPermissionStore.RemoveAllPermissionSettings(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual TUser FindByNameOrEmail(string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmail(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpUserStore.FindAllAsync(login); } public virtual List<TUser> FindAll(UserLoginInfo login) { return AbpUserStore.FindAll(login); } public virtual Task<TUser> FindAsync(int? tenantId, UserLoginInfo login) { return AbpUserStore.FindAsync(tenantId, login); } public virtual TUser Find(int? tenantId, UserLoginInfo login) { return AbpUserStore.Find(tenantId, login); } public virtual Task<TUser> FindByNameOrEmailAsync(int? tenantId, string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); } public virtual TUser FindByNameOrEmail(int? tenantId, string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmail(tenantId, userNameOrEmailAddress); } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId.ToString()); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual TUser GetUserById(long userId) { var user = AbpUserStore.FindById(userId.ToString()); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } // Microsoft.AspNetCore.Identity.UserManager doesn't have required sync version for method calls in this function //public virtual TUser GetUserById(long userId) //{ // var user = FindById(userId.ToString()); // if (user == null) // { // throw new AbpException("There is no user with id: " + userId); // } // return user; //} public override async Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } //Admin user's username can not be changed! if (user.UserName != AbpUserBase.AdminUserName) { if ((await GetOldUserNameAsync(user.Id)) == AbpUserBase.AdminUserName) { throw new UserFriendlyException(string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName)); } } return await base.UpdateAsync(user); } // Microsoft.AspNetCore.Identity.UserManager doesn't have required sync version for method calls in this function //public override IdentityResult Update(TUser user) //{ // var result = CheckDuplicateUsernameOrEmailAddress(user.Id, user.UserName, user.EmailAddress); // if (!result.Succeeded) // { // return result; // } // //Admin user's username can not be changed! // if (user.UserName != AbpUserBase.AdminUserName) // { // if ((GetOldUserName(user.Id)) == AbpUserBase.AdminUserName) // { // throw new UserFriendlyException(string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName)); // } // } // return base.Update(user); //} public override async Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUserBase.AdminUserName) { throw new UserFriendlyException(string.Format(L("CanNotDeleteAdminUser"), AbpUserBase.AdminUserName)); } return await base.DeleteAsync(user); } // Microsoft.AspNetCore.Identity.UserManager doesn't have required sync version for method calls in this function //public override IdentityResult Delete(TUser user) //{ // if (user.UserName == AbpUserBase.AdminUserName) // { // throw new UserFriendlyException(string.Format(L("CanNotDeleteAdminUser"), AbpUserBase.AdminUserName)); // } // return base.Delete(user); //} public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var errors = new List<IdentityError>(); foreach (var validator in PasswordValidators) { var validationResult = await validator.ValidateAsync(this, user, newPassword); if (!validationResult.Succeeded) { errors.AddRange(validationResult.Errors); } } if (errors.Any()) { return IdentityResult.Failed(errors.ToArray()); } await AbpUserStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(user, newPassword)); await UpdateSecurityStampAsync(user); return IdentityResult.Success; } // IPasswordValidator doesn't have a sync version of Validate(...) //public virtual IdentityResult ChangePassword(TUser user, string newPassword) //{ // var errors = new List<IdentityError>(); // foreach (var validator in PasswordValidators) // { // var validationResult = validator.Validate(this, user, newPassword); // if (!validationResult.Succeeded) // { // errors.AddRange(validationResult.Errors); // } // } // if (errors.Any()) // { // return IdentityResult.Failed(errors.ToArray()); // } // AbpUserStore.SetPasswordHash(user, PasswordHasher.HashPassword(user, newPassword)); // return IdentityResult.Success; //} public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateUserName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } // Microsoft.AspNetCore.Identity doesn't have a sync version of FindByName(...), FindByEmail(...) //public virtual IdentityResult CheckDuplicateUsernameOrEmailAddress(long? expectedUserId, string userName, string emailAddress) //{ // var user = (FindByName(userName)); // if (user != null && user.Id != expectedUserId) // { // throw new UserFriendlyException(string.Format(L("Identity.DuplicateUserName"), userName)); // } // user = (FindByEmail(emailAddress)); // if (user != null && user.Id != expectedUserId) // { // throw new UserFriendlyException(string.Format(L("Identity.DuplicateEmail"), emailAddress)); // } // return IdentityResult.Success; //} public virtual async Task<IdentityResult> SetRolesAsync(TUser user, string[] roleNames) { await AbpUserStore.UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles); //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId.ToString()); if (role != null && roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } // Microsoft.AspNetCore.Identity doesn't have a sync version of FindById(...), RemoveFromRole(...), GetRoleByName(...), AddToRole(...) //public virtual IdentityResult SetRoles(TUser user, string[] roleNames) //{ // AbpUserStore.UserRepository.EnsureCollectionLoaded(user, u => u.Roles); // //Remove from removed roles // foreach (var userRole in user.Roles.ToList()) // { // var role = RoleManager.FindById(userRole.RoleId.ToString()); // if (roleNames.All(roleName => role.Name != roleName)) // { // var result = RemoveFromRole(user, role.Name); // if (!result.Succeeded) // { // return result; // } // } // } // //Add to added roles // foreach (var roleName in roleNames) // { // var role = RoleManager.GetRoleByName(roleName); // if (user.Roles.All(ur => ur.RoleId != role.Id)) // { // var result = AddToRole(user, roleName); // if (!result.Succeeded) // { // return result; // } // } // } // return IdentityResult.Success; //} public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId) { return await IsInOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou) { return await _userOrganizationUnitRepository.CountAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; } public virtual bool IsInOrganizationUnit(TUser user, OrganizationUnit ou) { return _userOrganizationUnitRepository.Count(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; } public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId) { await AddToOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou) { var currentOus = await GetOrganizationUnitsAsync(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1); await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); } public virtual void AddToOrganizationUnit(TUser user, OrganizationUnit ou) { var currentOus = GetOrganizationUnits(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } CheckMaxUserOrganizationUnitMembershipCount(user.TenantId, currentOus.Count + 1); _userOrganizationUnitRepository.Insert(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); } public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId) { await RemoveFromOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id); } public virtual void RemoveFromOrganizationUnit(TUser user, OrganizationUnit ou) { _userOrganizationUnitRepository.Delete(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id); } public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds) { await SetOrganizationUnitsAsync( await GetUserByIdAsync(userId), organizationUnitIds ); } private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount) { var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId); if (requestedCount > maxCount) { throw new AbpException($"Can not set more than {maxCount} organization unit for a user!"); } } private void CheckMaxUserOrganizationUnitMembershipCount(int? tenantId, int requestedCount) { var maxCount = _organizationUnitSettings.GetMaxUserMembershipCount(tenantId); if (requestedCount > maxCount) { throw new AbpException($"Can not set more than {maxCount} organization unit for a user!"); } } [UnitOfWork] public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds) { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length); var currentOus = await GetOrganizationUnitsAsync(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { await RemoveFromOrganizationUnitAsync(user, currentOu); } } await _unitOfWorkManager.Current.SaveChangesAsync(); //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { await AddToOrganizationUnitAsync( user, await _organizationUnitRepository.GetAsync(organizationUnitId) ); } } } public virtual void SetOrganizationUnits(TUser user, params long[] organizationUnitIds) { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } CheckMaxUserOrganizationUnitMembershipCount(user.TenantId, organizationUnitIds.Length); var currentOus = GetOrganizationUnits(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { RemoveFromOrganizationUnit(user, currentOu); } } //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { AddToOrganizationUnit( user, _organizationUnitRepository.Get(organizationUnitId) ); } } } [UnitOfWork] public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user) { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return Task.FromResult(query.ToList()); } [UnitOfWork] public virtual List<OrganizationUnit> GetOrganizationUnits(TUser user) { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return query.ToList(); } [UnitOfWork] public virtual Task<List<TUser>> GetUsersInOrganizationUnitAsync(OrganizationUnit organizationUnit, bool includeChildren = false) { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return Task.FromResult(query.ToList()); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return Task.FromResult(query.ToList()); } } [UnitOfWork] public virtual List<TUser> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false) { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return query.ToList(); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return query.ToList(); } } public virtual async Task InitializeOptionsAsync(int? tenantId) { Options = JsonConvert.DeserializeObject<IdentityOptions>(_optionsAccessor.Value.ToJsonString()); //Lockout Options.Lockout.AllowedForNewUsers = await IsTrueAsync(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId); Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId)); Options.Lockout.MaxFailedAccessAttempts = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); //Password complexity Options.Password.RequireDigit = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit, tenantId); Options.Password.RequireLowercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase, tenantId); Options.Password.RequireNonAlphanumeric = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, tenantId); Options.Password.RequireUppercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, tenantId); Options.Password.RequiredLength = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, tenantId); } public virtual void InitializeOptions(int? tenantId) { Options = JsonConvert.DeserializeObject<IdentityOptions>(_optionsAccessor.Value.ToJsonString()); //Lockout Options.Lockout.AllowedForNewUsers = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId); Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId)); Options.Lockout.MaxFailedAccessAttempts = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); //Password complexity Options.Password.RequireDigit = GetSettingValue<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit, tenantId); Options.Password.RequireLowercase = GetSettingValue<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase, tenantId); Options.Password.RequireNonAlphanumeric = GetSettingValue<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, tenantId); Options.Password.RequireUppercase = GetSettingValue<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, tenantId); Options.Password.RequiredLength = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, tenantId); } protected virtual Task<string> GetOldUserNameAsync(long userId) { return AbpUserStore.GetUserNameFromDatabaseAsync(userId); } protected virtual string GetOldUserName(long userId) { return AbpUserStore.GetUserNameFromDatabase(userId); } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () => { var user = await FindByIdAsync(userId.ToString()); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(user)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } private UserPermissionCacheItem GetUserPermissionCacheItem(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return _cacheManager.GetUserPermissionCache().Get(cacheKey, () => { var user = AbpUserStore.FindById(userId.ToString()); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in AbpUserStore.GetRoles(user)) { newCacheItem.RoleIds.Add((RoleManager.GetRoleByName(roleName)).Id); } foreach (var permissionInfo in UserPermissionStore.GetPermissions(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(TUser user) { var providers = new List<string>(); foreach (var provider in await base.GetValidTwoFactorProvidersAsync(user)) { if (provider == "Email" && !await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, user.TenantId)) { continue; } if (provider == "Phone" && !await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, user.TenantId)) { continue; } providers.Add(provider); } return providers; } // no sync version available for GetValidTwoFactorProviders() //public override IList<string> GetValidTwoFactorProviders(TUser user) //{ // var providers = new List<string>(); // foreach (var provider in base.GetValidTwoFactorProviders(user)) // { // if (provider == "Email" && // !IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, user.TenantId)) // { // continue; // } // if (provider == "Phone" && // !IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, user.TenantId)) // { // continue; // } // providers.Add(provider); // } // return providers; //} private bool IsTrue(string settingName, int? tenantId) { return GetSettingValue<bool>(settingName, tenantId); } private Task<bool> IsTrueAsync(string settingName, int? tenantId) { return GetSettingValueAsync<bool>(settingName, tenantId); } private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplication<T>(settingName) : _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value); } private Task<T> GetSettingValueAsync<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplicationAsync<T>(settingName) : _settingManager.GetSettingValueForTenantAsync<T>(settingName, tenantId.Value); } protected virtual string L(string name) { return LocalizationManager.GetString(LocalizationSourceName, name); } protected virtual string L(string name, CultureInfo cultureInfo) { return LocalizationManager.GetString(LocalizationSourceName, name, cultureInfo); } private int? GetCurrentTenantId() { if (_unitOfWorkManager.Current != null) { return _unitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } private MultiTenancySides GetCurrentMultiTenancySide() { if (_unitOfWorkManager.Current != null) { return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue ? MultiTenancySides.Host : MultiTenancySides.Tenant; } return AbpSession.MultiTenancySide; } public virtual async Task AddTokenValidityKeyAsync( TUser user, string tokenValidityKey, DateTime expireDate, CancellationToken cancellationToken = default(CancellationToken)) { await AbpUserStore.AddTokenValidityKeyAsync(user, tokenValidityKey, expireDate, cancellationToken); } public virtual void AddTokenValidityKey( TUser user, string tokenValidityKey, DateTime expireDate, CancellationToken cancellationToken = default(CancellationToken)) { AbpUserStore.AddTokenValidityKey(user, tokenValidityKey, expireDate, cancellationToken); } public virtual async Task<bool> IsTokenValidityKeyValidAsync( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { return await AbpUserStore.IsTokenValidityKeyValidAsync(user, tokenValidityKey, cancellationToken); } public virtual bool IsTokenValidityKeyValid( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { return AbpUserStore.IsTokenValidityKeyValid(user, tokenValidityKey, cancellationToken); } public virtual async Task RemoveTokenValidityKeyAsync( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { await AbpUserStore.RemoveTokenValidityKeyAsync(user, tokenValidityKey, cancellationToken); } public virtual void RemoveTokenValidityKey( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { AbpUserStore.RemoveTokenValidityKey(user, tokenValidityKey, cancellationToken); } public bool IsLockedOut(string userId) { var user = AbpUserStore.FindById(userId); if (user == null) { throw new AbpException("There is no user with id: " + userId); } var lockoutEndDateUtc = AbpUserStore.GetLockoutEndDate(user); return lockoutEndDateUtc > DateTimeOffset.UtcNow; } public bool IsLockedOut(TUser user) { var lockoutEndDateUtc = AbpUserStore.GetLockoutEndDate(user); return lockoutEndDateUtc > DateTimeOffset.UtcNow; } public void ResetAccessFailedCount(TUser user) { AbpUserStore.ResetAccessFailedCount(user); } } }
/* * 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 Lucene.Net.Attributes; using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using System.Collections; namespace Lucene.Net.Util { using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; [TestFixture] public class TestOpenBitSet : BaseDocIdSetTestCase<OpenBitSet> { public override OpenBitSet CopyOf(BitArray bs, int length) { OpenBitSet set = new OpenBitSet(length); for (int doc = bs.NextSetBit(0); doc != -1; doc = bs.NextSetBit(doc + 1)) { set.Set(doc); } return set; } internal virtual void DoGet(BitArray a, OpenBitSet b) { int max = a.Length; for (int i = 0; i < max; i++) { if (a.SafeGet(i) != b.Get(i)) { Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.SafeGet(i)); } if (a.SafeGet(i) != b.Get((long)i)) { Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.SafeGet(i)); } } } internal virtual void DoGetFast(BitArray a, OpenBitSet b, int max) { for (int i = 0; i < max; i++) { if (a.SafeGet(i) != b.FastGet(i)) { Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.SafeGet(i)); } if (a.SafeGet(i) != b.FastGet((long)i)) { Assert.Fail("mismatch: BitSet=[" + i + "]=" + a.SafeGet(i)); } } } internal virtual void DoNextSetBit(BitArray a, OpenBitSet b) { int aa = -1, bb = -1; do { aa = a.NextSetBit(aa + 1); bb = b.NextSetBit(bb + 1); Assert.AreEqual(aa, bb); } while (aa >= 0); } internal virtual void DoNextSetBitLong(BitArray a, OpenBitSet b) { int aa = -1, bb = -1; do { aa = a.NextSetBit(aa + 1); bb = (int)b.NextSetBit((long)(bb + 1)); Assert.AreEqual(aa, bb); } while (aa >= 0); } internal virtual void DoPrevSetBit(BitArray a, OpenBitSet b) { int aa = a.Length + Random().Next(100); int bb = aa; do { // aa = a.PrevSetBit(aa-1); aa--; while ((aa >= 0) && (!a.SafeGet(aa))) { aa--; } bb = b.PrevSetBit(bb - 1); Assert.AreEqual(aa, bb); } while (aa >= 0); } internal virtual void DoPrevSetBitLong(BitArray a, OpenBitSet b) { int aa = a.Length + Random().Next(100); int bb = aa; do { // aa = a.PrevSetBit(aa-1); aa--; while ((aa >= 0) && (!a.SafeGet(aa))) { aa--; } bb = (int)b.PrevSetBit((long)(bb - 1)); Assert.AreEqual(aa, bb); } while (aa >= 0); } // test interleaving different OpenBitSetIterator.Next()/skipTo() internal virtual void DoIterate(BitArray a, OpenBitSet b, int mode) { if (mode == 1) { DoIterate1(a, b); } if (mode == 2) { DoIterate2(a, b); } } internal virtual void DoIterate1(BitArray a, OpenBitSet b) { int aa = -1, bb = -1; OpenBitSetIterator iterator = new OpenBitSetIterator(b); do { aa = a.NextSetBit(aa + 1); bb = Random().NextBoolean() ? iterator.NextDoc() : iterator.Advance(bb + 1); Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb); } while (aa >= 0); } internal virtual void DoIterate2(BitArray a, OpenBitSet b) { int aa = -1, bb = -1; OpenBitSetIterator iterator = new OpenBitSetIterator(b); do { aa = a.NextSetBit(aa + 1); bb = Random().NextBoolean() ? iterator.NextDoc() : iterator.Advance(bb + 1); Assert.AreEqual(aa == -1 ? DocIdSetIterator.NO_MORE_DOCS : aa, bb); } while (aa >= 0); } internal virtual void DoRandomSets(int maxSize, int iter, int mode) { BitArray a0 = null; OpenBitSet b0 = null; for (int i = 0; i < iter; i++) { int sz = Random().Next(maxSize); BitArray a = new BitArray(sz); OpenBitSet b = new OpenBitSet(sz); // test the various ways of setting bits if (sz > 0) { int nOper = Random().Next(sz); for (int j = 0; j < nOper; j++) { int idx; idx = Random().Next(sz); a.SafeSet(idx, true); b.FastSet(idx); idx = Random().Next(sz); a.SafeSet(idx, true); b.FastSet((long)idx); idx = Random().Next(sz); a.SafeSet(idx, false); b.FastClear(idx); idx = Random().Next(sz); a.SafeSet(idx, false); b.FastClear((long)idx); idx = Random().Next(sz); a.SafeSet(idx, !a.SafeGet(idx)); b.FastFlip(idx); bool val = b.FlipAndGet(idx); bool val2 = b.FlipAndGet(idx); Assert.IsTrue(val != val2); idx = Random().Next(sz); a.SafeSet(idx, !a.SafeGet(idx)); b.FastFlip((long)idx); val = b.FlipAndGet((long)idx); val2 = b.FlipAndGet((long)idx); Assert.IsTrue(val != val2); val = b.GetAndSet(idx); Assert.IsTrue(val2 == val); Assert.IsTrue(b.Get(idx)); if (!val) { b.FastClear(idx); } Assert.IsTrue(b.Get(idx) == val); } } // test that the various ways of accessing the bits are equivalent DoGet(a, b); DoGetFast(a, b, sz); // test ranges, including possible extension int fromIndex, toIndex; fromIndex = Random().Next(sz + 80); toIndex = fromIndex + Random().Next((sz >> 1) + 1); BitArray aa = new BitArray(a); // C# BitArray class does not support dynamic sizing. // We have to explicitly change its size using the Length attribute. if (toIndex > aa.Length) { aa.Length = toIndex; } aa.Flip(fromIndex, toIndex); OpenBitSet bb = (OpenBitSet)b.Clone(); bb.Flip(fromIndex, toIndex); DoIterate(aa, bb, mode); // a problem here is from flip or doIterate fromIndex = Random().Next(sz + 80); toIndex = fromIndex + Random().Next((sz >> 1) + 1); aa = new BitArray(a); if (toIndex > aa.Length) { aa.Length = toIndex; } aa.Clear(fromIndex, toIndex); bb = (OpenBitSet)b.Clone(); bb.Clear(fromIndex, toIndex); DoNextSetBit(aa, bb); // a problem here is from clear() or nextSetBit DoNextSetBitLong(aa, bb); DoPrevSetBit(aa, bb); DoPrevSetBitLong(aa, bb); fromIndex = Random().Next(sz + 80); toIndex = fromIndex + Random().Next((sz >> 1) + 1); aa = new BitArray(a); if (toIndex > aa.Length) { aa.Length = toIndex; } aa.Set(fromIndex, toIndex); bb = (OpenBitSet)b.Clone(); bb.Set(fromIndex, toIndex); DoNextSetBit(aa, bb); // a problem here is from set() or nextSetBit DoNextSetBitLong(aa, bb); DoPrevSetBit(aa, bb); DoPrevSetBitLong(aa, bb); if (a0 != null) { aa = new BitArray(a); BitArray aa0 = new BitArray(a0); int largest = Math.Max(a.Length, a0.Length); aa.Length = aa0.Length = largest; // BitWiseEquals needs both arrays to be the same size for succeeding. // We could enlarge the smallest of a and a0, but then the tests below // won't test "UnequalLengths" operations. Assert.AreEqual(aa.BitWiseEquals(aa0), b.Equals(b0)); Assert.AreEqual(a.Cardinality(), b.Cardinality()); BitArray a_and = new BitArray(a); a_and = a_and.And_UnequalLengths(a0); BitArray a_or = new BitArray(a); a_or = a_or.Or_UnequalLengths(a0); BitArray a_xor = new BitArray(a); a_xor = a_xor.Xor_UnequalLengths(a0); BitArray a_andn = new BitArray(a); a_andn.AndNot(a0); OpenBitSet b_and = (OpenBitSet)b.Clone(); Assert.AreEqual(b, b_and); b_and.And(b0); OpenBitSet b_or = (OpenBitSet)b.Clone(); b_or.Or(b0); OpenBitSet b_xor = (OpenBitSet)b.Clone(); b_xor.Xor(b0); OpenBitSet b_andn = (OpenBitSet)b.Clone(); b_andn.AndNot(b0); DoIterate(a_and, b_and, mode); DoIterate(a_or, b_or, mode); DoIterate(a_xor, b_xor, mode); DoIterate(a_andn, b_andn, mode); Assert.AreEqual(a_and.Cardinality(), b_and.Cardinality()); Assert.AreEqual(a_or.Cardinality(), b_or.Cardinality()); Assert.AreEqual(a_xor.Cardinality(), b_xor.Cardinality()); Assert.AreEqual(a_andn.Cardinality(), b_andn.Cardinality()); // test non-mutating popcounts Assert.AreEqual(b_and.Cardinality(), OpenBitSet.IntersectionCount(b, b0)); Assert.AreEqual(b_or.Cardinality(), OpenBitSet.UnionCount(b, b0)); Assert.AreEqual(b_xor.Cardinality(), OpenBitSet.XorCount(b, b0)); Assert.AreEqual(b_andn.Cardinality(), OpenBitSet.AndNotCount(b, b0)); } a0 = a; b0 = b; } } // large enough to flush obvious bugs, small enough to run in <.5 sec as part of a // larger testsuite. [Test, LongRunningTest] public virtual void TestSmall() { DoRandomSets(AtLeast(1200), AtLeast(1000), 1); DoRandomSets(AtLeast(1200), AtLeast(1000), 2); } [Test, LuceneNetSpecific] public void TestClearSmall() { OpenBitSet a = new OpenBitSet(30); // 0110010111001000101101001001110...0 int[] onesA = { 1, 2, 5, 7, 8, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 }; for (int i = 0; i < onesA.size(); i++) { a.Set(onesA[i]); } OpenBitSet b = new OpenBitSet(30); // 0110000001001000101101001001110...0 int[] onesB = { 1, 2, 9, 12, 16, 18, 19, 21, 24, 27, 28, 29 }; for (int i = 0; i < onesB.size(); i++) { b.Set(onesB[i]); } a.Clear(5, 9); Assert.True(a.Equals(b)); a.Clear(9, 10); Assert.False(a.Equals(b)); a.Set(9); Assert.True(a.Equals(b)); } [Test, LuceneNetSpecific] public void TestClearLarge() { int iters = AtLeast(1000); for (int it = 0; it < iters; it++) { Random random = new Random(); int sz = AtLeast(1200); OpenBitSet a = new OpenBitSet(sz); OpenBitSet b = new OpenBitSet(sz); int from = random.Next(sz - 1); int to = random.Next(from, sz); for (int i = 0; i < sz / 2; i++) { int index = random.Next(sz - 1); a.Set(index); if (index < from || index >= to) { b.Set(index); } } a.Clear(from, to); Assert.True(a.Equals(b)); } } // uncomment to run a bigger test (~2 minutes). /* public void TestBig() { doRandomSets(2000,200000, 1); doRandomSets(2000,200000, 2); } */ [Test] public virtual void TestEquals() { OpenBitSet b1 = new OpenBitSet(1111); OpenBitSet b2 = new OpenBitSet(2222); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); b1.Set(10); Assert.IsFalse(b1.Equals(b2)); Assert.IsFalse(b2.Equals(b1)); b2.Set(10); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); b2.Set(2221); Assert.IsFalse(b1.Equals(b2)); Assert.IsFalse(b2.Equals(b1)); b1.Set(2221); Assert.IsTrue(b1.Equals(b2)); Assert.IsTrue(b2.Equals(b1)); // try different type of object Assert.IsFalse(b1.Equals(new object())); } [Test] public virtual void TestHashCodeEquals() { OpenBitSet bs1 = new OpenBitSet(200); OpenBitSet bs2 = new OpenBitSet(64); bs1.Set(3); bs2.Set(3); Assert.AreEqual(bs1, bs2); Assert.AreEqual(bs1.GetHashCode(), bs2.GetHashCode()); } private OpenBitSet MakeOpenBitSet(int[] a) { OpenBitSet bs = new OpenBitSet(); foreach (int e in a) { bs.Set(e); } return bs; } private BitArray MakeBitSet(int[] a) { BitArray bs = new BitArray(a.Length); foreach (int e in a) { bs.SafeSet(e, true); } return bs; } private void CheckPrevSetBitArray(int[] a) { OpenBitSet obs = MakeOpenBitSet(a); BitArray bs = MakeBitSet(a); DoPrevSetBit(bs, obs); } [Test] public virtual void TestPrevSetBit() { CheckPrevSetBitArray(new int[] { }); CheckPrevSetBitArray(new int[] { 0 }); CheckPrevSetBitArray(new int[] { 0, 2 }); } [Test] public virtual void TestEnsureCapacity() { OpenBitSet bits = new OpenBitSet(1); int bit = Random().Next(100) + 10; bits.EnsureCapacity(bit); // make room for more bits bits.FastSet(bit - 1); Assert.IsTrue(bits.FastGet(bit - 1)); bits.EnsureCapacity(bit + 1); bits.FastSet(bit); Assert.IsTrue(bits.FastGet(bit)); bits.EnsureCapacity(3); // should not change numBits nor grow the array bits.FastSet(3); Assert.IsTrue(bits.FastGet(3)); bits.FastSet(bit - 1); Assert.IsTrue(bits.FastGet(bit - 1)); // test ensureCapacityWords int numWords = Random().Next(10) + 2; // make sure we grow the array (at least 128 bits) bits.EnsureCapacityWords(numWords); bit = TestUtil.NextInt(Random(), 127, (numWords << 6) - 1); // pick a bit >= to 128, but still within range bits.FastSet(bit); Assert.IsTrue(bits.FastGet(bit)); bits.FastClear(bit); Assert.IsFalse(bits.FastGet(bit)); bits.FastFlip(bit); Assert.IsTrue(bits.FastGet(bit)); bits.EnsureCapacityWords(2); // should not change numBits nor grow the array bits.FastSet(3); Assert.IsTrue(bits.FastGet(3)); bits.FastSet(bit - 1); Assert.IsTrue(bits.FastGet(bit - 1)); } #region BaseDocIdSetTestCase<T> // LUCENENET NOTE: Tests in an abstract base class are not pulled into the correct // context in Visual Studio. This fixes that with the minimum amount of code necessary // to run them in the correct context without duplicating all of the tests. /// <summary> /// Test length=0. /// </summary> [Test] public override void TestNoBit() { base.TestNoBit(); } /// <summary> /// Test length=1. /// </summary> [Test] public override void Test1Bit() { base.Test1Bit(); } /// <summary> /// Test length=2. /// </summary> [Test] public override void Test2Bits() { base.Test2Bits(); } /// <summary> /// Compare the content of the set against a <seealso cref="BitSet"/>. /// </summary> [Test, LongRunningTest] public override void TestAgainstBitSet() { base.TestAgainstBitSet(); } #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. /****************************************************************************** * 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 BroadcastScalarToVector128Double() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Double(); 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 SimpleUnaryOpTest__BroadcastScalarToVector128Double { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar; private Vector128<Double> _fld; private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable; static SimpleUnaryOpTest__BroadcastScalarToVector128Double() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__BroadcastScalarToVector128Double() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.BroadcastScalarToVector128<Double>( Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.BroadcastScalarToVector128<Double>( Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.BroadcastScalarToVector128<Double>( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Double) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Double) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Double) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.BroadcastScalarToVector128<Double>( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr); var result = Avx2.BroadcastScalarToVector128<Double>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr)); var result = Avx2.BroadcastScalarToVector128<Double>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr)); var result = Avx2.BroadcastScalarToVector128<Double>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Double(); var result = Avx2.BroadcastScalarToVector128<Double>(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.BroadcastScalarToVector128<Double>(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(firstOp[0]) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((BitConverter.DoubleToInt64Bits(firstOp[0]) != BitConverter.DoubleToInt64Bits(result[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<Double>(Vector128<Double>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using System.Threading; #if __UNIFIED__ using CoreLocation; using Foundation; using UIKit; #else using MonoTouch.CoreLocation; using MonoTouch.Foundation; using MonoTouch.UIKit; #endif using Geolocator.Plugin.Abstractions; namespace Geolocator.Plugin { /// <summary> /// Implementation for Geolocator /// </summary> public class GeolocatorImplementation : IGeolocator { public GeolocatorImplementation() { DesiredAccuracy = 50; this.manager = GetManager(); this.manager.AuthorizationChanged += OnAuthorizationChanged; this.manager.Failed += OnFailed; if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) this.manager.LocationsUpdated += OnLocationsUpdated; else this.manager.UpdatedLocation += OnUpdatedLocation; this.manager.UpdatedHeading += OnUpdatedHeading; RequestAuthorization(); } private void RequestAuthorization() { var info = NSBundle.MainBundle.InfoDictionary; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { if (info.ContainsKey(new NSString("NSLocationWhenInUseUsageDescription"))) this.manager.RequestWhenInUseAuthorization(); else if (info.ContainsKey(new NSString("NSLocationAlwaysUsageDescription"))) this.manager.RequestAlwaysAuthorization(); else throw new UnauthorizedAccessException("On iOS 8.0 and higher you must set either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in your Info.plist file to enable Authorization Requests for Location updates!"); } } /// <inheritdoc/> public event EventHandler<PositionErrorEventArgs> PositionError; /// <inheritdoc/> public event EventHandler<PositionEventArgs> PositionChanged; /// <inheritdoc/> public double DesiredAccuracy { get; set; } /// <inheritdoc/> public bool IsListening { get { return this.isListening; } } /// <inheritdoc/> public bool SupportsHeading { get { return CLLocationManager.HeadingAvailable; } } /// <inheritdoc/> public bool IsGeolocationAvailable { get { return true; } // all iOS devices support at least wifi geolocation } /// <inheritdoc/> public bool IsGeolocationEnabled { get { var status = CLLocationManager.Status; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { return status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.AuthorizedWhenInUse; } else { return status == CLAuthorizationStatus.Authorized; } } } /// <inheritdoc/> public Task<Position> GetPositionAsync (int timeout = Timeout.Infinite, CancellationToken? cancelToken = null, bool includeHeading = false) { if (timeout <= 0 && timeout != Timeout.Infinite) throw new ArgumentOutOfRangeException ("timeout", "Timeout must be positive or Timeout.Infinite"); if (!cancelToken.HasValue) cancelToken = CancellationToken.None; ; TaskCompletionSource<Position> tcs; if (!IsListening) { var m = GetManager(); tcs = new TaskCompletionSource<Position> (m); var singleListener = new GeolocationSingleUpdateDelegate (m, DesiredAccuracy, includeHeading, timeout, cancelToken.Value); m.Delegate = singleListener; m.StartUpdatingLocation (); if (includeHeading && SupportsHeading) m.StartUpdatingHeading (); return singleListener.Task; } else { tcs = new TaskCompletionSource<Position>(); if (this.position == null) { EventHandler<PositionErrorEventArgs> gotError = null; gotError = (s,e) => { tcs.TrySetException (new GeolocationException (e.Error)); PositionError -= gotError; }; PositionError += gotError; EventHandler<PositionEventArgs> gotPosition = null; gotPosition = (s, e) => { tcs.TrySetResult (e.Position); PositionChanged -= gotPosition; }; PositionChanged += gotPosition; } else tcs.SetResult (this.position); } return tcs.Task; } /// <inheritdoc/> public void StartListening (int minTime, double minDistance, bool includeHeading = false) { if (minTime < 0) throw new ArgumentOutOfRangeException ("minTime"); if (minDistance < 0) throw new ArgumentOutOfRangeException ("minDistance"); if (this.isListening) throw new InvalidOperationException ("Already listening"); this.isListening = true; this.manager.DesiredAccuracy = DesiredAccuracy; this.manager.DistanceFilter = minDistance; this.manager.StartUpdatingLocation (); if (includeHeading && CLLocationManager.HeadingAvailable) this.manager.StartUpdatingHeading (); } /// <inheritdoc/> public void StopListening () { if (!this.isListening) return; this.isListening = false; if (CLLocationManager.HeadingAvailable) this.manager.StopUpdatingHeading (); this.manager.StopUpdatingLocation (); this.position = null; } private readonly CLLocationManager manager; private bool isListening; private Position position; private CLLocationManager GetManager() { CLLocationManager m = null; new NSObject().InvokeOnMainThread (() => m = new CLLocationManager()); return m; } private void OnUpdatedHeading (object sender, CLHeadingUpdatedEventArgs e) { if (e.NewHeading.TrueHeading == -1) return; Position p = (this.position == null) ? new Position () : new Position (this.position); p.Heading = e.NewHeading.TrueHeading; this.position = p; OnPositionChanged (new PositionEventArgs (p)); } private void OnLocationsUpdated (object sender, CLLocationsUpdatedEventArgs e) { foreach (CLLocation location in e.Locations) UpdatePosition (location); } private void OnUpdatedLocation (object sender, CLLocationUpdatedEventArgs e) { UpdatePosition (e.NewLocation); } private void UpdatePosition (CLLocation location) { Position p = (this.position == null) ? new Position () : new Position (this.position); if (location.HorizontalAccuracy > -1) { p.Accuracy = location.HorizontalAccuracy; p.Latitude = location.Coordinate.Latitude; p.Longitude = location.Coordinate.Longitude; } if (location.VerticalAccuracy > -1) { p.Altitude = location.Altitude; p.AltitudeAccuracy = location.VerticalAccuracy; } if (location.Speed > -1) p.Speed = location.Speed; var dateTime = DateTime.SpecifyKind(location.Timestamp.ToDateTime(), DateTimeKind.Unspecified); p.Timestamp = new DateTimeOffset (dateTime); this.position = p; OnPositionChanged (new PositionEventArgs (p)); location.Dispose(); } private void OnFailed (object sender, NSErrorEventArgs e) { if ((CLError)(int)e.Error.Code == CLError.Network) OnPositionError (new PositionErrorEventArgs (GeolocationError.PositionUnavailable)); } private void OnAuthorizationChanged (object sender, CLAuthorizationChangedEventArgs e) { if (e.Status == CLAuthorizationStatus.Denied || e.Status == CLAuthorizationStatus.Restricted) OnPositionError (new PositionErrorEventArgs (GeolocationError.Unauthorized)); } private void OnPositionChanged (PositionEventArgs e) { var changed = PositionChanged; if (changed != null) changed (this, e); } private void OnPositionError (PositionErrorEventArgs e) { StopListening(); var error = PositionError; if (error != null) error (this, e); } } }